From 55e7beb6de9fcc8817d40d0a663857e3553c3632 Mon Sep 17 00:00:00 2001 From: Isaac W Date: Wed, 25 Nov 2026 06:38:17 +1000 Subject: [PATCH 001/258] D3D12.X: a draw does not wait for a graphics pipeline still being built pso_async means a graphics pipeline still being built to go on with its stand-in, which draws nothing, while a worker builds it; only compute pipelines are waited for (a skipped dispatch would leave its outputs unwritten). But graphics_bound and ExecuteIndirect called resolve_wait, which waits for the build - and builds it on the title's thread when no worker has started it. With lazy pipelines that is every graphics pipeline's first draw. On an NVIDIA GPU the retail title of #505 had its threads held 1 - 5 s per draw in the driver's compiler as its world loaded: 25 graphics binds, 33.2 s in all within 25 s (counted with #899's log), and its hang watchdog ended the run. A test report on #889 (RTX 4080) found a title thread held in bind::execute_indirect -> resolve_wait at the abort. Draws and ExecuteIndirect now take their pipeline with resolve_for_bind: a graphics one still being built goes to the workers and the draw uses its stand-in (ExecuteIndirect skips, as it already did for a pending one); a compute one is waited for as before. With this, the same world load logged no graphics wait. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 42 ++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index da5b15ef42..27719d80e7 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -253,7 +253,7 @@ fn signature_dispatches(sig: usize) -> bool { pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); - let pso = super::pso_async::resolve_wait(with(this, |s| s.pso)); + let pso = pso_for_draw(with(this, |s| s.pso)); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if !gfx && !compute { @@ -489,14 +489,23 @@ pub(super) unsafe fn emit_prepared_indexed_draw( list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); } +/// The pipeline a draw (or an ExecuteIndirect) uses now: a graphics pipeline still being built +/// is not waited for – its build goes to the workers and its stand-in, which draws nothing, is +/// used until it is built (`pso_async`). A compute one is waited for. Waiting held a retail +/// title's threads 1 – 5 s per draw in the driver's compiler (33 s in all as its world loaded, +/// on an NVIDIA GPU), and its hang watchdog ended it. +fn pso_for_draw(pso: usize) -> usize { + super::pso_async::resolve_for_bind(pso) +} + /// Before a draw: with a translated pipeline its ABI root signature and the kept graphics /// arguments are bound (None: the draw is skipped – a console pipeline without a /// translation, or no unified memory). unsafe fn graphics_bound(this: *mut c_void) -> Option { let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); - // a pipeline still being built in the background is waited for (its stand-in draws nothing) - if !super::real::is_translated_graphics(super::pso_async::resolve_wait(pso)) { + // a pipeline still being built in the background is not waited for (`pso_for_draw`) + if !super::real::is_translated_graphics(pso_for_draw(pso)) { count(DRAWS_PC); if super::present::trace_frame() { // which pipelines draw without a translation (first 12 distinct) @@ -504,7 +513,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option let mut g = SEEN.lock().unwrap(); if !g.contains(&pso) && g.len() < 12 { g.push(pso); - let real = super::pso_async::resolve_wait(pso); + let real = super::pso_async::resolve(pso); crate::xlog_info!( "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", super::pso_async::is_pending(pso), @@ -1178,6 +1187,31 @@ void main(uint t : SV_GroupIndex) { } } + /// A draw does not wait for a graphics pipeline still being built: its build goes to the + /// workers and the draw gets the stand-in at once; once built, the real one. A compute + /// pipeline is still waited for. + #[test] + fn a_draw_does_not_wait_for_a_graphics_pipeline_still_being_built() { + let (graphics, compute) = (0x7E57_6101usize, 0x7E57_6102usize); + pso_async::submit_lazy(graphics, false, Box::new(|| { + std::thread::sleep(std::time::Duration::from_millis(1500)); + 0x1301 + }), 0); + pso_async::submit_lazy(compute, true, Box::new(|| 0x1302), 0); + let t = std::time::Instant::now(); + assert_eq!(pso_for_draw(graphics), graphics, "the stand-in, not the real one"); + assert!(t.elapsed() < std::time::Duration::from_millis(500), "a draw waited {:?}", t.elapsed()); + // the draw sent it to the workers: it is built with no further draw + let start = std::time::Instant::now(); + while pso_async::is_pending(graphics) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(pso_for_draw(graphics), 0x1301, "built by a worker"); + assert_eq!(pso_for_draw(compute), 0x1302, "a compute pipeline is waited for"); + pso_async::released(graphics); + pso_async::released(compute); + } + /// Minimal RTS0 v2 root signature blob with one 4-constant parameter. fn test_rts0_blob() -> Vec { let words: [u32; 12] = [ From 03ceddb0be3d06287ca21ae800dbb0d7f98049e7 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:39:31 +0530 Subject: [PATCH 002/258] kernelx: physical pages as section slices that can be mapped at many addresses On the console a physical page mapped at several addresses is one page. XCL keeps a page at one address at a time and copies it when the title maps it elsewhere (`move_away`), so the other addresses go stale; a retail title maps its streamed pages into a pool, into the CPU view of a 24 GB reservation and into that reservation's GPU view (#1031). `kernelx::sections` is the base for real aliasing: a block of physical pages is one pagefile-backed SEC_RESERVE section, and a page is mapped as a view of its 64 KiB slice into a placeholder (MapViewOfFile3 with MEM_REPLACE_PLACEHOLDER). Every view of a slice is the same memory and a page takes commit once, when it is committed through any view. Unmapping leaves a placeholder for the next view. Ordinary reserved memory (write-watched if asked) can replace part of a placeholder and go back to one. Nothing calls it yet. Measured in a standalone program on Windows 11 26200 over 200 000 pages: map 2.2 us, unmap 2.75 us, commit 0.9 us a page. GetWriteWatch refuses a range that holds a view (error 87), and one call cannot span two neighbouring reservations either. --- crates/xcl/src/hle/kernelx.rs | 2 + crates/xcl/src/hle/kernelx/sections.rs | 308 +++++++++++++++++++++++++ 2 files changed, 310 insertions(+) create mode 100644 crates/xcl/src/hle/kernelx/sections.rs diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index afa86c30c8..c7fb934db9 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -109,6 +109,8 @@ pub fn exports() -> Vec<(&'static str, usize)> { pub const MEM_GRAPHICS: u32 = 0x1000_0000; mod placeholders; pub mod lazy; +#[allow(dead_code)] // used once physical pages alias (`XCL_PAGE_ALIAS`) +pub mod sections; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; const STD_PROTECT_MASK: u32 = 0xFF | 0x100 | 0x200 | 0x400; diff --git a/crates/xcl/src/hle/kernelx/sections.rs b/crates/xcl/src/hle/kernelx/sections.rs new file mode 100644 index 0000000000..9935686253 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/sections.rs @@ -0,0 +1,308 @@ +//! Physical pages that show at every address they are mapped at. +//! +//! On the console a physical page mapped at several addresses is one page: a write through one +//! address is read at all of them. A retail title maps its streamed pages into a pool, into the +//! CPU view of a 24 GB reservation and, through its queue, into that reservation's GPU view. +//! Here a block of physical pages is one pagefile-backed section, and mapping a page puts a view +//! of its 64 KiB slice into a placeholder at the address: every view of the slice is the same +//! memory, with no copy. The section is `SEC_RESERVE`, so a page takes commit only once it is +//! committed through one of its views, and then once for all of them. +//! +//! Address space that may hold such views is reserved as a placeholder (`reserve`). A view +//! replaces the placeholder at its address (`map`); unmapping it leaves a placeholder again +//! (`unmap`), ready for the next view. Ordinary memory can replace part of a placeholder too +//! (`replace_with_reservation`), write-watched if asked – but `GetWriteWatch` refuses a range +//! that holds a view, so the watch must ask about such reservations one by one. + +use std::ffi::c_void; + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MapViewOfFile3, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, VirtualQuery, MEMORY_BASIC_INFORMATION, + MEMORY_MAPPED_VIEW_ADDRESS, MEM_COMMIT, MEM_PRESERVE_PLACEHOLDER, MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, + MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, PAGE_READWRITE, SEC_RESERVE, VIRTUAL_ALLOCATION_TYPE, +}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; + +/// One console physical page (64 KiB, the Windows allocation granularity too). +pub const PAGE: usize = 0x1_0000; + +const MEM_WRITE_WATCH: VIRTUAL_ALLOCATION_TYPE = 0x20_0000; + +/// A block of physical pages: one pagefile-backed section of `pages` 64 KiB pages. +pub struct Section { + handle: HANDLE, + pages: usize, +} + +// SAFETY: a section handle may be used from any thread; the section itself is kernel state. +unsafe impl Send for Section {} +unsafe impl Sync for Section {} + +impl Section { + /// A section of `pages` pages, none committed. None if Windows refuses it. + pub fn new(pages: usize) -> Option
{ + let bytes = pages.checked_mul(PAGE).filter(|&b| b > 0)?; + // SAFETY: a pagefile-backed mapping with no name and default security. + let handle = unsafe { CreateFileMappingW(INVALID_HANDLE_VALUE, std::ptr::null(), PAGE_READWRITE | SEC_RESERVE, (bytes >> 32) as u32, bytes as u32, std::ptr::null()) }; + (!handle.is_null()).then_some(Section { handle, pages }) + } + + pub fn pages(&self) -> usize { + self.pages + } + + /// Map pages `first..first + n` of the section at `at`, which must be a placeholder or lie in + /// one (`reserve`). The view is one Windows mapping: `unmap` takes all of it at once. + /// + /// # Safety + /// `[at, at + n * PAGE)` must be address space the caller owns as a placeholder. + pub unsafe fn map(&self, first: usize, n: usize, at: usize) -> bool { + if n == 0 || first.checked_add(n).is_none_or(|end| end > self.pages) || !at.is_multiple_of(PAGE) { + return false; + } + let len = n * PAGE; + if !split(at, len) { + return false; + } + let v = MapViewOfFile3(self.handle, GetCurrentProcess(), at as *const c_void, (first * PAGE) as u64, len, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, std::ptr::null_mut(), 0); + v.Value as usize == at + } +} + +impl Drop for Section { + fn drop(&mut self) { + // views still mapped keep the section alive until they are unmapped + // SAFETY: the handle is ours and closed once. + unsafe { CloseHandle(self.handle) }; + } +} + +/// Reserve `len` bytes of placeholder address space, at `at` if given. None if it is taken. +/// +/// # Safety +/// Only reserves address space; the caller releases it with `release`. +pub unsafe fn reserve(at: Option, len: usize) -> Option { + if len == 0 || !len.is_multiple_of(PAGE) { + return None; + } + let want = at.unwrap_or(0); + let p = VirtualAlloc2(GetCurrentProcess(), want as *const c_void, len, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, std::ptr::null_mut(), 0) as usize; + (p != 0 && (at.is_none() || p == want)).then_some(p) +} + +/// The allocation `p` lies in: (base, size, state, type), from one VirtualQuery. +fn allocation_at(p: usize) -> Option<(usize, usize, u32, u32)> { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + if unsafe { VirtualQuery(p as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return None; + } + Some((m.AllocationBase as usize, m.RegionSize, m.State, m.Type)) +} + +/// Make `[at, at + len)` a placeholder of its own, splitting the placeholder it lies in. True if +/// it is one now (already exactly one, too). +/// +/// # Safety +/// `[at, at + len)` must lie in one placeholder the caller owns. +pub unsafe fn split(at: usize, len: usize) -> bool { + match allocation_at(at) { + // a placeholder is a reservation (MEM_RESERVE) with no protection; one that is already + // exactly this range cannot be split again – it is what was asked for + Some((base, size, MEM_RESERVE, _)) if base == at && size == len => true, + Some((_, _, MEM_RESERVE, _)) => VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0, + _ => false, + } +} + +/// Unmap the view at `at` (all of it) and leave a placeholder in its place. +/// +/// # Safety +/// `at` must be the start of a view made by `Section::map`. +pub unsafe fn unmap(at: usize) -> bool { + UnmapViewOfFile2(GetCurrentProcess(), MEMORY_MAPPED_VIEW_ADDRESS { Value: at as *mut c_void }, MEM_PRESERVE_PLACEHOLDER) != 0 +} + +/// Commit `[at, at + len)` of a view: the section's pages there are committed for every view of +/// them. True if they are committed now. +/// +/// # Safety +/// The range must lie in views made by `Section::map`. +pub unsafe fn commit(at: usize, len: usize) -> bool { + !VirtualAlloc(at as *const c_void, len, MEM_COMMIT, PAGE_READWRITE).is_null() +} + +/// Ordinary reserved memory in place of `[at, at + len)` of a placeholder, write-watched if +/// `write_watch` (commit it with `VirtualAlloc` as usual). +/// +/// # Safety +/// `[at, at + len)` must lie in one placeholder the caller owns. +pub unsafe fn replace_with_reservation(at: usize, len: usize, write_watch: bool) -> bool { + if !split(at, len) { + return false; + } + let t = MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | if write_watch { MEM_WRITE_WATCH } else { 0 }; + VirtualAlloc2(GetCurrentProcess(), at as *const c_void, len, t, PAGE_READWRITE, std::ptr::null_mut(), 0) as usize == at +} + +/// Turn the reservation `replace_with_reservation` made at `[at, at + len)` back into a +/// placeholder (what was committed there is gone). +/// +/// # Safety +/// `[at, at + len)` must be exactly such a reservation. +pub unsafe fn reservation_to_placeholder(at: usize, len: usize) -> bool { + VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0 +} + +/// Release the placeholder at `at` (its whole extent; views in it must be unmapped first). +/// +/// # Safety +/// `at` must be the start of a placeholder the caller owns. +pub unsafe fn release(at: usize) -> bool { + VirtualFree(at as *mut c_void, 0, MEM_RELEASE) != 0 +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::System::Memory::{GetWriteWatch, MEM_MAPPED}; + + /// Placeholder address space for a test, released at the end (views unmapped first by the test). + struct Space(usize, usize); + impl Space { + fn new(pages: usize) -> Space { + let len = pages * PAGE; + Space(unsafe { reserve(None, len) }.expect("placeholder"), len) + } + fn at(&self, i: usize) -> usize { + self.0 + i * PAGE + } + } + impl Drop for Space { + fn drop(&mut self) { + // the test leaves placeholders behind; release each piece + let mut p = self.0; + while p < self.0 + self.1 { + let (base, size, _, _) = allocation_at(p).unwrap(); + assert_eq!(base, p); + unsafe { release(p) }; + p += size; + } + } + } + + unsafe fn read(at: usize) -> u64 { + std::ptr::read_volatile(at as *const u64) + } + + unsafe fn write(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + #[test] + fn a_page_mapped_at_two_addresses_is_one_page() { + let s = Section::new(8).unwrap(); + let space = Space::new(16); + unsafe { + assert!(s.map(5, 1, space.at(2))); + assert!(s.map(5, 1, space.at(11))); + assert!(commit(space.at(2), PAGE)); + write(space.at(2) + 0x40, 0xDEAD_BEEF); + assert_eq!(read(space.at(11) + 0x40), 0xDEAD_BEEF, "a write at one address is read at the other"); + write(space.at(11) + 0x40, 7); + assert_eq!(read(space.at(2) + 0x40), 7); + assert_eq!(allocation_at(space.at(11)).unwrap().3, MEM_MAPPED); + assert!(unmap(space.at(2)) && unmap(space.at(11))); + } + } + + #[test] + fn committing_through_one_view_commits_the_page_for_all() { + let s = Section::new(2).unwrap(); + let space = Space::new(4); + unsafe { + assert!(s.map(1, 1, space.at(0))); + assert!(s.map(1, 1, space.at(3))); + assert_eq!(allocation_at(space.at(3)).unwrap().2, MEM_RESERVE, "a page is not committed before it is used"); + assert!(commit(space.at(0), PAGE)); + assert_eq!(allocation_at(space.at(3)).unwrap().2, MEM_COMMIT); + assert_eq!(read(space.at(3)), 0, "a new page reads zeros"); + assert!(unmap(space.at(0)) && unmap(space.at(3))); + } + } + + #[test] + fn unmapping_leaves_a_placeholder_for_the_next_page() { + let s = Section::new(4).unwrap(); + let space = Space::new(2); + unsafe { + assert!(s.map(0, 1, space.at(1)) && commit(space.at(1), PAGE)); + write(space.at(1), 1); + assert!(unmap(space.at(1))); + let (base, size, state, _) = allocation_at(space.at(1)).unwrap(); + assert_eq!((base, size, state), (space.at(1), PAGE, MEM_RESERVE), "a placeholder of the page's size is left"); + assert!(s.map(3, 1, space.at(1)) && commit(space.at(1), PAGE)); + assert_eq!(read(space.at(1)), 0, "the other page is there now"); + // the first page kept its contents while it was mapped nowhere + assert!(s.map(0, 1, space.at(0))); + assert_eq!(read(space.at(0)), 1); + assert!(unmap(space.at(0)) && unmap(space.at(1))); + } + } + + #[test] + fn a_run_of_pages_is_one_view() { + let s = Section::new(8).unwrap(); + let space = Space::new(8); + unsafe { + assert!(s.map(2, 4, space.at(1))); + assert_eq!(allocation_at(space.at(1)).unwrap().0, space.at(1)); + assert_eq!(allocation_at(space.at(4)).unwrap().0, space.at(1), "one view covers the run"); + assert!(commit(space.at(1), 4 * PAGE)); + assert!(s.map(4, 1, space.at(7))); + write(space.at(3), 42); // page 4 of the section, third of the run + assert_eq!(read(space.at(7)), 42); + assert!(!s.map(6, 4, space.at(0)), "pages past the end of the section are refused"); + assert!(unmap(space.at(1)) && unmap(space.at(7))); + } + } + + #[test] + fn write_watched_memory_lives_beside_views_in_one_placeholder() { + let s = Section::new(1).unwrap(); + let space = Space::new(8); + unsafe { + assert!(replace_with_reservation(space.at(0), 4 * PAGE, true)); + assert!(!VirtualAlloc(space.at(0) as *const c_void, 4 * PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert!(s.map(0, 1, space.at(6)) && commit(space.at(6), PAGE)); + write(space.at(1), 1); + write(space.at(6), 2); + let mut out = [std::ptr::null_mut::(); 64]; + let (mut n, mut gran) = (out.len(), 0u32); + assert_eq!(GetWriteWatch(1, space.at(0) as *const c_void, 4 * PAGE, out.as_mut_ptr(), &mut n, &mut gran), 0); + assert_eq!((n, out[0] as usize), (1, space.at(1)), "the write-watched reservation reports its write"); + let mut n = out.len(); + assert_ne!(GetWriteWatch(0, space.at(0) as *const c_void, 8 * PAGE, out.as_mut_ptr(), &mut n, &mut gran), 0, "a range with a view in it is refused"); + assert!(reservation_to_placeholder(space.at(0), 4 * PAGE)); + assert_eq!(allocation_at(space.at(0)).unwrap().2, MEM_RESERVE); + assert!(unmap(space.at(6))); + } + } + + #[test] + fn splitting_a_range_that_is_already_a_placeholder_is_a_no_op() { + let space = Space::new(3); + unsafe { + assert!(split(space.at(1), PAGE)); + assert!(split(space.at(1), PAGE)); + assert_eq!(allocation_at(space.at(1)).unwrap().0, space.at(1)); + assert_eq!(allocation_at(space.at(2)).unwrap().0, space.at(2)); + } + } + + #[test] + fn a_section_of_no_pages_is_refused() { + assert!(Section::new(0).is_none()); + } +} From 51ee197c69a3ba6ff37740457d4ecd39968c6e89 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:20:10 +0100 Subject: [PATCH 003/258] D3D12.X: add depth+UAV color twins and format-aliased placed texture copies --- crates/xcl/src/hle/d3d12x/bind.rs | 21 +- crates/xcl/src/hle/d3d12x/depth_uav.rs | 2743 +++++++++++++++++++++ crates/xcl/src/hle/d3d12x/device_x.rs | 45 +- crates/xcl/src/hle/d3d12x/format_alias.rs | 1282 ++++++++++ crates/xcl/src/hle/d3d12x/late_release.rs | 9 +- crates/xcl/src/hle/d3d12x/list_x.rs | 211 +- crates/xcl/src/hle/d3d12x/mod.rs | 2 + crates/xcl/src/hle/d3d12x/real.rs | 118 +- 8 files changed, 4341 insertions(+), 90 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/depth_uav.rs create mode 100644 crates/xcl/src/hle/d3d12x/format_alias.rs diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index c888e6325d..c07fbbe277 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -28,6 +28,8 @@ struct State { /// the title's graphics root signature (a PC object), bound before a draw with an /// untranslated pipeline – created with it – since SetGraphicsRootSignature binds nothing rs_gfx: usize, + /// the title's compute root signature (a PC object), preserved for internal-pass restoration + rs_cs: usize, pso: usize, allocator: usize, /// unified memory of this recording (io, argument tables) @@ -82,6 +84,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + s.rs_cs = 0; (old, std::mem::take(&mut s.uma)) }); console_list::hold_until_reset(old, blocks); @@ -97,6 +100,7 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + s.rs_cs = 0; }); } @@ -104,8 +108,8 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { /// deferred mid-list split (`to` records into `allocator` with its own fresh UMA arena while /// `from` retains its previously allocated blocks until `allocator` resets). pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { - let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { - (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) + let (layout, args, layout_gfx, args_gfx, rs_gfx, rs_cs, pso) = with(from, |s| { + (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.rs_cs, s.pso) }); let (old, blocks) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, allocator); @@ -115,6 +119,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.layout_gfx = layout_gfx; s.args_gfx = args_gfx; s.rs_gfx = rs_gfx; + s.rs_cs = rs_cs; s.pso = pso; (old, std::mem::take(&mut s.uma)) }); @@ -800,6 +805,7 @@ pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_voi with(this, |s| { s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; s.layout = layout; + s.rs_cs = rs as usize; }); } @@ -1046,6 +1052,17 @@ pub(super) fn tracked_pso(list: *mut c_void) -> usize { .map_or(0, |s| s.pso) } +/// Tracked console `(graphics_root_signature, compute_root_signature)` on `list` for restoring +/// PC root signatures after an internal graphics/compute sync pass. +pub(super) fn tracked_root_sigs(list: *mut c_void) -> (usize, usize) { + STATES + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .map_or((0, 0), |s| (s.rs_gfx, s.rs_cs)) +} + #[cfg(test)] mod tests { use super::super::{device_x, list_x, pso_async, real, title_list}; diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs new file mode 100644 index 0000000000..7eab5ca3f3 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -0,0 +1,2743 @@ +//! Depth-stencil + unordered-access color twins (`ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS`). +//! +//! Console titles bind depth-stencil buffers as UAVs in compute passes (for example, writing +//! tiled material classifications into depth and bitmasks into stencil, then testing them with +//! `DEPTH_READ` / `EQUAL` draws). PC D3D12 rejects `D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS` +//! on depth-stencil textures, so `device_x::pc_resource_desc` strips bit 2 (`ALLOW_UNORDERED_ACCESS`). +//! Without a writable host twin, every UAV of the depth-stencil texture becomes a null view and +//! compute writes vanish. +//! +//! This module pairs each single-sample depth+UAV texture with lazily allocated `ALLOW_UNORDERED_ACCESS` +//! color twin texture(s) (`R32_TYPELESS` / `R16_TYPELESS` for the depth plane and `R8_TYPELESS` for +//! the stencil plane on two-plane formats). Outside synchronization ops, every twin stays in +//! `D3D12_RESOURCE_STATE_UNORDERED_ACCESS` (valid on both DIRECT and COMPUTE queues). On DIRECT +//! command list transitions out of / into `UNORDERED_ACCESS` (or before `OMSetRenderTargets` binds +//! the DSV), dirty planes synchronize lazily: +//! * Single-plane `R32_TYPELESS` / `R16_TYPELESS`: direct `CopyResource`. +//! * Two-plane `R32G8X24_TYPELESS` depth (plane 0) and any two-plane stencil (plane 1): +//! per-subresource buffer-through `CopyTextureRegion` (exact bit-for-bit transfer). +//! * Two-plane `R24G8_TYPELESS` depth (plane 0, e.g. console `D16_UNORM_S8_UINT` / `D24_UNORM_S8_UINT`): +//! fullscreen depth-write pass (`SV_Depth`, stencil writes disabled) for twin -> depth and a +//! compute copy (`R24_UNORM_X8_TYPELESS` -> `R16_UNORM`/`R32_FLOAT`) for depth -> twin, +//! restoring all list graphics/descriptor bindings afterward. +//! +//! Set `XCL_DEPTH_UAV_TWIN=0` to disable color twins. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::{Interface, PCSTR}; +use windows::Win32::Foundation::RECT; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::list_x; +use super::real; + +const STATE_COMMON: u32 = 0; +const STATE_UAV: u32 = 0x8; +const STATE_DEPTH_WRITE: u32 = 0x10; +const STATE_DEPTH_READ: u32 = 0x20; +const STATE_COPY_DEST: u32 = 0x400; +const STATE_COPY_SOURCE: u32 = 0x800; +const STATE_SRV_ALL: u32 = 0x40 | 0x80; + +const FLAG_DEPTH_STENCIL: u32 = 0x2; +const FLAG_UAV: u32 = 0x4; + +/// How a depth resource's plane 0 synchronizes with its `depth_twin`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum DepthSyncKind { + /// Single-plane `R32_TYPELESS` or `R16_TYPELESS`: `CopyResource` directly. + DirectCopy, + /// Two-plane `R32G8X24_TYPELESS` plane 0 (`R32_TYPELESS`): buffer-through `CopyTextureRegion`. + BufferThrough, + /// Two-plane `R24G8_TYPELESS` plane 0: fullscreen depth-write pass (twin -> depth) and CS copy (depth -> twin). + FullscreenPass { twin_srv_fmt: i32, twin_uav_fmt: i32 }, +} + +/// Twin allocation & sync plan derived from a console resource format. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct TwinPlan { + pub depth_twin_fmt: i32, + pub stencil_twin_fmt: Option, + pub depth_sync: DepthSyncKind, + pub two_plane: bool, +} + +/// Choose the color twin format(s) and sync strategy for a console depth-stencil format. +pub(super) fn plan_for_console_format(console_fmt: u32) -> Option { + match console_fmt { + // D32_FLOAT / R32_TYPELESS + 39 | 40 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R32_TYPELESS.0, + stencil_twin_fmt: None, + depth_sync: DepthSyncKind::DirectCopy, + two_plane: false, + }), + // D16_UNORM / R16_TYPELESS + 53 | 55 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R16_TYPELESS.0, + stencil_twin_fmt: None, + depth_sync: DepthSyncKind::DirectCopy, + two_plane: false, + }), + // D32_FLOAT_S8X24_UINT / R32G8X24_TYPELESS + 19 | 20 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R32_TYPELESS.0, + stencil_twin_fmt: Some(DXGI_FORMAT_R8_TYPELESS.0), + depth_sync: DepthSyncKind::BufferThrough, + two_plane: true, + }), + // Console D16_UNORM_S8_UINT family -> PC R24G8_TYPELESS + 118..=120 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R16_TYPELESS.0, + stencil_twin_fmt: Some(DXGI_FORMAT_R8_TYPELESS.0), + depth_sync: DepthSyncKind::FullscreenPass { + twin_srv_fmt: DXGI_FORMAT_R16_UNORM.0, + twin_uav_fmt: DXGI_FORMAT_R16_UNORM.0, + }, + two_plane: true, + }), + // D24_UNORM_S8_UINT / R24G8_TYPELESS + 44 | 45 => Some(TwinPlan { + depth_twin_fmt: DXGI_FORMAT_R32_TYPELESS.0, + stencil_twin_fmt: Some(DXGI_FORMAT_R8_TYPELESS.0), + depth_sync: DepthSyncKind::FullscreenPass { + twin_srv_fmt: DXGI_FORMAT_R32_FLOAT.0, + twin_uav_fmt: DXGI_FORMAT_R32_FLOAT.0, + }, + two_plane: true, + }), + _ => None, + } +} + +/// Which plane(s) a view or barrier targets. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum PlaneMask { + Depth, + Stencil, + Both, +} + +impl PlaneMask { + fn includes_depth(self) -> bool { + matches!(self, PlaneMask::Depth | PlaneMask::Both) + } + + fn includes_stencil(self) -> bool { + matches!(self, PlaneMask::Stencil | PlaneMask::Both) + } +} + +/// Determine whether a UAV description targets the stencil plane of a two-plane depth resource. +pub(super) fn is_stencil_uav_format(fmt: u32, plane_slice: u32) -> bool { + plane_slice == 1 || matches!(fmt, 22 | 47 | 60..=64 | 120) +} + +/// Map a requested console/PC UAV format to a legal typed format on the chosen color twin. +pub(super) fn twin_uav_format(twin_typeless_fmt: i32, requested_fmt: u32) -> i32 { + match twin_typeless_fmt { + // R8_TYPELESS stencil twin + 60 => match requested_fmt { + 61 => DXGI_FORMAT_R8_UNORM.0, + 63 => DXGI_FORMAT_R8_SNORM.0, + 64 => DXGI_FORMAT_R8_SINT.0, + _ => DXGI_FORMAT_R8_UINT.0, + }, + // R16_TYPELESS depth twin + 53 => match requested_fmt { + 54 => DXGI_FORMAT_R16_FLOAT.0, + 57 => DXGI_FORMAT_R16_UINT.0, + 59 => DXGI_FORMAT_R16_SINT.0, + _ => DXGI_FORMAT_R16_UNORM.0, + }, + // R32_TYPELESS depth twin + 39 => match requested_fmt { + 42 => DXGI_FORMAT_R32_UINT.0, + 43 => DXGI_FORMAT_R32_SINT.0, + _ => DXGI_FORMAT_R32_FLOAT.0, + }, + other => other, + } +} + +/// Classify which plane(s) a D3D12 subresource index belongs to. +pub(super) fn plane_for_subresource(sub: u32, mips: u32, array_size: u32, two_plane: bool) -> PlaneMask { + if !two_plane { + return PlaneMask::Depth; + } + if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { + return PlaneMask::Both; + } + let per_plane = mips.max(1).saturating_mul(array_size.max(1)); + if sub >= per_plane { + PlaneMask::Stencil + } else { + PlaneMask::Depth + } +} + +struct Entry { + device: usize, + plan: TwinPlan, + width: u64, + height: u32, + array_size: u16, + mip_levels: u16, + depth_twin: Option, + stencil_twin: Option, + /// Last known PC resource state per subresource for plane 0 (depth) and plane 1 (stencil). + pc_states_depth: Vec, + pc_states_stencil: Vec, + /// True when the color twin may contain newer UAV writes than the depth-stencil resource. + depth_twin_dirty: bool, + stencil_twin_dirty: bool, + /// True when the depth-stencil resource may contain newer DSV/clear writes than the twin. + depth_plane_dirty: bool, + stencil_plane_dirty: bool, + /// True per subresource if a split barrier (`BEGIN_ONLY`) involving `UNORDERED_ACCESS` was suppressed. + split_uav_depth: Vec, + split_uav_stencil: Vec, + /// Lazy DSV/SRV/UAV descriptor heaps for `FullscreenPass` sync on `R24G8_TYPELESS`. + pass_dsv_heap: Option, + pass_srv_uav_heap: Option, +} + +// D3D12 resources and descriptor heaps are free-threaded. +unsafe impl Send for Entry {} + +impl Entry { + fn new(device: usize, plan: TwinPlan, width: u64, height: u32, array_size: u16, mip_levels: u16, initial_pc_state: u32, started_as_uav: bool) -> Self { + let array_size = array_size.max(1); + let mip_levels = mip_levels.max(1); + let per_plane = (mip_levels as usize).saturating_mul(array_size as usize).max(1); + let stencil_len = if plan.two_plane { per_plane } else { 0 }; + Self { + device, + plan, + width, + height, + array_size, + mip_levels, + depth_twin: None, + stencil_twin: None, + pc_states_depth: vec![initial_pc_state; per_plane], + pc_states_stencil: vec![initial_pc_state; stencil_len], + depth_twin_dirty: started_as_uav, + stencil_twin_dirty: started_as_uav && plan.two_plane, + depth_plane_dirty: !started_as_uav && (initial_pc_state & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0), + stencil_plane_dirty: !started_as_uav && plan.two_plane && (initial_pc_state & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0), + split_uav_depth: vec![false; per_plane], + split_uav_stencil: vec![false; stencil_len], + pass_dsv_heap: None, + pass_srv_uav_heap: None, + } + } + + fn subresources_per_plane(&self) -> u32 { + (self.mip_levels as u32).saturating_mul(self.array_size as u32).max(1) + } + + fn local_subs_for(&self, subresource: u32, plane: u32) -> std::ops::Range { + let per_plane = self.subresources_per_plane(); + if subresource == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { + return 0..per_plane as usize; + } + let base = plane * per_plane; + if subresource >= base && subresource < base + per_plane { + let idx = (subresource - base) as usize; + idx..idx + 1 + } else { + 0..0 + } + } +} + +/// Action queued by `filter_barrier` to run on the command list. +/// Each `(local_sub, before_state, after_state)` entry names the exact plane-local subresource +/// index and its tracked PC `StateBefore` / `StateAfter` so partial subresource barriers and +/// per-plane states never corrupt sibling subresources or planes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(super) enum SyncOp { + TwinToDepth { + res: usize, + depth: Vec<(u32, u32, u32)>, + stencil: Vec<(u32, u32, u32)>, + }, + DepthToTwin { + res: usize, + depth: Vec<(u32, u32, u32)>, + stencil: Vec<(u32, u32, u32)>, + }, + TransitionOnly { + res: usize, + depth: Vec<(u32, u32, u32)>, + stencil: Vec<(u32, u32, u32)>, + }, +} + +static ENTRIES: Mutex>> = Mutex::new(None); +static COUNT: AtomicUsize = AtomicUsize::new(0); +/// DSV CPU handle -> `(resource raw pointer, D3D12_DSV_FLAGS)`. +static DSV_TO_RES: Mutex>> = Mutex::new(None); + +/// Whether Depth+UAV color twins are enabled (`XCL_DEPTH_UAV_TWIN=0` turns them off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_DEPTH_UAV_TWIN").is_ok_and(|v| v.trim() == "0")) +} + +pub fn any() -> bool { + COUNT.load(Ordering::Relaxed) != 0 +} + +/// Register a newly created console depth+UAV texture (`flags & 6 == 6`, single-sample, 2D). +pub(super) fn register_if_depth_uav(device: *mut c_void, res: *mut c_void, console_desc: &[u8; 0x38], initial_pc_state: u32, console_initial_state: u32) { + if !enabled() || device.is_null() || res.is_null() { + return; + } + let dim = u32::from_le_bytes(console_desc[0..4].try_into().unwrap()); + let flags = u32::from_le_bytes(console_desc[0x30..0x34].try_into().unwrap()); + let samples = u32::from_le_bytes(console_desc[0x24..0x28].try_into().unwrap()); + if dim != D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 as u32 || (flags & (FLAG_DEPTH_STENCIL | FLAG_UAV)) != (FLAG_DEPTH_STENCIL | FLAG_UAV) || samples > 1 { + return; + } + let console_fmt = u32::from_le_bytes(console_desc[0x20..0x24].try_into().unwrap()); + let Some(plan) = plan_for_console_format(console_fmt) else { + return; + }; + let width = u64::from_le_bytes(console_desc[0x10..0x18].try_into().unwrap()); + let height = u32::from_le_bytes(console_desc[0x18..0x1C].try_into().unwrap()); + let array_size = u16::from_le_bytes(console_desc[0x1C..0x1E].try_into().unwrap()).max(1); + let mip_levels = u16::from_le_bytes(console_desc[0x1E..0x20].try_into().unwrap()).max(1); + let started_as_uav = console_initial_state & STATE_UAV != 0; + + let mut g = ENTRIES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + let prev = map.insert( + res as usize, + Entry::new(device as usize, plan, width, height, array_size, mip_levels, initial_pc_state, started_as_uav), + ); + if prev.is_none() { + COUNT.fetch_add(1, Ordering::Relaxed); + } + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: tracked depth+UAV texture {res:p} ({width}x{height}x{array_size}, {mip_levels} mips, console fmt {console_fmt}, two_plane {}) for color-twin UAV sync ({} tracked)", + plan.two_plane, + map.len() + ); + } +} + +/// Remove tracking when a resource is released for good (twins go through `res_release` -> `late_release`). +pub(super) fn forget(res: usize) { + if !any() { + return; + } + let removed = { + let mut g = ENTRIES.lock().unwrap(); + let r = g.as_mut().and_then(|m| m.remove(&res)); + if r.is_some() { + COUNT.fetch_sub(1, Ordering::Relaxed); + } + r + }; + if let Some(mut e) = removed { + if let Some(m) = DSV_TO_RES.lock().unwrap().as_mut() { + m.retain(|_, &mut (v, _)| v != res); + } + // Defer release of internal unadopted pass descriptor heaps until in-flight GPU work completes. + unsafe { + if let Some(h) = e.pass_dsv_heap.take() { + super::late_release::hold(h.into_raw() as usize); + } + if let Some(h) = e.pass_srv_uav_heap.take() { + super::late_release::hold(h.into_raw() as usize); + } + } + drop(e); + } +} + +/// Record DSV handle -> `(resource, dsv_flags)` for `OMSetRenderTargets` and `ClearDepthStencilView` hooks. +pub(super) fn note_dsv(dsv_cpu: usize, res: usize, dsv_flags: u32) { + if !any() || dsv_cpu == 0 { + return; + } + let tracked = ENTRIES.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&res)); + let mut g = DSV_TO_RES.lock().unwrap(); + if tracked { + g.get_or_insert_with(HashMap::new).insert(dsv_cpu, (res, dsv_flags)); + } else if let Some(m) = g.as_mut() { + m.remove(&dsv_cpu); + } +} + +unsafe fn create_twin_resource(device: *mut c_void, width: u64, height: u32, array_size: u16, mip_levels: u16, format: i32) -> Option { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: width, + Height: height, + DepthOrArraySize: array_size, + MipLevels: mip_levels, + Format: DXGI_FORMAT(format), + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }; + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = real::dev_create_committed_resource( + device, + &heap as *const _ as usize, + 0, + &desc as *const _ as usize, + STATE_UAV as usize, + 0, + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut out, + ); + if hr < 0 || out.is_null() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: depth+UAV twin allocation ({width}x{height}x{array_size}, fmt {format}) failed ({hr:#x})"); + } + return None; + } + Some(ID3D12Resource::from_raw(out)) +} + +/// Route a `CreateUnorderedAccessView` on a tracked depth+UAV resource to its depth or stencil +/// color twin, returning `(twin_raw_ptr, patched_uav_desc)` when handled. +pub(super) unsafe fn resolve_uav( + dev: *mut c_void, + res: *mut c_void, + orig_desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, +) -> Option<(*mut c_void, D3D12_UNORDERED_ACCESS_VIEW_DESC)> { + if !any() || res.is_null() { + return None; + } + let key = res as usize; + let plane_slice = orig_desc.map_or(0, |d| match d.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => d.Anonymous.Texture2D.PlaneSlice, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => d.Anonymous.Texture2DArray.PlaneSlice, + _ => 0, + }); + let req_fmt = orig_desc.map_or(0, |d| d.Format.0 as u32); + + // Inspect plan and check whether the twin already exists before allocating outside the lock. + let (need_alloc, is_stencil, twin_fmt, width, height, array_size, mip_levels, device, existing_raw) = { + let g = ENTRIES.lock().unwrap(); + let e = g.as_ref()?.get(&key)?; + let stencil = e.plan.two_plane && is_stencil_uav_format(req_fmt, plane_slice); + let twin_fmt = if stencil { e.plan.stencil_twin_fmt? } else { e.plan.depth_twin_fmt }; + let existing = if stencil { + e.stencil_twin.as_ref().map(|r| r.as_raw()) + } else { + e.depth_twin.as_ref().map(|r| r.as_raw()) + }; + (existing.is_none(), stencil, twin_fmt, e.width, e.height, e.array_size, e.mip_levels, if dev.is_null() { e.device as *mut c_void } else { dev }, existing) + }; + + let twin_raw = if let Some(raw) = existing_raw { + raw + } else if need_alloc { + let created = create_twin_resource(device, width, height, array_size, mip_levels, twin_fmt)?; + let mut g = ENTRIES.lock().unwrap(); + let Some(e) = g.as_mut().and_then(|m| m.get_mut(&key)) else { + return None; + }; + let slot = if is_stencil { &mut e.stencil_twin } else { &mut e.depth_twin }; + if slot.is_none() { + *slot = Some(created); + } + slot.as_ref()?.as_raw() + } else { + return None; + }; + + let patched_fmt = twin_uav_format(twin_fmt, req_fmt); + let mut patched = match orig_desc { + Some(d) => *d, + None => { + let mut d = D3D12_UNORDERED_ACCESS_VIEW_DESC::default(); + if array_size > 1 { + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY; + d.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV { + MipSlice: 0, + FirstArraySlice: 0, + ArraySize: array_size as u32, + PlaneSlice: 0, + }; + } else { + d.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; + d.Anonymous.Texture2D = D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }; + } + d + } + }; + patched.Format = DXGI_FORMAT(patched_fmt); + match patched.ViewDimension { + D3D12_UAV_DIMENSION_TEXTURE2D => patched.Anonymous.Texture2D.PlaneSlice = 0, + D3D12_UAV_DIMENSION_TEXTURE2DARRAY => patched.Anonymous.Texture2DArray.PlaneSlice = 0, + _ => {} + } + + static ROUTED: AtomicU64 = AtomicU64::new(0); + let n = ROUTED.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: routed {} UAV of depth+UAV texture {res:p} (req fmt {req_fmt} -> twin fmt {patched_fmt}) to color twin {twin_raw:p} ({} routed)", + if is_stencil { "stencil" } else { "depth" }, + n + 1 + ); + } + Some((twin_raw, patched)) +} + +/// Pure state-machine transition decision for a single barrier on a tracked depth+UAV texture. +/// Returns `(pass_through_barrier, needs_global_uav_barrier, optional_sync_op)`. +fn decide_transition( + e: &mut Entry, + subresource: u32, + before: u32, + after: u32, + flags: u32, + is_direct: bool, +) -> (bool, bool, Option) { + const BARRIER_BEGIN_ONLY: u32 = 1; + const BARRIER_END_ONLY: u32 = 2; + + let planes = plane_for_subresource(subresource, e.mip_levels as u32, e.array_size as u32, e.plan.two_plane); + let d_range = if planes.includes_depth() { e.local_subs_for(subresource, 0) } else { 0..0 }; + let s_range = if e.plan.two_plane && planes.includes_stencil() { e.local_subs_for(subresource, 1) } else { 0..0 }; + let touches_uav = (before | after) & STATE_UAV != 0; + + // Non-DIRECT lists (COMPUTE / COPY / BUNDLE) cannot transition a depth-stencil resource + // to/from DEPTH_* or UNORDERED_ACCESS; suppress invalid barriers and defer sync to DIRECT. + if !is_direct { + if touches_uav { + if after & STATE_UAV != 0 { + if !d_range.is_empty() && e.depth_twin.is_some() { + e.depth_twin_dirty = true; + } + if !s_range.is_empty() && e.stencil_twin.is_some() { + e.stencil_twin_dirty = true; + } + } + return (false, true, None); + } + return (false, false, None); + } + + // Handle split barriers touching UNORDERED_ACCESS: suppress BEGIN_ONLY and perform the + // complete atomic transition + sync at END_ONLY. + if flags == BARRIER_BEGIN_ONLY { + if touches_uav { + for s in d_range { + e.split_uav_depth[s] = true; + } + for s in s_range { + e.split_uav_stencil[s] = true; + } + return (false, false, None); + } + return (true, false, None); + } + if flags == BARRIER_END_ONLY { + let was_split_uav = d_range.clone().any(|s| e.split_uav_depth[s]) || s_range.clone().any(|s| e.split_uav_stencil[s]); + if !touches_uav && !was_split_uav { + for s in d_range.clone() { + e.pc_states_depth[s] = after; + } + if !d_range.is_empty() && after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.depth_plane_dirty = true; + } + for s in s_range.clone() { + e.pc_states_stencil[s] = after; + } + if !s_range.is_empty() && after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.stencil_plane_dirty = true; + } + return (true, false, None); + } + for s in d_range.clone() { + e.split_uav_depth[s] = false; + } + for s in s_range.clone() { + e.split_uav_stencil[s] = false; + } + } + + let collect_subs = |states: &mut [u32], range: std::ops::Range, target: u32| -> Vec<(u32, u32, u32)> { + let mut v = Vec::with_capacity(range.len()); + for s in range { + let prev = states[s]; + states[s] = target; + v.push((s as u32, prev, target)); + } + v + }; + + let leaving_uav = before & STATE_UAV != 0 && after & STATE_UAV == 0; + let entering_uav = before & STATE_UAV == 0 && after & STATE_UAV != 0; + + if leaving_uav { + let need_d = !d_range.is_empty() && e.depth_twin.is_some(); + let need_s = !s_range.is_empty() && e.stencil_twin.is_some(); + let depth = collect_subs(&mut e.pc_states_depth, d_range.clone(), after); + let stencil = collect_subs(&mut e.pc_states_stencil, s_range.clone(), after); + if !d_range.is_empty() { + e.depth_twin_dirty = false; + if after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.depth_plane_dirty = true; + } + } + if !s_range.is_empty() { + e.stencil_twin_dirty = false; + if after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.stencil_plane_dirty = true; + } + } + let op = if need_d || need_s { + Some(SyncOp::TwinToDepth { res: 0, depth, stencil }) + } else { + Some(SyncOp::TransitionOnly { res: 0, depth, stencil }) + }; + return (false, true, op); + } + + if entering_uav { + // Transition depth resource from each subresource's tracked PC state (`prev`) to + // `DEPTH_WRITE` as its resting state while UAV is active. + let need_d = !d_range.is_empty() && e.depth_twin.is_some() && (e.depth_plane_dirty || before & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0); + let need_s = !s_range.is_empty() && e.stencil_twin.is_some() && (e.stencil_plane_dirty || before & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0); + let depth = collect_subs(&mut e.pc_states_depth, d_range.clone(), STATE_DEPTH_WRITE); + let stencil = collect_subs(&mut e.pc_states_stencil, s_range.clone(), STATE_DEPTH_WRITE); + if !d_range.is_empty() { + e.depth_twin_dirty = e.depth_twin.is_some(); + e.depth_plane_dirty = false; + } + if !s_range.is_empty() { + e.stencil_twin_dirty = e.stencil_twin.is_some(); + e.stencil_plane_dirty = false; + } + let op = if need_d || need_s { + Some(SyncOp::DepthToTwin { res: 0, depth, stencil }) + } else { + Some(SyncOp::TransitionOnly { res: 0, depth, stencil }) + }; + return (false, true, op); + } + + // Neither before nor after is UNORDERED_ACCESS. If a twin became dirty (e.g. on an async + // compute list), flush it into the depth resource now as part of this transition. + let flush_d = !d_range.is_empty() && e.depth_twin_dirty && e.depth_twin.is_some(); + let flush_s = !s_range.is_empty() && e.stencil_twin_dirty && e.stencil_twin.is_some(); + let depth = collect_subs(&mut e.pc_states_depth, d_range.clone(), after); + let stencil = collect_subs(&mut e.pc_states_stencil, s_range.clone(), after); + if !d_range.is_empty() { + if flush_d { + e.depth_twin_dirty = false; + } + if after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.depth_plane_dirty = true; + } + } + if !s_range.is_empty() { + if flush_s { + e.stencil_twin_dirty = false; + } + if after & (STATE_DEPTH_WRITE | STATE_COPY_DEST) != 0 { + e.stencil_plane_dirty = true; + } + } + if flush_d || flush_s { + let op = SyncOp::TwinToDepth { res: 0, depth, stencil }; + return (false, true, Some(op)); + } + + (true, false, None) +} + +/// Inspect a PC transition barrier `[ty, flags, res_lo, res_hi, sub, before, after, _]` inside +/// `list_x::resource_barrier_x`. Returns `(pass_through, emit_global_uav_barrier)` and pushes +/// any required sync operation onto `ops`. +pub(super) fn filter_transition( + b: &[u32; 8], + is_direct: bool, + ops: &mut Vec, +) -> (bool, bool) { + if !any() { + return (true, false); + } + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + let mut g = ENTRIES.lock().unwrap(); + let Some(e) = g.as_mut().and_then(|m| m.get_mut(&res)) else { + return (true, false); + }; + let (pass, uav, op) = decide_transition(e, b[4], b[5], b[6], b[1], is_direct); + if let Some(mut op) = op { + match &mut op { + SyncOp::TwinToDepth { res: r, .. } | SyncOp::DepthToTwin { res: r, .. } | SyncOp::TransitionOnly { res: r, .. } => *r = res, + } + ops.push(op); + } + (pass, uav) +} + +/// Whether a `D3D12_BARRIER_LAYOUT` is an unordered-access layout (generic or queue-specific). +fn is_uav_layout(layout: D3D12_BARRIER_LAYOUT) -> bool { + matches!( + layout, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS + ) +} + +/// Whether a `D3D12_BARRIER_LAYOUT` is a depth-write or copy-destination layout. +fn is_depth_write_or_copy_dest_layout(layout: D3D12_BARRIER_LAYOUT) -> bool { + matches!( + layout, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE + | D3D12_BARRIER_LAYOUT_COPY_DEST + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_DEST + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_DEST + ) +} + +/// Map a `D3D12_BARRIER_LAYOUT` + `D3D12_BARRIER_ACCESS` pair to a valid PC `D3D12_RESOURCE_STATES` +/// value for a depth-stencil texture (never returning `STATE_UAV` or buffer-only state bits). +pub(super) fn enhanced_layout_to_pc_state(layout: D3D12_BARRIER_LAYOUT, access: D3D12_BARRIER_ACCESS) -> u32 { + let a = access.0 as u32; + let access_state = || -> u32 { + if a & (D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE.0 as u32) != 0 { + STATE_DEPTH_WRITE + } else if a & (D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ.0 as u32) != 0 { + STATE_DEPTH_READ + } else if a & (D3D12_BARRIER_ACCESS_SHADER_RESOURCE.0 as u32) != 0 { + STATE_SRV_ALL + } else if a & (D3D12_BARRIER_ACCESS_COPY_DEST.0 as u32) != 0 { + STATE_COPY_DEST + } else if a & (D3D12_BARRIER_ACCESS_COPY_SOURCE.0 as u32) != 0 { + STATE_COPY_SOURCE + } else { + STATE_COMMON + } + }; + match layout { + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE => STATE_DEPTH_WRITE, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ => STATE_DEPTH_READ, + D3D12_BARRIER_LAYOUT_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE => STATE_SRV_ALL, + D3D12_BARRIER_LAYOUT_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_SOURCE => STATE_COPY_SOURCE, + D3D12_BARRIER_LAYOUT_COPY_DEST + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_DEST + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_DEST => STATE_COPY_DEST, + D3D12_BARRIER_LAYOUT_GENERIC_READ + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_GENERIC_READ => { + if a & (D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ.0 as u32) != 0 { + STATE_DEPTH_READ + } else { + STATE_SRV_ALL | STATE_COPY_SOURCE + } + } + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS => STATE_DEPTH_WRITE, + _ => access_state(), + } +} + +/// Resolve an enhanced barrier's `D3D12_BARRIER_SUBRESOURCE_RANGE` into plane-local subresource +/// indices `(depth_subs, stencil_subs)`. +fn resolve_enhanced_subresources(e: &Entry, range: &D3D12_BARRIER_SUBRESOURCE_RANGE) -> (Vec, Vec) { + let mips = e.mip_levels as u32; + let slices = e.array_size as u32; + let two_plane = e.plan.two_plane; + if range.NumMipLevels == 0 { + let sub = range.IndexOrFirstMipLevel; + let planes = plane_for_subresource(sub, mips, slices, two_plane); + let d = if planes.includes_depth() { e.local_subs_for(sub, 0).map(|s| s as u32).collect() } else { Vec::new() }; + let s = if two_plane && planes.includes_stencil() { e.local_subs_for(sub, 1).map(|s| s as u32).collect() } else { Vec::new() }; + return (d, s); + } + let first_mip = range.IndexOrFirstMipLevel.min(mips); + let end_mip = range.IndexOrFirstMipLevel.saturating_add(range.NumMipLevels).min(mips); + let first_arr = range.FirstArraySlice.min(slices); + let num_arr = if range.NumArraySlices == 0 { 1 } else { range.NumArraySlices }; + let end_arr = range.FirstArraySlice.saturating_add(num_arr).min(slices); + let plane_count = if two_plane { 2u32 } else { 1u32 }; + let first_plane = range.FirstPlane.min(plane_count); + let num_planes = if range.NumPlanes == 0 { 1 } else { range.NumPlanes }; + let end_plane = range.FirstPlane.saturating_add(num_planes).min(plane_count); + + let mut depth = Vec::new(); + let mut stencil = Vec::new(); + for p in first_plane..end_plane { + let dst = if p == 0 { &mut depth } else { &mut stencil }; + for a in first_arr..end_arr { + for m in first_mip..end_mip { + dst.push(a * mips + m); + } + } + } + (depth, stencil) +} + +/// Pure state-machine transition decision for an enhanced `D3D12_TEXTURE_BARRIER` (`#146`) on a +/// tracked depth+UAV texture. +#[allow(clippy::too_many_arguments)] +fn decide_enhanced_texture_barrier( + e: &mut Entry, + access_before: D3D12_BARRIER_ACCESS, + access_after: D3D12_BARRIER_ACCESS, + layout_before: D3D12_BARRIER_LAYOUT, + layout_after: D3D12_BARRIER_LAYOUT, + subresources: &D3D12_BARRIER_SUBRESOURCE_RANGE, + flags: D3D12_TEXTURE_BARRIER_FLAGS, + is_direct: bool, +) -> Option { + let (d_subs, s_subs) = resolve_enhanced_subresources(e, subresources); + if d_subs.is_empty() && s_subs.is_empty() { + return None; + } + let ab = access_before.0 as u32; + let aa = access_after.0 as u32; + let uav_bit = D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0 as u32; + let write_bits = (D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE.0 as u32) | (D3D12_BARRIER_ACCESS_COPY_DEST.0 as u32); + let discard_before = (flags.0 as u32) & (D3D12_TEXTURE_BARRIER_FLAG_DISCARD.0 as u32) != 0 || layout_before == D3D12_BARRIER_LAYOUT_UNDEFINED; + + let common_before = ab == 0 && matches!(layout_before, D3D12_BARRIER_LAYOUT_COMMON | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COMMON | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COMMON); + let uav_before = (ab & uav_bit) != 0 || is_uav_layout(layout_before); + let uav_after = (aa & uav_bit) != 0 || is_uav_layout(layout_after); + let write_before = (ab & write_bits) != 0 || is_depth_write_or_copy_dest_layout(layout_before); + let write_after = (aa & write_bits) != 0 || is_depth_write_or_copy_dest_layout(layout_after); + let after_pc = enhanced_layout_to_pc_state(layout_after, access_after); + + if !is_direct { + if uav_before || uav_after || common_before { + if !d_subs.is_empty() && e.depth_twin.is_some() && !e.depth_plane_dirty { + e.depth_twin_dirty = true; + } + if !s_subs.is_empty() && e.stencil_twin.is_some() && !e.stencil_plane_dirty { + e.stencil_twin_dirty = true; + } + } + return None; + } + + let collect_subs = |states: &mut [u32], subs: &[u32], target: u32| -> Vec<(u32, u32, u32)> { + let mut v = Vec::with_capacity(subs.len()); + for &s in subs { + let idx = s as usize; + if idx < states.len() { + let prev = states[idx]; + states[idx] = target; + v.push((s, prev, target)); + } + } + v + }; + + if uav_before && !uav_after { + let need_d = !discard_before && !d_subs.is_empty() && e.depth_twin.is_some(); + let need_s = !discard_before && !s_subs.is_empty() && e.stencil_twin.is_some(); + let depth = collect_subs(&mut e.pc_states_depth, &d_subs, after_pc); + let stencil = collect_subs(&mut e.pc_states_stencil, &s_subs, after_pc); + if !d_subs.is_empty() { + e.depth_twin_dirty = false; + if write_after { + e.depth_plane_dirty = true; + } + } + if !s_subs.is_empty() { + e.stencil_twin_dirty = false; + if write_after { + e.stencil_plane_dirty = true; + } + } + return if need_d || need_s { + Some(SyncOp::TwinToDepth { res: 0, depth, stencil }) + } else if depth.iter().any(|&(_, b, a)| b != a) || stencil.iter().any(|&(_, b, a)| b != a) { + Some(SyncOp::TransitionOnly { res: 0, depth, stencil }) + } else { + None + }; + } + + if !uav_before && uav_after { + let need_d = !discard_before && !d_subs.is_empty() && e.depth_twin.is_some() && (e.depth_plane_dirty || write_before); + let need_s = !discard_before && !s_subs.is_empty() && e.stencil_twin.is_some() && (e.stencil_plane_dirty || write_before); + let depth = collect_subs(&mut e.pc_states_depth, &d_subs, STATE_DEPTH_WRITE); + let stencil = collect_subs(&mut e.pc_states_stencil, &s_subs, STATE_DEPTH_WRITE); + if !d_subs.is_empty() { + e.depth_twin_dirty = e.depth_twin.is_some(); + e.depth_plane_dirty = false; + } + if !s_subs.is_empty() { + e.stencil_twin_dirty = e.stencil_twin.is_some(); + e.stencil_plane_dirty = false; + } + return if need_d || need_s { + Some(SyncOp::DepthToTwin { res: 0, depth, stencil }) + } else if depth.iter().any(|&(_, b, a)| b != a) || stencil.iter().any(|&(_, b, a)| b != a) { + Some(SyncOp::TransitionOnly { res: 0, depth, stencil }) + } else { + None + }; + } + + if uav_before && uav_after { + if !d_subs.is_empty() && e.depth_twin.is_some() { + e.depth_twin_dirty = true; + } + if !s_subs.is_empty() && e.stencil_twin.is_some() { + e.stencil_twin_dirty = true; + } + return None; + } + + // Neither before nor after explicitly names UAV. Flush dirty twins (including compute-only + // twins transitioning out of COMMON access) unless discarded, and advance tracked PC state. + let flush_d = !discard_before && !d_subs.is_empty() && e.depth_twin.is_some() && (e.depth_twin_dirty || (common_before && !e.depth_plane_dirty)); + let flush_s = !discard_before && !s_subs.is_empty() && e.stencil_twin.is_some() && (e.stencil_twin_dirty || (common_before && !e.stencil_plane_dirty)); + let depth = collect_subs(&mut e.pc_states_depth, &d_subs, after_pc); + let stencil = collect_subs(&mut e.pc_states_stencil, &s_subs, after_pc); + if !d_subs.is_empty() { + if flush_d || discard_before { + e.depth_twin_dirty = false; + } + if write_after { + e.depth_plane_dirty = true; + } else if discard_before { + e.depth_plane_dirty = false; + } + } + if !s_subs.is_empty() { + if flush_s || discard_before { + e.stencil_twin_dirty = false; + } + if write_after { + e.stencil_plane_dirty = true; + } else if discard_before { + e.stencil_plane_dirty = false; + } + } + if flush_d || flush_s { + return Some(SyncOp::TwinToDepth { res: 0, depth, stencil }); + } + if depth.iter().any(|&(_, b, a)| b != a) || stencil.iter().any(|&(_, b, a)| b != a) { + return Some(SyncOp::TransitionOnly { res: 0, depth, stencil }); + } + None +} + +/// Inspect `ID3D12GraphicsCommandList7::Barrier` (`#146`) barrier groups for tracked depth+UAV +/// textures. Queues any immediate `SyncOp`s on `ops` and returns `true` if a global (or unparsed) +/// UAV barrier was present so the caller should also call `on_global_uav_barrier()`. +pub(super) unsafe fn filter_enhanced_barriers( + n: u32, + groups: *const c_void, + is_direct: bool, + ops: &mut Vec, +) -> bool { + if !any() { + return false; + } + if n == 0 || groups.is_null() { + return true; + } + let group_count = (n as usize).min(256); + let group_bytes = group_count.saturating_mul(std::mem::size_of::()); + if !crate::gpu::shader::readable(groups as usize, group_bytes) { + return true; + } + let slice = std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, group_count); + let mut had_global_uav = false; + for grp in slice { + let count = (grp.NumBarriers as usize).min(4096); + match grp.Type { + D3D12_BARRIER_TYPE_GLOBAL => { + if count == 0 { + continue; + } + let ptr = grp.Anonymous.pGlobalBarriers; + let bytes = count.saturating_mul(std::mem::size_of::()); + if ptr.is_null() || !crate::gpu::shader::readable(ptr as usize, bytes) { + had_global_uav = true; + continue; + } + let gbs = std::slice::from_raw_parts(ptr, count); + for gb in gbs { + let ab = gb.AccessBefore.0 as u32; + if ab == 0 || ab & (D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0 as u32) != 0 { + had_global_uav = true; + break; + } + } + } + D3D12_BARRIER_TYPE_TEXTURE => { + if count == 0 { + continue; + } + let ptr = grp.Anonymous.pTextureBarriers; + let bytes = count.saturating_mul(std::mem::size_of::()); + if ptr.is_null() || !crate::gpu::shader::readable(ptr as usize, bytes) { + had_global_uav = true; + continue; + } + let tbs = std::slice::from_raw_parts(ptr, count); + let mut g = ENTRIES.lock().unwrap(); + let Some(map) = g.as_mut() else { + continue; + }; + for tb in tbs { + let res: usize = std::mem::transmute_copy(&tb.pResource); + if res == 0 { + continue; + } + let Some(e) = map.get_mut(&res) else { + continue; + }; + if let Some(mut op) = decide_enhanced_texture_barrier( + e, + tb.AccessBefore, + tb.AccessAfter, + tb.LayoutBefore, + tb.LayoutAfter, + &tb.Subresources, + tb.Flags, + is_direct, + ) { + match &mut op { + SyncOp::TwinToDepth { res: r, .. } | SyncOp::DepthToTwin { res: r, .. } | SyncOp::TransitionOnly { res: r, .. } => *r = res, + } + ops.push(op); + } + } + } + D3D12_BARRIER_TYPE_BUFFER => {} + _ => { + had_global_uav = true; + } + } + } + had_global_uav +} + +/// Apply a global UAV barrier to a single entry: mark materialized twins dirty only when their +/// corresponding depth/stencil plane is not currently graphics-dirty (avoiding clobbering +/// graphics-rendered depth targets on unrelated global UAV barriers). +fn mark_global_uav_dirty(e: &mut Entry) { + if e.depth_twin.is_some() && !e.depth_plane_dirty { + e.depth_twin_dirty = true; + } + if e.stencil_twin.is_some() && !e.stencil_plane_dirty { + e.stencil_twin_dirty = true; + } +} + +/// Mark materialized twins dirty on a global UAV barrier (`#146` global barrier or `#26` wildcard +/// `pResource == NULL` UAV barrier) for tracked depth+UAV resources whose depth/stencil plane is +/// not currently graphics-dirty, so compute-written depth+UAV targets flush on subsequent DSV bind. +pub(super) fn on_global_uav_barrier() { + if !any() { + return; + } + let mut g = ENTRIES.lock().unwrap(); + let Some(map) = g.as_mut() else { + return; + }; + for e in map.values_mut() { + mark_global_uav_dirty(e); + } +} + +/// Route a resource-specific UAV barrier targeting a tracked Depth+UAV resource to both its +/// materialized depth and stencil color twins, and mark those twins dirty so subsequent DSV/SRV +/// transitions flush their latest UAV writes back into the depth-stencil resource. +pub(super) fn on_uav_barrier(res: usize) -> [usize; 2] { + if !any() || res == 0 { + return [0, 0]; + } + let mut g = ENTRIES.lock().unwrap(); + let Some(e) = g.as_mut().and_then(|m| m.get_mut(&res)) else { + return [0, 0]; + }; + let d = match &e.depth_twin { + Some(t) => { + e.depth_twin_dirty = true; + t.as_raw() as usize + } + None => 0, + }; + let s = match &e.stencil_twin { + Some(t) => { + e.stencil_twin_dirty = true; + t.as_raw() as usize + } + None => 0, + }; + [d, s] +} + +/// Before `OMSetRenderTargets` binds `dsv_cpu`, flush any dirty color twin into the depth resource. +pub(super) unsafe fn before_bind_dsv(list: *mut c_void, dsv_cpu: usize) { + if !any() || dsv_cpu == 0 { + return; + } + if list_x::tracked_list_type(list).is_some_and(|t| t != D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + let Some((res, dsv_flags)) = DSV_TO_RES.lock().unwrap().as_ref().and_then(|m| m.get(&dsv_cpu).copied()) else { + return; + }; + let d_target_from_common = if dsv_flags & (D3D12_DSV_FLAG_READ_ONLY_DEPTH.0 as u32) != 0 { + STATE_DEPTH_READ + } else { + STATE_DEPTH_WRITE + }; + let s_target_from_common = if dsv_flags & (D3D12_DSV_FLAG_READ_ONLY_STENCIL.0 as u32) != 0 { + STATE_DEPTH_READ + } else { + STATE_DEPTH_WRITE + }; + let op = { + let mut g = ENTRIES.lock().unwrap(); + let Some(e) = g.as_mut().and_then(|m| m.get_mut(&res)) else { + return; + }; + let d = e.depth_twin_dirty && e.depth_twin.is_some(); + let s = e.stencil_twin_dirty && e.stencil_twin.is_some(); + if !d && !s { + return; + } + if d { + e.depth_twin_dirty = false; + } + if s { + e.stencil_twin_dirty = false; + } + let depth = if d { + e.pc_states_depth + .iter_mut() + .enumerate() + .map(|(sub, st)| { + let before = *st; + let after = if before == STATE_COMMON { d_target_from_common } else { before }; + *st = after; + (sub as u32, before, after) + }) + .collect() + } else { + Vec::new() + }; + let stencil = if s { + e.pc_states_stencil + .iter_mut() + .enumerate() + .map(|(sub, st)| { + let before = *st; + let after = if before == STATE_COMMON { s_target_from_common } else { before }; + *st = after; + (sub as u32, before, after) + }) + .collect() + } else { + Vec::new() + }; + SyncOp::TwinToDepth { res, depth, stencil } + }; + execute_syncs(list, &[op]); +} + +/// Record a `ClearDepthStencilView` on a tracked depth+UAV resource so cleared planes are marked +/// depth-dirty (and no longer wait for a stale twin flush). +pub(super) fn on_clear_dsv(dsv_cpu: usize, clear_flags: u32) { + if !any() || dsv_cpu == 0 { + return; + } + let Some((res, _)) = DSV_TO_RES.lock().unwrap().as_ref().and_then(|m| m.get(&dsv_cpu).copied()) else { + return; + }; + let mut g = ENTRIES.lock().unwrap(); + if let Some(e) = g.as_mut().and_then(|m| m.get_mut(&res)) { + if clear_flags & 1 != 0 { + e.depth_twin_dirty = false; + e.depth_plane_dirty = true; + } + if clear_flags & 2 != 0 && e.plan.two_plane { + e.stencil_twin_dirty = false; + e.stencil_plane_dirty = true; + } + } +} + +/// RAII guard for `D3D12_TEXTURE_COPY_LOCATION` so `ManuallyDrop>` is +/// always dropped cleanly without leaking COM references. +struct OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION); + +impl Drop for OwnedCopyLoc { + fn drop(&mut self) { + unsafe { ManuallyDrop::drop(&mut self.0.pResource) }; + } +} + +/// Transition specific plane-local subresources on `list` from their tracked `before` state to +/// `target_override` (if `Some`) or their tracked `after` state (if `None`). +unsafe fn transition_plane_subs( + list: *mut c_void, + res: usize, + two_plane: bool, + per_plane: u32, + plane: u32, + subs: &[(u32, u32, u32)], + target_override: Option, +) { + if subs.is_empty() { + return; + } + if !two_plane && subs.len() == per_plane as usize { + let first_b = subs[0].1; + let first_a = target_override.unwrap_or(subs[0].2); + if subs.iter().all(|&(_, b, a)| b == first_b && target_override.unwrap_or(a) == first_a) { + if first_b != first_a { + list_x::transition(list, res, D3D12_RESOURCE_STATES(first_b as i32), D3D12_RESOURCE_STATES(first_a as i32)); + } + return; + } + } + let base = plane * per_plane; + let mut barriers = Vec::with_capacity(subs.len()); + for &(s, before, after) in subs { + let dst = target_override.unwrap_or(after); + if before == dst { + continue; + } + barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&res), + Subresource: base + s, + StateBefore: D3D12_RESOURCE_STATES(before as i32), + StateAfter: D3D12_RESOURCE_STATES(dst as i32), + }), + }, + }); + } + if !barriers.is_empty() { + list_x::pc_resource_barriers(list, &barriers); + } +} + +/// Transition specific plane-local subresources from a common intermediate `from_state` back to +/// each subresource's tracked `after` state. +unsafe fn transition_plane_from( + list: *mut c_void, + res: usize, + two_plane: bool, + per_plane: u32, + plane: u32, + from_state: u32, + subs: &[(u32, u32, u32)], +) { + if subs.is_empty() { + return; + } + if !two_plane && subs.len() == per_plane as usize { + let first_a = subs[0].2; + if subs.iter().all(|&(_, _, a)| a == first_a) { + if from_state != first_a { + list_x::transition(list, res, D3D12_RESOURCE_STATES(from_state as i32), D3D12_RESOURCE_STATES(first_a as i32)); + } + return; + } + } + let base = plane * per_plane; + let mut barriers = Vec::with_capacity(subs.len()); + for &(s, _, after) in subs { + if from_state == after { + continue; + } + barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&res), + Subresource: base + s, + StateBefore: D3D12_RESOURCE_STATES(from_state as i32), + StateAfter: D3D12_RESOURCE_STATES(after as i32), + }), + }, + }); + } + if !barriers.is_empty() { + list_x::pc_resource_barriers(list, &barriers); + } +} + +/// Copy specific subresources (`subs` local indices) directly between two format-compatible +/// single-plane resources via `CopyTextureRegion` (or `CopyResource` if all subresources match). +unsafe fn copy_direct_subs( + list: *mut c_void, + dst_res: &ID3D12Resource, + src_res: &ID3D12Resource, + per_plane: u32, + subs: &[(u32, u32, u32)], +) { + if subs.len() == per_plane as usize { + list_x::pc_copy_resource(list, dst_res.as_raw() as usize, src_res.as_raw() as usize); + return; + } + for &(s, _, _) in subs { + let dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(dst_res.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: s }, + }); + let src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(src_res.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: s }, + }); + list_x::pc_copy_texture_region(list, &dst_loc.0, 0, 0, 0, &src_loc.0, std::ptr::null()); + } +} + +/// Copy specific subresources (`subs`) on one plane (`plane`: 0 or 1) between `depth_res` and +/// `twin_res` via a staging buffer using `CopyTextureRegion`. +unsafe fn copy_plane_through_buffer( + list: *mut c_void, + dev: &ID3D12Device, + dst_res: &ID3D12Resource, + dst_plane: u32, + src_res: &ID3D12Resource, + src_plane: u32, + per_plane: u32, + subs: &[(u32, u32, u32)], +) -> bool { + let dst_desc = dst_res.GetDesc(); + let src_desc = src_res.GetDesc(); + for &(s, _, _) in subs { + let src_sub = src_plane * per_plane + s; + let dst_sub = dst_plane * per_plane + s; + let mut src_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut dst_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut src_rows = 0u32; + let mut dst_rows = 0u32; + let mut src_total = 0u64; + let mut dst_total = 0u64; + dev.GetCopyableFootprints(&src_desc, src_sub, 1, 0, Some(&mut src_fp), Some(&mut src_rows), None, Some(&mut src_total)); + dev.GetCopyableFootprints(&dst_desc, dst_sub, 1, 0, Some(&mut dst_fp), Some(&mut dst_rows), None, Some(&mut dst_total)); + if src_total == 0 + || src_total == u64::MAX + || dst_total == 0 + || dst_total == u64::MAX + || src_rows != dst_rows + || src_fp.Footprint.Width != dst_fp.Footprint.Width + || src_fp.Footprint.Height != dst_fp.Footprint.Height + { + return false; + } + // Plane 1 of a two-plane depth-stencil texture (e.g. R24G8_TYPELESS stencil) can report a + // larger row pitch (e.g. 512 B) than a standalone R8_TYPELESS twin (256 B). D3D12 allows + // increasing Footprint.RowPitch to any 256-byte multiple >= the reported minimum, so + // unifying both footprints to `max(src_pitch, dst_pitch)` keeps every row aligned identically. + let row_pitch = src_fp.Footprint.RowPitch.max(dst_fp.Footprint.RowPitch); + src_fp.Footprint.RowPitch = row_pitch; + dst_fp.Footprint.RowPitch = row_pitch; + let needed = (row_pitch as u64).saturating_mul(src_rows as u64).max(src_total).max(dst_total); + let Some(scratch_raw) = list_x::acquire_scratch_for_copy(list, needed) else { + return false; + }; + let scratch_ptr = scratch_raw as *mut c_void; + let Some(scratch) = ID3D12Resource::from_raw_borrowed(&scratch_ptr) else { + return false; + }; + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + { + let src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(src_res.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: src_sub }, + }); + let buf_dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(scratch.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: src_fp }, + }); + list_x::pc_copy_texture_region(list, &buf_dst_loc.0, 0, 0, 0, &src_loc.0, std::ptr::null()); + } + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + { + let buf_src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(scratch.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: dst_fp }, + }); + let dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(dst_res.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: dst_sub }, + }); + list_x::pc_copy_texture_region(list, &dst_loc.0, 0, 0, 0, &buf_src_loc.0, std::ptr::null()); + } + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + } + true +} + +// --------------------------------------------------------------------------------------- +// Internal fullscreen depth-write & compute depth-read pipelines for R24G8_TYPELESS +// (console D16_UNORM_S8_UINT / D24_UNORM_S8_UINT plane 0) +// --------------------------------------------------------------------------------------- + +struct SyncPipelines { + gfx_rs: ID3D12RootSignature, + gfx_pso: ID3D12PipelineState, + cs_rs: ID3D12RootSignature, + cs_pso: ID3D12PipelineState, +} + +unsafe impl Send for SyncPipelines {} + +static PIPELINES: Mutex>>> = Mutex::new(None); + +fn compile_sm5(src: &str, target: &str) -> Option> { + unsafe { + let mut blob = None; + let t = format!("{target}\0"); + let r = D3DCompile( + src.as_ptr() as *const c_void, + src.len(), + PCSTR::null(), + None, + None, + PCSTR(b"main\0".as_ptr()), + PCSTR(t.as_ptr()), + 0, + 0, + &mut blob, + None, + ); + match (r, blob) { + (Ok(()), Some(b)) => Some(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec()), + _ => None, + } + } +} + +unsafe fn build_sync_pipelines(dev: &ID3D12Device) -> Option { + let vs = compile_sm5( + "float4 main(uint id : SV_VertexID) : SV_Position {\n\ + float2 p = float2((id == 2) ? 3.0 : -1.0, (id == 1) ? 3.0 : -1.0);\n\ + return float4(p, 0.0, 1.0);\n\ + }\n", + "vs_5_0", + )?; + let ps = compile_sm5( + "Texture2DArray src : register(t0);\n\ + cbuffer C : register(b0) { uint slice; uint mip; };\n\ + float main(float4 pos : SV_Position) : SV_Depth {\n\ + return src.Load(int4(int2(pos.xy), int(slice), int(mip)));\n\ + }\n", + "ps_5_0", + )?; + let cs = compile_sm5( + "Texture2DArray src : register(t0);\n\ + RWTexture2DArray dst : register(u0);\n\ + cbuffer C : register(b0) { uint w; uint h; uint slices; uint mip; };\n\ + [numthreads(8, 8, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + if (id.x < w && id.y < h && id.z < slices) {\n\ + dst[id] = src.Load(int4(int3(id), int(mip)));\n\ + }\n\ + }\n", + "cs_5_0", + )?; + + // Graphics RS: [0] 2 root constants (b0), [1] 1 SRV table (t0) + let srv_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let gfx_params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 2 }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_PIXEL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &srv_range }, + }, + }, + ]; + let gfx_rs_desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: gfx_params.len() as u32, + pParameters: gfx_params.as_ptr(), + ..Default::default() + }; + let mut blob = None; + D3D12SerializeRootSignature(&gfx_rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut blob, None).ok()?; + let blob = blob?; + let dev_raw = dev.as_raw(); + type CreateRsFn = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create_rs: CreateRsFn = std::mem::transmute(real::orig_fn(dev_raw, 16)); + let mut gfx_rs_raw = std::ptr::null_mut(); + if create_rs(dev_raw, 0, blob.GetBufferPointer(), blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const _, &mut gfx_rs_raw) < 0 || gfx_rs_raw.is_null() { + return None; + } + let gfx_rs = ID3D12RootSignature::from_raw(gfx_rs_raw); + + // Compute RS: [0] 4 root constants (b0), [1] 1 SRV table (t0), [2] 1 UAV table (u0) + let uav_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let cs_params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 4 }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &srv_range }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &uav_range }, + }, + }, + ]; + let cs_rs_desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: cs_params.len() as u32, + pParameters: cs_params.as_ptr(), + ..Default::default() + }; + let mut cs_blob = None; + D3D12SerializeRootSignature(&cs_rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut cs_blob, None).ok()?; + let cs_blob = cs_blob?; + let mut cs_rs_raw = std::ptr::null_mut(); + if create_rs(dev_raw, 0, cs_blob.GetBufferPointer(), cs_blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const _, &mut cs_rs_raw) < 0 || cs_rs_raw.is_null() { + return None; + } + let cs_rs = ID3D12RootSignature::from_raw(cs_rs_raw); + + // Graphics PSO: write SV_Depth unconditionally, stencil disabled so plane 1 stays intact. + let mut gfx_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(gfx_rs.clone())), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: vs.as_ptr() as *const c_void, BytecodeLength: vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: ps.as_ptr() as *const c_void, BytecodeLength: ps.len() }, + SampleMask: u32::MAX, + RasterizerState: D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + DepthClipEnable: false.into(), + ..Default::default() + }, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ALL, + DepthFunc: D3D12_COMPARISON_FUNC_ALWAYS, + StencilEnable: false.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 0, + DSVFormat: DXGI_FORMAT_D24_UNORM_S8_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + type CreateGfxPsoFn = unsafe extern "system" fn(*mut c_void, *const D3D12_GRAPHICS_PIPELINE_STATE_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create_gfx: CreateGfxPsoFn = std::mem::transmute(real::orig_fn(dev_raw, 10)); + let mut gfx_pso_raw = std::ptr::null_mut(); + let hr_gfx = create_gfx(dev_raw, &gfx_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut gfx_pso_raw); + ManuallyDrop::drop(&mut gfx_desc.pRootSignature); + if hr_gfx < 0 || gfx_pso_raw.is_null() { + return None; + } + let gfx_pso = ID3D12PipelineState::from_raw(gfx_pso_raw); + + let mut cs_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(cs_rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, + ..Default::default() + }; + type CreateCsPsoFn = unsafe extern "system" fn(*mut c_void, *const D3D12_COMPUTE_PIPELINE_STATE_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + let create_cs: CreateCsPsoFn = std::mem::transmute(real::orig_fn(dev_raw, 11)); + let mut cs_pso_raw = std::ptr::null_mut(); + let hr_cs = create_cs(dev_raw, &cs_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut cs_pso_raw); + ManuallyDrop::drop(&mut cs_desc.pRootSignature); + if hr_cs < 0 || cs_pso_raw.is_null() { + return None; + } + let cs_pso = ID3D12PipelineState::from_raw(cs_pso_raw); + + Some(SyncPipelines { gfx_rs, gfx_pso, cs_rs, cs_pso }) +} + +/// Ensure per-resource internal unadopted PC DSV + SRV/UAV descriptor heaps exist for `R24G8_TYPELESS` sync. +unsafe fn ensure_pass_heaps( + dev: &ID3D12Device, + depth_res: &ID3D12Resource, + twin_res: &ID3D12Resource, + e: &mut Entry, + twin_srv_fmt: i32, + twin_uav_fmt: i32, +) -> Option<(ID3D12DescriptorHeap, ID3D12DescriptorHeap)> { + let dev_raw = dev.as_raw(); + type CreateHeapFn = unsafe extern "system" fn(*mut c_void, *const D3D12_DESCRIPTOR_HEAP_DESC, *const windows_sys::core::GUID, *mut *mut c_void) -> i32; + type IncSizeFn = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + type CreateDsvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, usize); + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_heap: CreateHeapFn = std::mem::transmute(real::orig_fn(dev_raw, 14)); + let inc_size: IncSizeFn = std::mem::transmute(real::orig_fn(dev_raw, 15)); + let create_srv: CreateSrvFn = std::mem::transmute(real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); + let create_dsv: CreateDsvFn = std::mem::transmute(real::orig_fn(dev_raw, 21)); + + let mips = e.mip_levels as u32; + let slices = e.array_size as u32; + if e.pass_dsv_heap.is_none() { + let desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: mips * slices, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }; + let mut raw = std::ptr::null_mut(); + if create_heap(dev_raw, &desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut raw) < 0 || raw.is_null() { + return None; + } + let dsv_heap = ID3D12DescriptorHeap::from_raw(raw); + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let base = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + for m in 0..mips { + for a in 0..slices { + let dsv = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D24_UNORM_S8_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2DARRAY, + Flags: D3D12_DSV_FLAG_NONE, + Anonymous: D3D12_DEPTH_STENCIL_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_DSV { MipSlice: m, FirstArraySlice: a, ArraySize: 1 }, + }, + }; + let idx = (m * slices + a) as usize; + create_dsv(dev_raw, depth_res.as_raw(), &dsv, base + idx * inc); + } + } + e.pass_dsv_heap = Some(dsv_heap); + } + if e.pass_srv_uav_heap.is_none() { + // Slot 0: twin SRV, Slot 1: depth plane 0 SRV (R24_UNORM_X8_TYPELESS), Slots 2..2+mips: twin UAV per mip + let total = 2 + mips; + let desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: total, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }; + let mut raw = std::ptr::null_mut(); + if create_heap(dev_raw, &desc, &ID3D12DescriptorHeap::IID as *const _ as *const _, &mut raw) < 0 || raw.is_null() { + return None; + } + let heap = ID3D12DescriptorHeap::from_raw(raw); + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let base = heap.GetCPUDescriptorHandleForHeapStart().ptr; + let twin_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT(twin_srv_fmt), + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: 0, MipLevels: mips, FirstArraySlice: 0, ArraySize: slices, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + }; + create_srv(dev_raw, twin_res.as_raw(), &twin_srv, base); + let depth_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { MostDetailedMip: 0, MipLevels: mips, FirstArraySlice: 0, ArraySize: slices, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + }; + create_srv(dev_raw, depth_res.as_raw(), &depth_srv, base + inc); + for m in 0..mips { + let uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(twin_uav_fmt), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: m, FirstArraySlice: 0, ArraySize: slices, PlaneSlice: 0 }, + }, + }; + create_uav(dev_raw, twin_res.as_raw(), std::ptr::null_mut(), &uav, base + (2 + m as usize) * inc); + } + e.pass_srv_uav_heap = Some(heap); + } + Some((e.pass_dsv_heap.clone()?, e.pass_srv_uav_heap.clone()?)) +} + +unsafe fn get_pipelines(dev: &ID3D12Device) -> Option<(ID3D12RootSignature, ID3D12PipelineState, ID3D12RootSignature, ID3D12PipelineState)> { + let key = dev.as_raw() as usize; + let mut g = PIPELINES.lock().unwrap(); + let map = g.get_or_insert_with(HashMap::new); + let entry = map.entry(key).or_insert_with(|| build_sync_pipelines(dev)); + let p = entry.as_ref()?; + Some((p.gfx_rs.clone(), p.gfx_pso.clone(), p.cs_rs.clone(), p.cs_pso.clone())) +} + +/// Execute queued depth+UAV synchronization ops on a `DIRECT` command list. +pub(super) unsafe fn execute_syncs(list: *mut c_void, ops: &[SyncOp]) { + if ops.is_empty() || list.is_null() { + return; + } + let Some(dev) = list_x::device_of_list(list) else { + return; + }; + let dev_raw = dev.as_raw(); + type IncSizeFn = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + let inc_size: IncSizeFn = std::mem::transmute(real::orig_fn(dev_raw, 15)); + let mut clobbered_gfx = false; + let mut clobbered_cs = false; + + for op in ops { + match op { + SyncOp::TransitionOnly { res, depth, stencil } => { + let res = *res; + let Some((two_plane, per_plane)) = ({ + let g = ENTRIES.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&res)).map(|e| (e.plan.two_plane, e.subresources_per_plane())) + }) else { + continue; + }; + if !depth.is_empty() { + transition_plane_subs(list, res, two_plane, per_plane, 0, depth, None); + } + if two_plane && !stencil.is_empty() { + transition_plane_subs(list, res, two_plane, per_plane, 1, stencil, None); + } + } + SyncOp::TwinToDepth { res, depth, stencil } => { + let res = *res; + let res_ptr = res as *mut c_void; + let Some(depth_res) = ID3D12Resource::from_raw_borrowed(&res_ptr) else { + continue; + }; + let snapshot = { + let g = ENTRIES.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&res)).map(|e| { + ( + e.plan, + e.width, + e.height, + e.array_size, + e.mip_levels, + e.subresources_per_plane(), + e.depth_twin.clone(), + e.stencil_twin.clone(), + ) + }) + }; + let Some((plan, width, height, array_size, mip_levels, per_plane, depth_twin, stencil_twin)) = snapshot else { + continue; + }; + + if !depth.is_empty() { + if let Some(twin) = depth_twin { + match plan.depth_sync { + DepthSyncKind::DirectCopy => { + let twin_raw = twin.as_raw() as usize; + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_plane_subs(list, res, false, per_plane, 0, depth, Some(STATE_COPY_DEST)); + copy_direct_subs(list, depth_res, &twin, per_plane, depth); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, false, per_plane, 0, STATE_COPY_DEST, depth); + } + DepthSyncKind::BufferThrough => { + let twin_raw = twin.as_raw() as usize; + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_COPY_DEST)); + let _ = copy_plane_through_buffer(list, &dev, depth_res, 0, &twin, 0, per_plane, depth); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 0, STATE_COPY_DEST, depth); + } + DepthSyncKind::FullscreenPass { twin_srv_fmt, twin_uav_fmt } => { + let heaps = { + let mut g = ENTRIES.lock().unwrap(); + g.as_mut().and_then(|m| m.get_mut(&res)).and_then(|e| ensure_pass_heaps(&dev, depth_res, &twin, e, twin_srv_fmt, twin_uav_fmt)) + }; + if let (Some((gfx_rs, gfx_pso, _, _)), Some((dsv_heap, srv_heap))) = (get_pipelines(&dev), heaps) { + let twin_raw = twin.as_raw() as usize; + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATES(STATE_SRV_ALL as i32)); + transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_DEPTH_WRITE)); + let srv_raw = srv_heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); + let set_gfx_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 30)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 25)); + let set_topo: unsafe extern "system" fn(*mut c_void, u32) = std::mem::transmute(real::orig_fn(list, 20)); + let set_gfx_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list, 32)); + let set_vp: unsafe extern "system" fn(*mut c_void, u32, *const D3D12_VIEWPORT) = std::mem::transmute(real::orig_fn(list, 21)); + let set_sc: unsafe extern "system" fn(*mut c_void, u32, *const RECT) = std::mem::transmute(real::orig_fn(list, 22)); + let set_rt: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = std::mem::transmute(real::orig_fn(list, 46)); + let set_gfx_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 36)); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 12)); + + set_heaps(list, 1, &srv_raw); + set_gfx_rs(list, gfx_rs.as_raw()); + set_pso(list, gfx_pso.as_raw()); + set_topo(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + set_gfx_table(list, 1, srv_heap.GetGPUDescriptorHandleForHeapStart().ptr); + let dsv_base = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let dsv_inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let mips_u32 = mip_levels as u32; + for &(local_sub, _, _) in depth { + let m = local_sub % mips_u32; + let a = local_sub / mips_u32; + let mw = ((width as u32) >> m).max(1); + let mh = (height >> m).max(1); + let vp = D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: mw as f32, Height: mh as f32, MinDepth: 0.0, MaxDepth: 1.0 }; + let sc = RECT { left: 0, top: 0, right: mw as i32, bottom: mh as i32 }; + set_vp(list, 1, &vp); + set_sc(list, 1, &sc); + let dsv = dsv_base + ((m * array_size as u32 + a) as usize) * dsv_inc; + set_rt(list, 0, std::ptr::null(), 0, &dsv); + let c = [a, m]; + set_gfx_consts(list, 0, 2, c.as_ptr(), 0); + draw(list, 3, 1, 0, 0); + } + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATES(STATE_SRV_ALL as i32), D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 0, STATE_DEPTH_WRITE, depth); + clobbered_gfx = true; + } else { + transition_plane_subs(list, res, true, per_plane, 0, depth, None); + } + } + } + } else { + transition_plane_subs(list, res, plan.two_plane, per_plane, 0, depth, None); + } + } + + if plan.two_plane && !stencil.is_empty() { + if let Some(twin) = stencil_twin { + let twin_raw = twin.as_raw() as usize; + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + transition_plane_subs(list, res, true, per_plane, 1, stencil, Some(STATE_COPY_DEST)); + let _ = copy_plane_through_buffer(list, &dev, depth_res, 1, &twin, 0, per_plane, stencil); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 1, STATE_COPY_DEST, stencil); + } else { + transition_plane_subs(list, res, true, per_plane, 1, stencil, None); + } + } + } + SyncOp::DepthToTwin { res, depth, stencil } => { + let res = *res; + let res_ptr = res as *mut c_void; + let Some(depth_res) = ID3D12Resource::from_raw_borrowed(&res_ptr) else { + continue; + }; + let snapshot = { + let g = ENTRIES.lock().unwrap(); + g.as_ref().and_then(|m| m.get(&res)).map(|e| { + ( + e.plan, + e.width, + e.height, + e.array_size, + e.mip_levels, + e.subresources_per_plane(), + e.depth_twin.clone(), + e.stencil_twin.clone(), + ) + }) + }; + let Some((plan, width, height, array_size, mip_levels, per_plane, depth_twin, stencil_twin)) = snapshot else { + continue; + }; + + if !depth.is_empty() { + if let Some(twin) = depth_twin { + match plan.depth_sync { + DepthSyncKind::DirectCopy => { + let twin_raw = twin.as_raw() as usize; + transition_plane_subs(list, res, false, per_plane, 0, depth, Some(STATE_COPY_SOURCE)); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + copy_direct_subs(list, &twin, depth_res, per_plane, depth); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, false, per_plane, 0, STATE_COPY_SOURCE, depth); + } + DepthSyncKind::BufferThrough => { + let twin_raw = twin.as_raw() as usize; + transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_COPY_SOURCE)); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + let _ = copy_plane_through_buffer(list, &dev, &twin, 0, depth_res, 0, per_plane, depth); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 0, STATE_COPY_SOURCE, depth); + } + DepthSyncKind::FullscreenPass { twin_srv_fmt, twin_uav_fmt } => { + let heaps = { + let mut g = ENTRIES.lock().unwrap(); + g.as_mut().and_then(|m| m.get_mut(&res)).and_then(|e| ensure_pass_heaps(&dev, depth_res, &twin, e, twin_srv_fmt, twin_uav_fmt)) + }; + if let (Some((_, _, cs_rs, cs_pso)), Some((_, srv_heap))) = (get_pipelines(&dev), heaps) { + transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_SRV_ALL)); + let srv_raw = srv_heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 14)); + + set_heaps(list, 1, &srv_raw); + set_cs_rs(list, cs_rs.as_raw()); + set_pso(list, cs_pso.as_raw()); + let gpu_base = srv_heap.GetGPUDescriptorHandleForHeapStart().ptr; + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as u64; + set_cs_table(list, 1, gpu_base + inc); + let mips_u32 = mip_levels as u32; + let mut dispatched_mips = vec![false; mips_u32 as usize]; + for &(local_sub, _, _) in depth { + let m = local_sub % mips_u32; + if dispatched_mips[m as usize] { + continue; + } + dispatched_mips[m as usize] = true; + let mw = ((width as u32) >> m).max(1); + let mh = (height >> m).max(1); + let c = [mw, mh, array_size as u32, m]; + set_cs_consts(list, 0, 4, c.as_ptr(), 0); + set_cs_table(list, 2, gpu_base + (2 + m as u64) * inc); + dispatch(list, mw.div_ceil(8), mh.div_ceil(8), array_size as u32); + } + // Order internal compute UAV writes to `twin` before subsequent title dispatches. + let twin_raw = twin.as_raw() as usize; + let uav_barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::transmute_copy(&twin_raw), + }), + }, + }; + list_x::pc_resource_barriers(list, &[uav_barrier]); + transition_plane_from(list, res, true, per_plane, 0, STATE_SRV_ALL, depth); + clobbered_cs = true; + } else { + transition_plane_subs(list, res, true, per_plane, 0, depth, None); + } + } + } + } else { + transition_plane_subs(list, res, plan.two_plane, per_plane, 0, depth, None); + } + } + + if plan.two_plane && !stencil.is_empty() { + if let Some(twin) = stencil_twin { + let twin_raw = twin.as_raw() as usize; + transition_plane_subs(list, res, true, per_plane, 1, stencil, Some(STATE_COPY_SOURCE)); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST); + let _ = copy_plane_through_buffer(list, &dev, &twin, 0, depth_res, 1, per_plane, stencil); + list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + transition_plane_from(list, res, true, per_plane, 1, STATE_COPY_SOURCE, stencil); + } else { + transition_plane_subs(list, res, true, per_plane, 1, stencil, None); + } + } + } + } + } + + if clobbered_gfx || clobbered_cs { + list_x::restore_after_internal_pass(list, clobbered_gfx, clobbered_cs); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn twin_plans_cover_console_depth_formats() { + let d32 = plan_for_console_format(40).expect("D32_FLOAT"); + assert_eq!((d32.depth_twin_fmt, d32.stencil_twin_fmt, d32.depth_sync, d32.two_plane), (39, None, DepthSyncKind::DirectCopy, false)); + + let d16 = plan_for_console_format(55).expect("D16_UNORM"); + assert_eq!((d16.depth_twin_fmt, d16.stencil_twin_fmt, d16.depth_sync, d16.two_plane), (53, None, DepthSyncKind::DirectCopy, false)); + + let d32s8 = plan_for_console_format(20).expect("D32_FLOAT_S8X24_UINT"); + assert_eq!((d32s8.depth_twin_fmt, d32s8.stencil_twin_fmt, d32s8.depth_sync, d32s8.two_plane), (39, Some(60), DepthSyncKind::BufferThrough, true)); + + let d16s8 = plan_for_console_format(118).expect("D16_UNORM_S8_UINT"); + assert_eq!(d16s8.depth_twin_fmt, 53); + assert_eq!(d16s8.stencil_twin_fmt, Some(60)); + assert!(d16s8.two_plane); + assert_eq!(d16s8.depth_sync, DepthSyncKind::FullscreenPass { twin_srv_fmt: 56, twin_uav_fmt: 56 }); + + let d24s8 = plan_for_console_format(45).expect("D24_UNORM_S8_UINT"); + assert_eq!(d24s8.depth_twin_fmt, 39); + assert_eq!(d24s8.stencil_twin_fmt, Some(60)); + assert_eq!(d24s8.depth_sync, DepthSyncKind::FullscreenPass { twin_srv_fmt: 41, twin_uav_fmt: 41 }); + + assert!(plan_for_console_format(28).is_none(), "color format has no depth twin plan"); + } + + #[test] + fn uav_format_and_plane_classification() { + // Stencil plane detection via format or explicit PlaneSlice == 1 + assert!(is_stencil_uav_format(62, 0)); // R8_UINT + assert!(is_stencil_uav_format(120, 0)); // console X16_TYPELESS_G8_UINT + assert!(is_stencil_uav_format(47, 0)); // X24_TYPELESS_G8_UINT + assert!(is_stencil_uav_format(22, 0)); // X32_TYPELESS_G8X24_UINT + assert!(is_stencil_uav_format(0, 1)); // explicit PlaneSlice 1 + assert!(!is_stencil_uav_format(56, 0)); // R16_UNORM depth + assert!(!is_stencil_uav_format(41, 0)); // R32_FLOAT depth + + // Legal typed UAV formats on each typeless twin + assert_eq!(twin_uav_format(60, 120), 62); + assert_eq!(twin_uav_format(60, 61), 61); + assert_eq!(twin_uav_format(53, 118), 56); + assert_eq!(twin_uav_format(53, 57), 57); + assert_eq!(twin_uav_format(39, 40), 41); + assert_eq!(twin_uav_format(39, 42), 42); + + // Subresource plane split (2 mips * 3 slices = 6 subresources per plane) + assert_eq!(plane_for_subresource(D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, 2, 3, true), PlaneMask::Both); + assert_eq!(plane_for_subresource(0, 2, 3, true), PlaneMask::Depth); + assert_eq!(plane_for_subresource(5, 2, 3, true), PlaneMask::Depth); + assert_eq!(plane_for_subresource(6, 2, 3, true), PlaneMask::Stencil); + assert_eq!(plane_for_subresource(11, 2, 3, true), PlaneMask::Stencil); + assert_eq!(plane_for_subresource(D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, 2, 3, false), PlaneMask::Depth); + } + + #[test] + fn state_machine_handles_split_and_async_compute_transitions() { + let plan = plan_for_console_format(118).unwrap(); + let mut e = Entry::new(0x1, plan, 1920, 1080, 1, 1, STATE_DEPTH_WRITE, true); + + // Without twins allocated yet, leaving UAV becomes a plain TransitionOnly (DEPTH_WRITE -> DEPTH_READ) + let (pass, uav, op) = decide_transition(&mut e, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, STATE_UAV, 0x20, 0, true); + assert!(!pass && uav); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![(0, STATE_DEPTH_WRITE, 0x20)], + stencil: vec![(0, STATE_DEPTH_WRITE, 0x20)], + }) + ); + assert_eq!((e.pc_states_depth[0], e.pc_states_stencil[0]), (0x20, 0x20)); + + // Split barrier BEGIN_ONLY touching UAV is suppressed, and END_ONLY performs the atomic transition + let (pass, uav, op) = decide_transition(&mut e, 1, 0x20, STATE_UAV, 1, true); + assert!(!pass && !uav && op.is_none()); + assert!(e.split_uav_stencil[0] && !e.split_uav_depth[0]); + + let (pass, uav, op) = decide_transition(&mut e, 1, 0x20, STATE_UAV, 2, true); + assert!(!pass && uav); + assert!(!e.split_uav_stencil[0]); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![], + stencil: vec![(0, 0x20, STATE_DEPTH_WRITE)], + }) + ); + // Plane 0 stayed in DEPTH_READ while plane 1 moved to DEPTH_WRITE + assert_eq!((e.pc_states_depth[0], e.pc_states_stencil[0]), (0x20, STATE_DEPTH_WRITE)); + + // Multi-mip per-subresource tracking: transitioning only mip 1 must leave mip 0 untouched + // and entering UAV must use each subresource's tracked PC state as StateBefore (not title `before`). + let mut multi = Entry::new(0x1, plan, 512, 512, 1, 2, STATE_DEPTH_WRITE, false); + let (pass, _, op) = decide_transition(&mut multi, 1, STATE_DEPTH_WRITE, 0x20, 0, true); + assert!(pass && op.is_none()); + assert_eq!(multi.pc_states_depth, vec![STATE_DEPTH_WRITE, 0x20]); + let (pass, uav, op) = decide_transition(&mut multi, 1, STATE_COMMON, STATE_UAV, 0, true); + assert!(!pass && uav); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![(1, 0x20, STATE_DEPTH_WRITE)], + stencil: vec![], + }), + "single-subresource UAV entry transitions only mip 1 from its tracked PC state 0x20" + ); + assert_eq!(multi.pc_states_depth, vec![STATE_DEPTH_WRITE, STATE_DEPTH_WRITE]); + + // On a COMPUTE list, UAV transitions are suppressed with a global UAV barrier (no invalid DEPTH state) + let (pass, uav, op) = decide_transition(&mut e, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, STATE_UAV, STATE_COMMON, 0, false); + assert!(!pass && uav && op.is_none()); + } + + #[test] + fn uav_barrier_returns_zero_for_untracked_resources() { + assert_eq!(on_uav_barrier(0), [0, 0]); + assert_eq!(on_uav_barrier(0xDEAD_BEE0), [0, 0]); + } + + #[test] + fn enhanced_barriers_handle_texture_subresources_uav_and_discard() { + // Layout + access -> valid PC resource state (never STATE_UAV or buffer-only bits) + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ), + STATE_DEPTH_READ + ); + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ), + STATE_DEPTH_READ + ); + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_COMMON, D3D12_BARRIER_ACCESS_SHADER_RESOURCE), + STATE_SRV_ALL + ); + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS), + STATE_DEPTH_WRITE + ); + assert_eq!( + enhanced_layout_to_pc_state(D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS), + STATE_DEPTH_WRITE + ); + + let plan = plan_for_console_format(44).unwrap(); + let mut e = Entry::new(0x1, plan, 2560, 1440, 1, 2, STATE_COMMON, false); + let all = D3D12_BARRIER_SUBRESOURCE_RANGE { + IndexOrFirstMipLevel: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + NumMipLevels: 0, + FirstArraySlice: 0, + NumArraySlices: 0, + FirstPlane: 0, + NumPlanes: 0, + }; + assert_eq!(resolve_enhanced_subresources(&e, &all), (vec![0, 1], vec![0, 1])); + + // Plane-specific range: stencil plane only, mip 1 only + let stencil_mip1 = D3D12_BARRIER_SUBRESOURCE_RANGE { + IndexOrFirstMipLevel: 1, + NumMipLevels: 1, + FirstArraySlice: 0, + NumArraySlices: 1, + FirstPlane: 1, + NumPlanes: 1, + }; + assert_eq!(resolve_enhanced_subresources(&e, &stencil_mip1), (vec![], vec![1])); + + // Without twins materialized yet, leaving UAV produces TransitionOnly -> DEPTH_READ + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + &all, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + true, + ); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![(0, STATE_COMMON, STATE_DEPTH_READ), (1, STATE_COMMON, STATE_DEPTH_READ)], + stencil: vec![(0, STATE_COMMON, STATE_DEPTH_READ), (1, STATE_COMMON, STATE_DEPTH_READ)], + }) + ); + assert_eq!(e.pc_states_depth, vec![STATE_DEPTH_READ, STATE_DEPTH_READ]); + assert_eq!(e.pc_states_stencil, vec![STATE_DEPTH_READ, STATE_DEPTH_READ]); + + // DISCARD entering DEPTH_STENCIL_WRITE marks plane dirty and transitions DEPTH_READ -> DEPTH_WRITE + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS_NO_ACCESS, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_WRITE, + D3D12_BARRIER_LAYOUT_UNDEFINED, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_WRITE, + &all, + D3D12_TEXTURE_BARRIER_FLAG_DISCARD, + true, + ); + assert_eq!( + op, + Some(SyncOp::TransitionOnly { + res: 0, + depth: vec![(0, STATE_DEPTH_READ, STATE_DEPTH_WRITE), (1, STATE_DEPTH_READ, STATE_DEPTH_WRITE)], + stencil: vec![(0, STATE_DEPTH_READ, STATE_DEPTH_WRITE), (1, STATE_DEPTH_READ, STATE_DEPTH_WRITE)], + }) + ); + assert!(e.depth_plane_dirty && e.stencil_plane_dirty); + + // Non-DIRECT list never returns a SyncOp + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + &all, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + false, + ); + assert!(op.is_none()); + } + + /// GPU: verify `D24_UNORM_S8_UINT` (console fmt 44) and `D16_UNORM_S8_UINT` (console fmt 118) + /// compute UAV writes (`permutation / 65535.0` depth + per-pixel stencil) synchronize cleanly + /// via BOTH enhanced texture barriers (`#146` `D3D12_TEXTURE_BARRIER`) AND global UAV barriers + /// + `before_bind_dsv`, passing exact `DepthFunc = EQUAL` draws while preserving stencil. + #[test] + fn gpu_d24s8_and_d16s8_enhanced_barrier_twin_sync_passes_equal_depth_test() { + unsafe { + let dev: ID3D12Device = { + use windows::Win32::Graphics::Dxgi::*; + if std::env::var_os("XCL_D3D12_DEBUG").is_some() { + let _ = crate::gpu::agility::enable_debug_layer(); + } + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let adapter: Option = if sel == crate::gpu::adapter::Selector::Warp { + let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { + return crate::gpu::recomp::runner::skip_test("no DXGI factory"); + }; + let Ok(warp) = factory.EnumWarpAdapter::() else { + return crate::gpu::recomp::runner::skip_test("no WARP adapter"); + }; + Some(warp.cast().unwrap()) + } else { + None + }; + let Ok(d) = crate::gpu::agility::create_device(adapter.as_ref(), windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + d + }; + let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut fence_val = 0u64; + + let wait_gpu = |q: &ID3D12CommandQueue, fence: &ID3D12Fence, val: &mut u64| { + *val += 1; + q.Signal(fence, *val).unwrap(); + while fence.GetCompletedValue() < *val { + std::thread::yield_now(); + } + }; + + // Compute shader writing 4 quadrant permutations (1, 17, 42, 120) / 65535.0 to depth twin + // and (0x11, 0x22, 0x5A, 0xA5) to stencil twin; c0 overrides quadrant 0 permutation. + let cs_write = compile_sm5( + "RWTexture2D dstD : register(u0);\n\ + RWTexture2D dstS : register(u1);\n\ + cbuffer C : register(b0) { uint q0_perm; };\n\ + [numthreads(8, 8, 1)]\n\ + void main(uint3 id : SV_DispatchThreadID) {\n\ + uint q = (id.x >= 8 ? 1u : 0u) + (id.y >= 8 ? 2u : 0u);\n\ + uint perm = (q == 0u) ? q0_perm : ((q == 1u) ? 17u : ((q == 2u) ? 42u : 120u));\n\ + uint st = (q == 0u) ? 0x11u : ((q == 1u) ? 0x22u : ((q == 2u) ? 0x5Au : 0xA5u));\n\ + dstD[id.xy] = float(perm) / 65535.0;\n\ + dstS[id.xy] = st;\n\ + }\n", + "cs_5_0", + ) + .expect("cs_write"); + let uav_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 2, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let cs_params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 1 }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &uav_range }, + }, + }, + ]; + let mut rs_blob = None; + D3D12SerializeRootSignature( + &D3D12_ROOT_SIGNATURE_DESC { NumParameters: 2, pParameters: cs_params.as_ptr(), ..Default::default() }, + D3D_ROOT_SIGNATURE_VERSION_1, + &mut rs_blob, + None, + ) + .unwrap(); + let rs_blob = rs_blob.unwrap(); + let cs_rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(rs_blob.GetBufferPointer() as *const u8, rs_blob.GetBufferSize())).unwrap(); + let mut cs_pso_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(cs_rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs_write.as_ptr() as _, BytecodeLength: cs_write.len() }, + ..Default::default() + }; + let cs_pso: ID3D12PipelineState = dev.CreateComputePipelineState(&cs_pso_desc).unwrap(); + ManuallyDrop::drop(&mut cs_pso_desc.pRootSignature); + + // Graphics EQUAL test shader: VS outputs z = target_perm / 65535.0, PS writes solid 0xFF red. + let eq_vs = compile_sm5( + "cbuffer C : register(b0) { uint target_perm; };\n\ + float4 main(uint id : SV_VertexID) : SV_Position {\n\ + float2 p = float2((id == 2) ? 3.0 : -1.0, (id == 1) ? 3.0 : -1.0);\n\ + return float4(p, float(target_perm) / 65535.0, 1.0);\n\ + }\n", + "vs_5_0", + ) + .expect("eq_vs"); + let eq_ps = compile_sm5("float4 main() : SV_Target { return float4(1.0, 0.0, 0.0, 1.0); }\n", "ps_5_0").expect("eq_ps"); + let eq_param = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_VERTEX, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 1 }, + }, + }; + let mut eq_rs_blob = None; + D3D12SerializeRootSignature( + &D3D12_ROOT_SIGNATURE_DESC { NumParameters: 1, pParameters: &eq_param, ..Default::default() }, + D3D_ROOT_SIGNATURE_VERSION_1, + &mut eq_rs_blob, + None, + ) + .unwrap(); + let eq_rs_blob = eq_rs_blob.unwrap(); + let eq_rs: ID3D12RootSignature = dev.CreateRootSignature(0, std::slice::from_raw_parts(eq_rs_blob.GetBufferPointer() as *const u8, eq_rs_blob.GetBufferSize())).unwrap(); + let mut eq_pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(eq_rs.clone())), + VS: D3D12_SHADER_BYTECODE { pShaderBytecode: eq_vs.as_ptr() as _, BytecodeLength: eq_vs.len() }, + PS: D3D12_SHADER_BYTECODE { pShaderBytecode: eq_ps.as_ptr() as _, BytecodeLength: eq_ps.len() }, + SampleMask: u32::MAX, + BlendState: D3D12_BLEND_DESC { + RenderTarget: [ + D3D12_RENDER_TARGET_BLEND_DESC { RenderTargetWriteMask: 0xF, ..Default::default() }, + Default::default(), Default::default(), Default::default(), + Default::default(), Default::default(), Default::default(), Default::default(), + ], + ..Default::default() + }, + RasterizerState: D3D12_RASTERIZER_DESC { FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() }, + DepthStencilState: D3D12_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO, + DepthFunc: D3D12_COMPARISON_FUNC_EQUAL, + StencilEnable: false.into(), + ..Default::default() + }, + PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, + NumRenderTargets: 1, + RTVFormats: [DXGI_FORMAT_R8G8B8A8_UNORM, Default::default(), Default::default(), Default::default(), Default::default(), Default::default(), Default::default(), Default::default()], + DSVFormat: DXGI_FORMAT_D24_UNORM_S8_UINT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + let eq_pso: ID3D12PipelineState = dev.CreateGraphicsPipelineState(&eq_pso_desc).unwrap(); + ManuallyDrop::drop(&mut eq_pso_desc.pRootSignature); + + // Helper descriptors & heaps + let rt_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let mut rt: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, + None, + &mut rt, + ) + .unwrap(); + let rt = rt.unwrap(); + + let rtv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: 1, ..Default::default() }).unwrap(); + let rtv_cpu = rtv_heap.GetCPUDescriptorHandleForHeapStart(); + dev.CreateRenderTargetView(&rt, None, rtv_cpu); + + let dsv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, NumDescriptors: 1, ..Default::default() }).unwrap(); + let dsv_cpu = dsv_heap.GetCPUDescriptorHandleForHeapStart(); + + let uav_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + ..Default::default() + }) + .unwrap(); + let uav_cpu_base = uav_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let uav_gpu_base = uav_heap.GetGPUDescriptorHandleForHeapStart().ptr; + let uav_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + + let rb_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 16 * 1024, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut rb_rt: Option = None; + let mut rb_st: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb_rt).unwrap(); + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &rb_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb_st).unwrap(); + let (rb_rt, rb_st) = (rb_rt.unwrap(), rb_st.unwrap()); + + let pc_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R24G8_TYPELESS, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let mut rt_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + dev.GetCopyableFootprints(&rt_desc, 0, 1, 0, Some(&mut rt_fp), None, None, None); + let mut st_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + dev.GetCopyableFootprints(&pc_desc, 1, 1, 0, Some(&mut st_fp), None, None, None); + + // Create both depth-stencil targets BEFORE adopting `dev` so test heaps/resources stay + // pure unadopted PC COM objects (no console vtable ABI or global UMA side effects). + let mut depth_targets: Vec<(u32, ID3D12Resource)> = Vec::new(); + for console_fmt in [44u32, 118u32] { + let mut depth_res: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &pc_desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut depth_res, + ) + .unwrap(); + depth_targets.push((console_fmt, depth_res.unwrap())); + } + + // Adopt dev + list so `depth_uav` internal helpers use `real::orig_fn` cleanly. + real::adopt(dev.as_raw(), real::Kind::Device); + real::adopt(list.as_raw(), real::Kind::CommandList); + list_x::on_create(list.as_raw(), alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + + type CreateUavOrig = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + type CreateDsvOrig = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, usize); + let create_uav_orig: CreateUavOrig = std::mem::transmute(real::orig_fn(dev.as_raw(), 19)); + let create_dsv_orig: CreateDsvOrig = std::mem::transmute(real::orig_fn(dev.as_raw(), 21)); + + for (console_fmt, depth_res) in depth_targets { + let mut console_desc = [0u8; 0x38]; + console_desc[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + console_desc[0x10..0x18].copy_from_slice(&16u64.to_le_bytes()); + console_desc[0x18..0x1C].copy_from_slice(&16u32.to_le_bytes()); + console_desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x20..0x24].copy_from_slice(&console_fmt.to_le_bytes()); + console_desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + console_desc[0x30..0x34].copy_from_slice(&6u32.to_le_bytes()); // DEPTH_STENCIL | UAV + + register_if_depth_uav(dev.as_raw(), depth_res.as_raw(), &console_desc, STATE_COMMON, STATE_COMMON); + + let dsv_desc = D3D12_DEPTH_STENCIL_VIEW_DESC { + Format: DXGI_FORMAT_D24_UNORM_S8_UINT, + ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D, + Flags: D3D12_DSV_FLAG_READ_ONLY_DEPTH | D3D12_DSV_FLAG_READ_ONLY_STENCIL, + ..Default::default() + }; + create_dsv_orig(dev.as_raw(), depth_res.as_raw(), &dsv_desc, dsv_cpu.ptr); + note_dsv(dsv_cpu.ptr, depth_res.as_raw() as usize, dsv_desc.Flags.0 as u32); + + let depth_uav_req = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let stencil_uav_req = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_X24_TYPELESS_G8_UINT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let (d_twin_raw, d_uav_desc) = resolve_uav(dev.as_raw(), depth_res.as_raw(), Some(&depth_uav_req)).expect("depth twin"); + let (s_twin_raw, s_uav_desc) = resolve_uav(dev.as_raw(), depth_res.as_raw(), Some(&stencil_uav_req)).expect("stencil twin"); + create_uav_orig(dev.as_raw(), d_twin_raw, std::ptr::null_mut(), &d_uav_desc, uav_cpu_base); + create_uav_orig(dev.as_raw(), s_twin_raw, std::ptr::null_mut(), &s_uav_desc, uav_cpu_base + uav_inc); + + // --- Phase 1: Compute writes twins -> Enhanced #146 Texture Barrier (UAV -> DEPTH_READ) -> EQUAL draw (perm 42) --- + let set_heaps_orig: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list.as_raw(), 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list.as_raw(), 29)); + let set_gfx_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list.as_raw(), 30)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list.as_raw(), 31)); + let set_cs_const: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 33)); + let set_gfx_const: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 34)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list.as_raw(), 25)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 14)); + let draw: unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 12)); + let set_topo: unsafe extern "system" fn(*mut c_void, u32) = std::mem::transmute(real::orig_fn(list.as_raw(), 20)); + let set_vp: unsafe extern "system" fn(*mut c_void, u32, *const D3D12_VIEWPORT) = std::mem::transmute(real::orig_fn(list.as_raw(), 21)); + let set_sc: unsafe extern "system" fn(*mut c_void, u32, *const RECT) = std::mem::transmute(real::orig_fn(list.as_raw(), 22)); + let set_rt: unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize) = std::mem::transmute(real::orig_fn(list.as_raw(), 46)); + let clear_rt: unsafe extern "system" fn(*mut c_void, usize, *const [f32; 4], u32, *const RECT) = std::mem::transmute(real::orig_fn(list.as_raw(), 48)); + + let uav_heap_raw = uav_heap.as_raw() as usize; + set_heaps_orig(list.as_raw(), 1, &uav_heap_raw); + set_cs_rs(list.as_raw(), cs_rs.as_raw()); + set_pso(list.as_raw(), cs_pso.as_raw()); + set_cs_const(list.as_raw(), 0, 1, 0); // q0_perm = 1 + set_cs_table(list.as_raw(), 1, uav_gpu_base); + dispatch(list.as_raw(), 2, 2, 1); + + // Enhanced #146 Texture Barrier: UNORDERED_ACCESS -> DEPTH_STENCIL_READ + let tb = D3D12_TEXTURE_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_COMPUTE_SHADING, + SyncAfter: D3D12_BARRIER_SYNC_DEPTH_STENCIL, + AccessBefore: D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + AccessAfter: D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + LayoutBefore: D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + LayoutAfter: D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + pResource: ManuallyDrop::new(Some(depth_res.clone())), + Subresources: D3D12_BARRIER_SUBRESOURCE_RANGE { + IndexOrFirstMipLevel: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + NumMipLevels: 0, + FirstArraySlice: 0, + NumArraySlices: 0, + FirstPlane: 0, + NumPlanes: 0, + }, + Flags: D3D12_TEXTURE_BARRIER_FLAG_NONE, + }; + let grp = D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_TEXTURE, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: &tb }, + }; + let mut ops = Vec::new(); + let had_global = filter_enhanced_barriers(1, &grp as *const _ as *const c_void, true, &mut ops); + ManuallyDrop::drop(&mut { tb }.pResource); + assert!(!had_global); + assert_eq!(ops.len(), 1, "enhanced texture barrier must queue TwinToDepth"); + execute_syncs(list.as_raw(), &ops); + + // Draw with DepthFunc = EQUAL at z = 42 / 65535.0 + let black = [0.0f32; 4]; + clear_rt(list.as_raw(), rtv_cpu.ptr, &black, 0, std::ptr::null()); + let vp = D3D12_VIEWPORT { TopLeftX: 0.0, TopLeftY: 0.0, Width: 16.0, Height: 16.0, MinDepth: 0.0, MaxDepth: 1.0 }; + let sc = RECT { left: 0, top: 0, right: 16, bottom: 16 }; + set_vp(list.as_raw(), 1, &vp); + set_sc(list.as_raw(), 1, &sc); + set_rt(list.as_raw(), 1, &rtv_cpu.ptr, 0, &dsv_cpu.ptr); + set_gfx_rs(list.as_raw(), eq_rs.as_raw()); + set_pso(list.as_raw(), eq_pso.as_raw()); + set_topo(list.as_raw(), D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + set_gfx_const(list.as_raw(), 0, 42, 0); + draw(list.as_raw(), 3, 1, 0, 0); + + // Copy RT + stencil plane (subresource 1) to readback + list_x::transition(list.as_raw(), rt.as_raw() as usize, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + let dst_rt = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { pResource: ManuallyDrop::new(Some(rb_rt.clone())), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: rt_fp } }); + let src_rt = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { pResource: ManuallyDrop::new(Some(rt.clone())), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }); + list_x::pc_copy_texture_region(list.as_raw(), &dst_rt.0, 0, 0, 0, &src_rt.0, std::ptr::null()); + list_x::transition(list.as_raw(), rt.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + + // Copy stencil plane (subresource 1) from DEPTH_READ -> COPY_SOURCE -> DEPTH_READ + let st_to_src = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&depth_res), + Subresource: 1, + StateBefore: D3D12_RESOURCE_STATE_DEPTH_READ, + StateAfter: D3D12_RESOURCE_STATE_COPY_SOURCE, + }), + }, + }; + list_x::pc_resource_barriers(list.as_raw(), &[st_to_src]); + let dst_st = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { pResource: ManuallyDrop::new(Some(rb_st.clone())), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: st_fp } }); + let src_st = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { pResource: ManuallyDrop::new(Some(depth_res.clone())), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 1 } }); + list_x::pc_copy_texture_region(list.as_raw(), &dst_st.0, 0, 0, 0, &src_st.0, std::ptr::null()); + let st_to_read = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(&depth_res), + Subresource: 1, + StateBefore: D3D12_RESOURCE_STATE_COPY_SOURCE, + StateAfter: D3D12_RESOURCE_STATE_DEPTH_READ, + }), + }, + }; + list_x::pc_resource_barriers(list.as_raw(), &[st_to_read]); + + let close_orig: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(real::orig_fn(list.as_raw(), 9)); + let hr_close = close_orig(list.as_raw()); + if hr_close != 0 { + if let Ok(iq) = dev.cast::() { + let n = iq.GetNumStoredMessages(); + for i in 0..n { + let mut sz = 0usize; + let _ = iq.GetMessage(i, None, &mut sz); + if sz > 0 { + let mut buf = vec![0u8; sz]; + if iq.GetMessage(i, Some(buf.as_mut_ptr() as *mut D3D12_MESSAGE), &mut sz).is_ok() { + let msg = &*(buf.as_ptr() as *const D3D12_MESSAGE); + let desc = std::ffi::CStr::from_ptr(msg.pDescription as *const i8).to_string_lossy(); + eprintln!("D3D12 INFO[{i}]: id={} sev={} {desc}", msg.ID.0, msg.Severity.0); + } + } + } + } + } + assert_eq!(hr_close, 0); + q.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + wait_gpu(&q, &fence, &mut fence_val); + + // Verify Phase 1 RT: ONLY quadrant 2 (x < 8, y >= 8, perm 42) passed EQUAL! + let mut mapped = std::ptr::null_mut(); + rb_rt.Map(0, None, Some(&mut mapped)).unwrap(); + let rt_bytes = std::slice::from_raw_parts(mapped as *const u8, 16 * rt_fp.Footprint.RowPitch as usize); + for (qx, qy, expect_r) in [(2usize, 2usize, 0u8), (10, 2, 0), (2, 10, 255), (10, 10, 0)] { + let r = rt_bytes[qy * rt_fp.Footprint.RowPitch as usize + qx * 4]; + assert_eq!(r, expect_r, "fmt {console_fmt} Phase 1 EQUAL(42) at ({qx},{qy})"); + } + rb_rt.Unmap(0, None); + + // Verify stencil survived FullscreenPass intact + let mut st_mapped = std::ptr::null_mut(); + rb_st.Map(0, None, Some(&mut st_mapped)).unwrap(); + let st_bytes = std::slice::from_raw_parts(st_mapped as *const u8, 16 * st_fp.Footprint.RowPitch as usize); + for (qx, qy, expect_s) in [(2usize, 2usize, 0x11u8), (10, 2, 0x22), (2, 10, 0x5A), (10, 10, 0xA5)] { + let s = st_bytes[qy * st_fp.Footprint.RowPitch as usize + qx]; + assert_eq!(s, expect_s, "fmt {console_fmt} stencil at ({qx},{qy})"); + } + rb_st.Unmap(0, None); + + // --- Phase 2: Global UAV barrier (#146 GLOBAL) + before_bind_dsv --- + alloc.Reset().unwrap(); + let reset_orig: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> i32 = std::mem::transmute(real::orig_fn(list.as_raw(), 10)); + assert_eq!(reset_orig(list.as_raw(), alloc.as_raw(), std::ptr::null_mut()), 0); + + set_heaps_orig(list.as_raw(), 1, &uav_heap_raw); + set_cs_rs(list.as_raw(), cs_rs.as_raw()); + set_pso(list.as_raw(), cs_pso.as_raw()); + set_cs_const(list.as_raw(), 0, 77, 0); // q0_perm = 77 + set_cs_table(list.as_raw(), 1, uav_gpu_base); + dispatch(list.as_raw(), 2, 2, 1); + + let gb = D3D12_GLOBAL_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_COMPUTE_SHADING, + SyncAfter: D3D12_BARRIER_SYNC_ALL, + AccessBefore: D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + AccessAfter: D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + }; + let ggrp = D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_GLOBAL, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { pGlobalBarriers: &gb }, + }; + let mut ops2 = Vec::new(); + assert!(filter_enhanced_barriers(1, &ggrp as *const _ as *const c_void, true, &mut ops2)); + assert!(ops2.is_empty()); + on_global_uav_barrier(); + before_bind_dsv(list.as_raw(), dsv_cpu.ptr); + + clear_rt(list.as_raw(), rtv_cpu.ptr, &black, 0, std::ptr::null()); + set_vp(list.as_raw(), 1, &vp); + set_sc(list.as_raw(), 1, &sc); + set_rt(list.as_raw(), 1, &rtv_cpu.ptr, 0, &dsv_cpu.ptr); + set_gfx_rs(list.as_raw(), eq_rs.as_raw()); + set_pso(list.as_raw(), eq_pso.as_raw()); + set_topo(list.as_raw(), D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); + set_gfx_const(list.as_raw(), 0, 77, 0); + draw(list.as_raw(), 3, 1, 0, 0); + + list_x::transition(list.as_raw(), rt.as_raw() as usize, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_x::pc_copy_texture_region(list.as_raw(), &dst_rt.0, 0, 0, 0, &src_rt.0, std::ptr::null()); + list_x::transition(list.as_raw(), rt.as_raw() as usize, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + assert_eq!(close_orig(list.as_raw()), 0); + q.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + wait_gpu(&q, &fence, &mut fence_val); + + let mut mapped2 = std::ptr::null_mut(); + rb_rt.Map(0, None, Some(&mut mapped2)).unwrap(); + let rt_bytes2 = std::slice::from_raw_parts(mapped2 as *const u8, 16 * rt_fp.Footprint.RowPitch as usize); + for (qx, qy, expect_r) in [(2usize, 2usize, 255u8), (10, 2, 0), (2, 10, 0), (10, 10, 0)] { + let r = rt_bytes2[qy * rt_fp.Footprint.RowPitch as usize + qx * 4]; + assert_eq!(r, expect_r, "fmt {console_fmt} Phase 2 global+before_bind_dsv EQUAL(77) at ({qx},{qy})"); + } + rb_rt.Unmap(0, None); + + forget(depth_res.as_raw() as usize); + alloc.Reset().unwrap(); + assert_eq!(reset_orig(list.as_raw(), alloc.as_raw(), std::ptr::null_mut()), 0); + } + if let Some(m) = PIPELINES.lock().unwrap().as_mut() { + m.remove(&(dev.as_raw() as usize)); + } + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 152431e22e..d66284ebea 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -872,11 +872,11 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { let view = pc_view_format(view); match (resource, view) { // R32G8X24_TYPELESS: depth 21, stencil 22 - (19..=22, 0 | 19 | 20 | 21 | 39 | 40 | 41) => 21, - (19..=22, 22 | 61 | 62) => 22, + (19..=22, 0 | 19 | 20 | 21 | 39 | 40 | 41 | 42 | 43) => 21, + (19..=22, 22 | 60..=64) => 22, // R24G8_TYPELESS: depth 46, stencil 47 - (44..=47, 0 | 41 | 44 | 45 | 46 | 53 | 54 | 55 | 56) => 46, - (44..=47, 47 | 61 | 62) => 47, + (44..=47, 0 | 41 | 42 | 44 | 45 | 46 | 53 | 54 | 55 | 56 | 57 | 59) => 46, + (44..=47, 47 | 60..=64) => 47, // R32_TYPELESS, R16_TYPELESS (39 | 40, 0 | 39 | 40) => 41, (53 | 55, 0 | 53 | 55) => 56, @@ -1067,6 +1067,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, note_alias(va as usize, &x); // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the // PC's: the PC refused the resource (E_INVALIDARG) and the title threw + let console_state = state; let state = pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state); let mut clear_buf = [0u8; 24]; let clear = pc_clear(clear, &mut clear_buf); @@ -1088,8 +1089,10 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, // sampled textures: on the same shared 64 KiB pages when tiled resources allow, else committed let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); let mut placed_hr = None; + let mut pc_tex_desc: Option = None; if !buffer { let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); + pc_tex_desc = Some(pc); let console_bytes = crate::hle::xg::Texture::new(&x).ok().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { @@ -1098,6 +1101,8 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, super::title_textures::retire_overlapping(va as usize, bytes as usize); } real::note_title_address(*ppv as usize, va as usize); + super::depth_uav::register_if_depth_uav(this, *ppv, &x, state, console_state); + super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); } return hr; } @@ -1113,21 +1118,27 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } }; if hr >= 0 && !buffer && !(*ppv).is_null() { + super::depth_uav::register_if_depth_uav(this, *ppv, &x, state, console_state); + let aliased_to_gpu = pc_tex_desc.as_ref().is_some_and(|pc| { + super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, pc, flags, state) + }); static M: AtomicU64 = AtomicU64::new(0); - match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { - Ok(()) => { - real::note_title_address(*ppv as usize, va as usize); - return hr; - } - Err(e) if once(&M, 4) => { - let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); - crate::xlog_warn!( - "D3D12.X: CreatePlacedResourceX texture at {va:#x} (dimension {} {}x{}x{}, {} mips, format {}, {} samples, layout {:#x}, flags {:#x}): not kept in step with the memory ({e})", - u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u16::from_le_bytes(x[0x1C..0x1E].try_into().unwrap()), - u16::from_le_bytes(x[0x1E..0x20].try_into().unwrap()), u(0x20), u(0x24), u(0x2C), u(0x30) - ) + if !aliased_to_gpu { + match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { + Ok(()) => { + real::note_title_address(*ppv as usize, va as usize); + return hr; + } + Err(e) if once(&M, 4) => { + let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + crate::xlog_warn!( + "D3D12.X: CreatePlacedResourceX texture at {va:#x} (dimension {} {}x{}x{}, {} mips, format {}, {} samples, layout {:#x}, flags {:#x}): not kept in step with the memory ({e})", + u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u16::from_le_bytes(x[0x1C..0x1E].try_into().unwrap()), + u16::from_le_bytes(x[0x1E..0x20].try_into().unwrap()), u(0x20), u(0x24), u(0x2C), u(0x30) + ) + } + Err(_) => {} } - Err(_) => {} } } if hr >= 0 && !(*ppv).is_null() { diff --git a/crates/xcl/src/hle/d3d12x/format_alias.rs b/crates/xcl/src/hle/d3d12x/format_alias.rs new file mode 100644 index 0000000000..81b5aabc1e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/format_alias.rs @@ -0,0 +1,1282 @@ +//! Placed UAV/SRV texture views (`Create{ShaderResource,UnorderedAccess}ViewAtX`) and +//! format-aliased GPU copies across incompatible DXGI format families. +//! +//! Console titles write packed lighting data (sky, light probes, volumetric fog) through a placed +//! UAV texture view in an integer format (such as `R32_UINT`) and sample the same title address +//! through a placed SRV view in an incompatible format of the same texel width (such as +//! `R9G9B9E5_SHAREDEXP`). On PC D3D12: +//! * `CreateUnorderedAccessViewAtX` often passes a resource desc without `ALLOW_UNORDERED_ACCESS` +//! (or with `R9G9B9E5_SHAREDEXP` / `SRGB`), which caused XCL to produce a null UAV view or +//! promote `R9G9B9E5` to `R11G11B10_FLOAT` (breaking `R32_UINT` views and RGB9E5 decoding). +//! * `CreateShaderResourceViewAtX` with `ALLOW_RENDER_TARGET | ALLOW_UNORDERED_ACCESS` bits still +//! set caused `R9G9B9E5_SHAREDEXP` to be promoted to `R11G11B10_FLOAT` and could register a +//! GPU-written texture in `title_textures` (overwriting GPU data with zeros from CPU memory). +//! * Direct `CopyResource` / `CopyTextureRegion` between different DXGI format families is invalid +//! on PC D3D12; texels of equal byte width must be transferred through an intermediate buffer +//! (`CopyTextureRegion` across all mips and array/depth slices). +//! +//! Set `XCL_FORMAT_ALIAS=0` to disable format-alias syncing. + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use super::list_x; +use super::real; + +const STATE_COMMON: u32 = 0; +const STATE_RENDER_TARGET: u32 = 0x4; +const STATE_UAV: u32 = 0x8; +const STATE_SRV_NON_PIXEL: u32 = 0x40; +const STATE_SRV_ALL: u32 = 0x40 | 0x80; + +const FLAG_RENDER_TARGET: u32 = 0x1; +const FLAG_DEPTH_STENCIL: u32 = 0x2; +const FLAG_UAV: u32 = 0x4; + +/// Geometry & format summary of a texture for alias / buffer-through copy compatibility checks. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct TexShape { + pub dimension: i32, + pub width: u64, + pub height: u32, + pub depth_or_array: u16, + pub mip_levels: u16, + pub format: u32, + pub samples: u32, +} + +impl TexShape { + pub(super) fn from_pc_desc(d: &D3D12_RESOURCE_DESC) -> Self { + Self { + dimension: d.Dimension.0, + width: d.Width, + height: d.Height, + depth_or_array: d.DepthOrArraySize.max(1), + mip_levels: d.MipLevels.max(1), + format: d.Format.0 as u32, + samples: d.SampleDesc.Count.max(1), + } + } + + pub(super) fn subresource_count(&self) -> u32 { + let slices = if self.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + 1 + } else { + self.depth_or_array as u32 + }; + (self.mip_levels as u32).saturating_mul(slices).max(1) + } +} + +/// `(bytes_per_element, is_4x4_block_compressed)` for common DXGI formats. +pub(super) fn format_element_bytes(fmt: u32) -> Option<(u32, bool)> { + match fmt { + // 128-bit uncompressed (16 bytes/texel) + 1..=4 => Some((16, false)), + // 96-bit uncompressed (12 bytes/texel) + 5..=8 => Some((12, false)), + // 64-bit uncompressed (8 bytes/texel): R16G16B16A16_*, R32G32_* + 9..=18 => Some((8, false)), + // 32-bit uncompressed (4 bytes/texel): R10G10B10A2_*, R11G11B10_FLOAT, R8G8B8A8_*, R16G16_*, R32_*, R9G9B9E5_SHAREDEXP, B8G8R8A8/X8_* + 23..=43 | 67 | 87..=93 => Some((4, false)), + // 16-bit uncompressed (2 bytes/texel): R8G8_*, R16_*, B5G6R5, B5G5R5A1, B4G4R4A4 + 48..=59 | 85 | 86 | 115 => Some((2, false)), + // 8-bit uncompressed (1 byte/texel): R8_*, A8_UNORM + 60..=65 => Some((1, false)), + // 4x4 block-compressed, 8 bytes/block: BC1, BC4 + 70..=72 | 79..=81 => Some((8, true)), + // 4x4 block-compressed, 16 bytes/block: BC2, BC3, BC5, BC6H, BC7 + 73..=78 | 82..=84 | 94..=99 => Some((16, true)), + _ => None, + } +} + +/// Canonical typeless family representative for a DXGI format. +pub(super) fn typeless_family(fmt: u32) -> u32 { + match fmt { + 1..=4 => 1, // R32G32B32A32_TYPELESS + 5..=8 => 5, // R32G32B32_TYPELESS + 9..=14 => 9, // R16G16B16A16_TYPELESS + 15..=18 => 15, // R32G32_TYPELESS + 19..=22 => 19, // R32G8X24_TYPELESS + 23..=25 => 23, // R10G10B10A2_TYPELESS + 27..=32 => 27, // R8G8B8A8_TYPELESS + 33..=38 => 33, // R16G16_TYPELESS + 39..=43 => 39, // R32_TYPELESS + 44..=47 => 44, // R24G8_TYPELESS + 48..=52 => 48, // R8G8_TYPELESS + 53..=59 => 53, // R16_TYPELESS + 60..=64 => 60, // R8_TYPELESS + 70..=72 => 70, // BC1_TYPELESS + 73..=75 => 73, // BC2_TYPELESS + 76..=78 => 76, // BC3_TYPELESS + 79..=81 => 79, // BC4_TYPELESS + 82..=84 => 82, // BC5_TYPELESS + 87 | 90 | 91 => 90, // B8G8R8A8_TYPELESS + 88 | 92 | 93 => 92, // B8G8R8X8_TYPELESS + 94..=96 => 94, // BC6H_TYPELESS + 97..=99 => 97, // BC7_TYPELESS + other => other, + } +} + +/// Whether `dst_fmt` and `src_fmt` belong to different DXGI typeless families (so direct +/// `CopyResource` is illegal on PC D3D12 and a buffer-through `CopyTextureRegion` is needed). +pub(super) fn needs_buffer_through(dst_fmt: u32, src_fmt: u32) -> bool { + dst_fmt != 0 && src_fmt != 0 && typeless_family(dst_fmt) != typeless_family(src_fmt) +} + +/// Whether two textures can exchange texels via an intermediate buffer (`CopyTextureRegion`). +pub(super) fn can_copy_through_buffer(dst: &TexShape, src: &TexShape) -> bool { + if dst.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 + || src.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 + || dst.dimension != src.dimension + || dst.samples > 1 + || src.samples > 1 + || dst.mip_levels != src.mip_levels + || dst.depth_or_array != src.depth_or_array + { + return false; + } + let (Some((db, dbc)), Some((sb, sbc))) = (format_element_bytes(dst.format), format_element_bytes(src.format)) else { + return false; + }; + if db != sb { + return false; + } + match (dbc, sbc) { + (false, false) | (true, true) => dst.width == src.width && dst.height == src.height, + (true, false) => src.width == dst.width.div_ceil(4) && src.height == dst.height.div_ceil(4), + (false, true) => dst.width == src.width.div_ceil(4) && dst.height == src.height.div_ceil(4), + } +} + +/// Choose a UAV-capable PC resource format that accepts `view_fmt` (or `rdesc_fmt` if `view_fmt == 0`). +pub(super) fn uav_resource_format(rdesc_fmt: u32, view_fmt: u32) -> u32 { + let target = if view_fmt != 0 { view_fmt } else { rdesc_fmt }; + // R9G9B9E5_SHAREDEXP cannot have ALLOW_UNORDERED_ACCESS on PC; use R32_TYPELESS when the + // view wants 32-bit integer/float UAV access, otherwise let device_x handle it. + if rdesc_fmt == 67 && view_fmt != 0 && view_fmt != 67 { + return typeless_family(view_fmt); + } + // sRGB formats cannot have ALLOW_UNORDERED_ACCESS on PC; use their typeless family. + if matches!(target, 29 | 91 | 93) { + return typeless_family(target); + } + // If the view requests a different family than the resource desc (e.g. R32_UINT view over + // an R9G9B9E5 or R11G11B10 resource), make the UAV texture typeless in the view's family. + if view_fmt != 0 && typeless_family(rdesc_fmt) != typeless_family(view_fmt) { + return typeless_family(view_fmt); + } + // Use typeless when available so both typed UAV and SRV views match cleanly. + let fam = typeless_family(target); + match fam { + 1 | 9 | 15 | 23 | 27 | 33 | 39 | 48 | 53 | 60 | 90 => fam, + _ => target, + } +} + +/// Sanitize a console resource desc for `CreateUnorderedAccessViewAtX`: guarantee +/// `ALLOW_UNORDERED_ACCESS` and a UAV-compatible format so PC D3D12 never drops it to a null view. +pub(super) fn prepare_placed_uav_desc(rdesc: &[u8; 0x38], view_fmt: u32) -> [u8; 0x38] { + let mut x = *rdesc; + x[0x34..].fill(0); + let rdesc_fmt = u32::from_le_bytes(x[0x20..0x24].try_into().unwrap()); + let mut flags = u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()); + let is_depth = flags & FLAG_DEPTH_STENCIL != 0 || matches!(rdesc_fmt, 19 | 20 | 40 | 44 | 45 | 55 | 118..=120); + if !is_depth { + // Strip RTV bit on placed UAV textures so integer/typeless UAV formats are never rejected + // by render-target format restrictions. + flags = (flags & !FLAG_RENDER_TARGET) | FLAG_UAV; + let fmt = uav_resource_format(rdesc_fmt, view_fmt); + x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); + } else { + flags |= FLAG_UAV; + } + x[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + x +} + +/// Sanitize a console resource desc for `CreateShaderResourceViewAtX`: strip `ALLOW_RENDER_TARGET` +/// and `ALLOW_UNORDERED_ACCESS` so `R9G9B9E5_SHAREDEXP` stays format 67 and placed SRVs never +/// retire or overwrite GPU-owned target tracking at `va`. +pub(super) fn prepare_placed_srv_desc(rdesc: &[u8; 0x38], view_fmt: u32) -> [u8; 0x38] { + let mut x = *rdesc; + x[0x34..].fill(0); + let rdesc_fmt = u32::from_le_bytes(x[0x20..0x24].try_into().unwrap()); + let mut flags = u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()); + flags &= !(FLAG_RENDER_TARGET | FLAG_UAV); + x[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + if view_fmt != 0 && typeless_family(rdesc_fmt) != typeless_family(view_fmt) && format_element_bytes(view_fmt).is_some() { + // Keep R9G9B9E5_SHAREDEXP (67) and other single-member formats verbatim; use typeless + // only when it belongs to a multi-format typeless family. + let fmt = match typeless_family(view_fmt) { + f if f == view_fmt => view_fmt, + f if matches!(f, 1 | 9 | 15 | 23 | 27 | 33 | 39 | 48 | 53 | 60 | 70 | 73 | 76 | 79 | 82 | 90 | 92 | 94 | 97) => f, + _ => view_fmt, + }; + x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); + } + x +} + +/// Ownership of a resource participating in format-alias tracking. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Owner { + /// Internal texture created by `dev_create_uav_at_x` (resting state: `UNORDERED_ACCESS`). + PlacedUav, + /// Internal texture created by `dev_create_srv_at_x` (resting state outside open list: `COMMON`). + PlacedSrv, + /// Title-created texture from `CreatePlacedResourceX` (tracked PC state). + TitlePlaced, +} + +struct TrackedTex { + device: usize, + va: usize, + shape: TexShape, + owner: Owner, + /// Per-subresource PC states (only tracked for `Owner::TitlePlaced`). + pc_states: Vec, + is_writer: bool, +} + +impl TrackedTex { + fn new(device: usize, va: usize, shape: TexShape, owner: Owner, initial_state: u32, is_writer: bool) -> Self { + let n = if owner == Owner::TitlePlaced { shape.subresource_count().max(1) as usize } else { 0 }; + Self { device, va, shape, owner, pc_states: vec![initial_state; n], is_writer } + } + + fn uniform_state(&self) -> Option { + let &first = self.pc_states.first()?; + self.pc_states.iter().all(|&s| s == first).then_some(first) + } + + fn update_state(&mut self, subresource: u32, after: u32) { + if subresource == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES { + self.pc_states.fill(after); + } else if let Some(slot) = self.pc_states.get_mut(subresource as usize) { + *slot = after; + } + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +struct AliasPair { + writer: usize, + reader: usize, + device: usize, + buffer_through: bool, + writer_owner: Owner, + reader_owner: Owner, +} + +struct AliasTable { + /// Cached internal placed-UAV textures: `(va, prepared_desc)` -> owned `ID3D12Resource`. + placed_uavs: HashMap<(u64, [u8; 0x38]), ID3D12Resource>, + /// Cached internal placed-SRV textures: `(va, prepared_desc)` -> owned `ID3D12Resource`. + placed_srvs: HashMap<(u64, [u8; 0x38]), ID3D12Resource>, + /// All tracked textures by raw resource pointer. + by_res: HashMap, + /// Title VA -> tracked resource pointers at that exact VA. + by_va: HashMap>, + /// Active `(writer -> reader)` sync pairs. + pairs: Vec, + /// Pairs whose writer is an internal `PlacedUav` (must be synced on UAV barriers). + placed_uav_pairs: usize, +} + +unsafe impl Send for AliasTable {} + +impl AliasTable { + fn new() -> Self { + Self { + placed_uavs: HashMap::new(), + placed_srvs: HashMap::new(), + by_res: HashMap::new(), + by_va: HashMap::new(), + pairs: Vec::new(), + placed_uav_pairs: 0, + } + } + + fn has_writer_at(&self, va: usize, shape: &TexShape) -> bool { + self.by_va.get(&va).is_some_and(|list| { + list.iter().any(|r| { + self.by_res.get(r).is_some_and(|t| t.is_writer && can_copy_through_buffer(shape, &t.shape)) + }) + }) + } + + /// Register `res` at `va` and link any compatible `(writer -> reader)` pairs at the same VA. + /// Returns any existing reader resources that should be marked `gpu_written` in `title_textures`. + fn insert(&mut self, res: usize, tex: TrackedTex) -> Vec { + self.remove(res); + let mut mark_gpu_written = Vec::new(); + let mut new_pairs = Vec::new(); + if let Some(peers) = self.by_va.get(&tex.va) { + for &peer in peers { + let Some(p) = self.by_res.get(&peer) else { + continue; + }; + if p.device != tex.device { + continue; + } + // Link writer -> reader when one is a PlacedUav (always needs sync to its SRV alias) + // OR when their formats are in different typeless families (format-aliased GPU textures). + if tex.is_writer && !p.is_writer && can_copy_through_buffer(&p.shape, &tex.shape) { + let bt = needs_buffer_through(p.shape.format, tex.shape.format); + if tex.owner == Owner::PlacedUav || bt { + new_pairs.push(AliasPair { + writer: res, + reader: peer, + device: tex.device, + buffer_through: bt, + writer_owner: tex.owner, + reader_owner: p.owner, + }); + mark_gpu_written.push(peer); + } + } else if !tex.is_writer && p.is_writer && can_copy_through_buffer(&tex.shape, &p.shape) { + let bt = needs_buffer_through(tex.shape.format, p.shape.format); + if p.owner == Owner::PlacedUav || bt { + new_pairs.push(AliasPair { + writer: peer, + reader: res, + device: tex.device, + buffer_through: bt, + writer_owner: p.owner, + reader_owner: tex.owner, + }); + mark_gpu_written.push(res); + } + } + } + } + for pair in new_pairs { + self.add_pair(pair); + } + self.by_va.entry(tex.va).or_default().push(res); + if tex.owner == Owner::TitlePlaced { + TRACKED_TITLE_TEX.fetch_add(1, Ordering::Relaxed); + } + self.by_res.insert(res, tex); + mark_gpu_written + } + + /// Evict cached internal `PlacedUav`/`PlacedSrv` resources at `va` whose shape no longer + /// matches `keep_shape` (or all internal resources at `va` when `keep_shape` is `None` and + /// no `TitlePlaced` peers remain at `va`), returning the evicted `ID3D12Resource`s to be + /// deferred-released outside the lock. + fn evict_stale_internal_at(&mut self, va: usize, keep_shape: Option<&TexShape>) -> Vec { + let mut evicted_ptrs = Vec::new(); + if let Some(list) = self.by_va.get(&va) { + let has_title = list.iter().any(|r| self.by_res.get(r).is_some_and(|t| t.owner == Owner::TitlePlaced)); + if keep_shape.is_none() && has_title { + return Vec::new(); + } + for &r in list { + let Some(t) = self.by_res.get(&r) else { continue }; + if t.owner == Owner::TitlePlaced { + continue; + } + let stale = match keep_shape { + Some(s) => !can_copy_through_buffer(s, &t.shape), + None => true, + }; + if stale { + evicted_ptrs.push(r); + } + } + } + let mut dropped = Vec::new(); + for r in evicted_ptrs { + self.remove(r); + let uav_keys: Vec<_> = self.placed_uavs.iter().filter(|(_, v)| v.as_raw() as usize == r).map(|(k, _)| *k).collect(); + for k in uav_keys { + if let Some(res) = self.placed_uavs.remove(&k) { + dropped.push(res); + } + } + let srv_keys: Vec<_> = self.placed_srvs.iter().filter(|(_, v)| v.as_raw() as usize == r).map(|(k, _)| *k).collect(); + for k in srv_keys { + if let Some(res) = self.placed_srvs.remove(&k) { + dropped.push(res); + } + } + } + dropped + } + + fn add_pair(&mut self, pair: AliasPair) { + if self.pairs.iter().any(|p| p.writer == pair.writer && p.reader == pair.reader) { + return; + } + if pair.writer_owner == Owner::PlacedUav { + self.placed_uav_pairs += 1; + ACTIVE_PLACED_UAV_PAIRS.store(self.placed_uav_pairs, Ordering::Relaxed); + } + ACTIVE_PAIRS.store(self.pairs.len() + 1, Ordering::Relaxed); + self.pairs.push(pair); + } + + fn remove(&mut self, res: usize) -> Option { + if let Some(old) = self.by_res.remove(&res) { + if old.owner == Owner::TitlePlaced { + TRACKED_TITLE_TEX.fetch_sub(1, Ordering::Relaxed); + } + if let Some(list) = self.by_va.get_mut(&old.va) { + list.retain(|&r| r != res); + if list.is_empty() { + self.by_va.remove(&old.va); + } + } + let before = self.pairs.len(); + self.pairs.retain(|p| p.writer != res && p.reader != res); + if self.pairs.len() != before { + self.placed_uav_pairs = self.pairs.iter().filter(|p| p.writer_owner == Owner::PlacedUav).count(); + ACTIVE_PLACED_UAV_PAIRS.store(self.placed_uav_pairs, Ordering::Relaxed); + ACTIVE_PAIRS.store(self.pairs.len(), Ordering::Relaxed); + } + return Some(old.va); + } + None + } +} + +static TABLE: Mutex> = Mutex::new(None); +static TRACKED_TITLE_TEX: AtomicUsize = AtomicUsize::new(0); +static ACTIVE_PAIRS: AtomicUsize = AtomicUsize::new(0); +static ACTIVE_PLACED_UAV_PAIRS: AtomicUsize = AtomicUsize::new(0); + +/// Defer releasing internal resources evicted from `placed_uavs` / `placed_srvs` until in-flight +/// GPU work has completed. +unsafe fn defer_drop_resources(evicted: Vec) { + for r in evicted { + super::late_release::hold(r.into_raw() as usize); + } +} + +/// D3D12 resource states legal in a `ResourceBarrier` on a `COMPUTE` command list for textures +/// (`COMMON`, `UNORDERED_ACCESS`, `NON_PIXEL_SHADER_RESOURCE`, `COPY_DEST`, `COPY_SOURCE`). +const COMPUTE_VALID_STATES: u32 = 0x8 | 0x40 | 0x400 | 0x800; + +fn state_valid_on_list(ty: D3D12_COMMAND_LIST_TYPE, st: u32) -> bool { + ty == D3D12_COMMAND_LIST_TYPE_DIRECT || (st & !COMPUTE_VALID_STATES == 0) +} + +/// Per-open-list state for `PlacedSrv` resources transitioned into read state on that list +/// (returned to `COMMON` before `Close()`), plus last synced `bind::activity()`. +#[derive(Default)] +struct ListSyncState { + /// `PlacedSrv` resource -> current state on this open list (`SRV_ALL` or `SRV_NON_PIXEL`). + srv_states: HashMap, + last_activity: (u64, u64), + list_type: Option, +} + +static LIST_STATES: Mutex>> = Mutex::new(None); + +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_FORMAT_ALIAS").is_ok_and(|v| v.trim() == "0")) +} + +unsafe fn create_internal_texture(dev: *mut c_void, pc_desc: &[u8; 0x38], initial_state: u32) -> Option { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = real::dev_create_committed_resource( + dev, + &heap as *const _ as usize, + 0, + pc_desc.as_ptr() as usize, + initial_state as usize, + 0, + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut out, + ); + if hr < 0 || out.is_null() { + return None; + } + Some(ID3D12Resource::from_raw(out)) +} + +/// Obtain or create the host UAV texture backing `CreateUnorderedAccessViewAtX` at `va`. +pub(super) unsafe fn placed_uav_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> *mut c_void { + if rdesc.is_null() || va == 0 || !crate::gpu::shader::readable(rdesc as usize, 0x38) { + return std::ptr::null_mut(); + } + let raw_x: [u8; 0x38] = (rdesc as *const [u8; 0x38]).read_unaligned(); + let prepared = prepare_placed_uav_desc(&raw_x, view_fmt); + let key = (va, prepared); + + { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + if let Some(res) = t.placed_uavs.get(&key) { + return res.as_raw(); + } + } + + let pc = super::device_x::pc_resource_desc(&prepared); + let flags = u32::from_le_bytes(prepared[0x30..0x34].try_into().unwrap()); + let is_depth_uav = flags & (FLAG_DEPTH_STENCIL | FLAG_UAV) == (FLAG_DEPTH_STENCIL | FLAG_UAV); + let init_state = if is_depth_uav { + super::device_x::pc_initial_state(flags, STATE_UAV) + } else { + STATE_UAV + }; + let Some(res) = create_internal_texture(dev, &pc, init_state) else { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: placed UAV texture at {va:#x} (view fmt {view_fmt}) could not be created"); + } + return std::ptr::null_mut(); + }; + let raw = res.as_raw(); + if is_depth_uav { + super::depth_uav::register_if_depth_uav(dev, raw, &prepared, init_state, STATE_UAV); + } + let pc_desc = res.GetDesc(); + let shape = TexShape::from_pc_desc(&pc_desc); + let mark = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + let entry = t.placed_uavs.entry(key).or_insert(res); + let raw_in = entry.as_raw(); + if raw_in == raw && !is_depth_uav && enabled() { + t.insert( + raw as usize, + TrackedTex::new(dev as usize, va as usize, shape, Owner::PlacedUav, STATE_UAV, true), + ) + } else { + Vec::new() + } + }; + for reader in mark { + super::title_textures::note_gpu_write(reader); + } + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: placed UAV texture at {va:#x} ({}x{}x{}, {} mips, pc fmt {}, view fmt {view_fmt}) -> {raw:p} ({} created)", + pc_desc.Width, + pc_desc.Height, + pc_desc.DepthOrArraySize, + pc_desc.MipLevels, + pc_desc.Format.0, + n + 1 + ); + } + raw +} + +/// Obtain or create the host SRV texture backing `CreateShaderResourceViewAtX` at `va`. +/// If a GPU writer already occupies `va` with a compatible shape, creates a dedicated GPU-synced +/// SRV texture (skipping `title_textures` so CPU zeros never overwrite GPU writes); otherwise +/// delegates to `create_placed_resource_x` and registers it as a reader in case a placed UAV +/// appears at `va` later. +pub(super) unsafe fn placed_srv_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> *mut c_void { + if rdesc.is_null() || va == 0 || !crate::gpu::shader::readable(rdesc as usize, 0x38) { + return std::ptr::null_mut(); + } + let raw_x: [u8; 0x38] = (rdesc as *const [u8; 0x38]).read_unaligned(); + let prepared = prepare_placed_srv_desc(&raw_x, view_fmt); + let key = (va, prepared); + let pc = super::device_x::pc_resource_desc(&prepared); + let pc_desc = std::ptr::read_unaligned(pc.as_ptr() as *const D3D12_RESOURCE_DESC); + let shape = TexShape::from_pc_desc(&pc_desc); + + let has_writer = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + if let Some(res) = t.placed_srvs.get(&key) { + return res.as_raw(); + } + enabled() && t.has_writer_at(va as usize, &shape) + }; + + let res = if has_writer { + // Dedicated GPU-synced SRV texture in COMMON state (not registered in title_textures). + match create_internal_texture(dev, &pc, STATE_COMMON) { + Some(r) => r, + None => return std::ptr::null_mut(), + } + } else { + let mut r = std::ptr::null_mut(); + let hr = super::device_x::create_placed_resource_x( + dev, + va, + prepared.as_ptr(), + 0, + std::ptr::null(), + &ID3D12Resource::IID as *const _ as *const windows_sys::core::GUID, + &mut r, + ); + if hr < 0 || r.is_null() { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!("D3D12.X: placed SRV texture at {va:#x}: resource creation failed ({hr:#x})"); + } + return std::ptr::null_mut(); + } + ID3D12Resource::from_raw(r) + }; + + let raw = res.as_raw(); + let owner = if has_writer { Owner::PlacedSrv } else { Owner::TitlePlaced }; + let mark = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + let entry = t.placed_srvs.entry(key).or_insert(res); + let raw_in = entry.as_raw(); + if raw_in == raw && enabled() { + t.insert( + raw as usize, + TrackedTex::new(dev as usize, va as usize, shape, owner, STATE_COMMON, false), + ) + } else { + Vec::new() + } + }; + for reader in mark { + super::title_textures::note_gpu_write(reader); + } + raw +} + +/// Register a title-created placed texture from `device_x::create_placed_resource_x`. +/// Returns `true` if the texture is already aliased to a GPU writer at `va` (so callers should +/// call `title_textures::note_gpu_write` and avoid CPU uploads over GPU-written texels). +pub(super) fn register_title_texture(dev: usize, res: usize, va: usize, pc_desc: &D3D12_RESOURCE_DESC, flags: u32, initial_state: u32) -> bool { + if !enabled() || res == 0 || va == 0 || pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return false; + } + let shape = TexShape::from_pc_desc(pc_desc); + if format_element_bytes(shape.format).is_none() || shape.samples > 1 { + return false; + } + let is_writer = flags & (FLAG_RENDER_TARGET | FLAG_UAV) != 0; + let (mark, evicted) = { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + let evicted = t.evict_stale_internal_at(va, Some(&shape)); + let mark = t.insert( + res, + TrackedTex::new(dev, va, shape, Owner::TitlePlaced, initial_state, is_writer), + ); + (mark, evicted) + }; + if !evicted.is_empty() { + unsafe { defer_drop_resources(evicted) }; + } + let mut self_gpu_written = false; + for r in mark { + if r == res { + self_gpu_written = true; + } + super::title_textures::note_gpu_write(r); + } + self_gpu_written +} + +/// Remove a released title resource from format-alias tracking, evicting any orphaned internal +/// `PlacedUav`/`PlacedSrv` textures at the same VA via deferred GPU release. +pub(super) fn forget(res: usize) { + let evicted = { + let mut g = TABLE.lock().unwrap(); + if let Some(t) = g.as_mut() { + let mut dropped = Vec::new(); + let va = t.remove(res); + let uav_keys: Vec<_> = t.placed_uavs.iter().filter(|(_, v)| v.as_raw() as usize == res).map(|(k, _)| *k).collect(); + for k in uav_keys { + if let Some(r) = t.placed_uavs.remove(&k) { + dropped.push(r); + } + } + let srv_keys: Vec<_> = t.placed_srvs.iter().filter(|(_, v)| v.as_raw() as usize == res).map(|(k, _)| *k).collect(); + for k in srv_keys { + if let Some(r) = t.placed_srvs.remove(&k) { + dropped.push(r); + } + } + if let Some(va) = va { + dropped.extend(t.evict_stale_internal_at(va, None)); + } + dropped + } else { + Vec::new() + } + }; + if !evicted.is_empty() { + unsafe { defer_drop_resources(evicted) }; + } + if let Some(m) = LIST_STATES.lock().unwrap().as_mut() { + for s in m.values_mut() { + s.srv_states.remove(&res); + } + } +} + +/// Track state transitions of title-owned textures (even before an alias peer is created at the +/// same VA) and collect any writers leaving `UNORDERED_ACCESS` / `RENDER_TARGET` whose +/// format-aliased readers need a copy. Ignores split-barrier `BEGIN_ONLY` flags. +pub(super) fn note_title_transition(res: usize, subresource: u32, before: u32, after: u32, flags: u32, writers_to_sync: &mut Vec<(usize, u32)>) { + const BARRIER_BEGIN_ONLY: u32 = 1; + if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 || flags == BARRIER_BEGIN_ONLY { + return; + } + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { + return; + }; + let Some(tex) = t.by_res.get_mut(&res) else { + return; + }; + if tex.owner != Owner::TitlePlaced { + return; + } + tex.update_state(subresource, after); + let uniform = tex.uniform_state(); + let is_writer = tex.is_writer; + let leaving_write = (before & (STATE_UAV | STATE_RENDER_TARGET) != 0) && (after & (STATE_UAV | STATE_RENDER_TARGET) == 0); + if is_writer && leaving_write && ACTIVE_PAIRS.load(Ordering::Relaxed) != 0 && t.pairs.iter().any(|p| p.writer == res) { + if let Some(st) = uniform { + writers_to_sync.push((res, st)); + } + } +} + +/// Copy all subresources of `src` into `dst` through an intermediate buffer (`CopyTextureRegion`), +/// preserving raw texel bits across incompatible DXGI format families (e.g. `R32_UINT` -> +/// `R9G9B9E5_SHAREDEXP` or `BCn` <-> `R32G32B32A32_UINT`). +/// Callers must ensure `src` is in `COPY_SOURCE` and `dst` is in `COPY_DEST`. +pub(super) unsafe fn copy_all_subresources_through_buffer( + list: *mut c_void, + dev: &ID3D12Device, + dst: &ID3D12Resource, + src: &ID3D12Resource, +) -> bool { + let dst_desc = dst.GetDesc(); + let src_desc = src.GetDesc(); + let dst_shape = TexShape::from_pc_desc(&dst_desc); + let src_shape = TexShape::from_pc_desc(&src_desc); + if !can_copy_through_buffer(&dst_shape, &src_shape) { + return false; + } + let count = dst_shape.subresource_count().min(src_shape.subresource_count()); + for sub in 0..count { + if !copy_one_subresource_through_buffer(list, dev, dst, &dst_desc, sub, src, &src_desc, sub) { + return false; + } + } + true +} + +struct OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION); + +impl Drop for OwnedCopyLoc { + fn drop(&mut self) { + unsafe { ManuallyDrop::drop(&mut self.0.pResource) }; + } +} + +/// Verify two single-subresource footprints have identical element byte widths and compatible +/// block/texel dimensions (preventing accidental aliasing of incompatible formats that merely +/// share a 256-byte-aligned `RowPitch`). +fn subresource_footprints_compatible(dst_fmt: u32, dst_fp: &D3D12_SUBRESOURCE_FOOTPRINT, src_fmt: u32, src_fp: &D3D12_SUBRESOURCE_FOOTPRINT) -> bool { + let (Some((db, dbc)), Some((sb, sbc))) = (format_element_bytes(dst_fmt), format_element_bytes(src_fmt)) else { + return false; + }; + if db != sb || dst_fp.Depth != src_fp.Depth { + return false; + } + let eff = |bc: bool, w: u32, h: u32| -> (u32, u32) { + if bc { (w.div_ceil(4), h.div_ceil(4)) } else { (w, h) } + }; + eff(dbc, dst_fp.Width, dst_fp.Height) == eff(sbc, src_fp.Width, src_fp.Height) +} + +unsafe fn copy_one_subresource_through_buffer( + list: *mut c_void, + dev: &ID3D12Device, + dst: &ID3D12Resource, + dst_desc: &D3D12_RESOURCE_DESC, + dst_sub: u32, + src: &ID3D12Resource, + src_desc: &D3D12_RESOURCE_DESC, + src_sub: u32, +) -> bool { + let mut src_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut dst_fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut src_rows = 0u32; + let mut dst_rows = 0u32; + let mut src_total = 0u64; + let mut dst_total = 0u64; + dev.GetCopyableFootprints(src_desc, src_sub, 1, 0, Some(&mut src_fp), Some(&mut src_rows), None, Some(&mut src_total)); + dev.GetCopyableFootprints(dst_desc, dst_sub, 1, 0, Some(&mut dst_fp), Some(&mut dst_rows), None, Some(&mut dst_total)); + if src_total == 0 + || src_total == u64::MAX + || dst_total == 0 + || dst_total == u64::MAX + || src_rows != dst_rows + || !subresource_footprints_compatible(dst_desc.Format.0 as u32, &dst_fp.Footprint, src_desc.Format.0 as u32, &src_fp.Footprint) + { + return false; + } + let row_pitch = src_fp.Footprint.RowPitch.max(dst_fp.Footprint.RowPitch); + src_fp.Footprint.RowPitch = row_pitch; + dst_fp.Footprint.RowPitch = row_pitch; + let slices = (src_fp.Footprint.Depth as u64).max(1); + let needed = (row_pitch as u64).saturating_mul(src_rows as u64).saturating_mul(slices).max(src_total).max(dst_total); + let Some(scratch_raw) = list_x::acquire_scratch_for_copy(list, needed) else { + return false; + }; + let scratch_ptr = scratch_raw as *mut c_void; + let Some(scratch) = ID3D12Resource::from_raw_borrowed(&scratch_ptr) else { + return false; + }; + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + { + let src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(src.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: src_sub }, + }); + let buf_dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(scratch.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: src_fp }, + }); + list_x::pc_copy_texture_region(list, &buf_dst_loc.0, 0, 0, 0, &src_loc.0, std::ptr::null()); + } + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + { + let buf_src_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(scratch.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: dst_fp }, + }); + let dst_loc = OwnedCopyLoc(D3D12_TEXTURE_COPY_LOCATION { + pResource: ManuallyDrop::new(Some(dst.clone())), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: dst_sub }, + }); + list_x::pc_copy_texture_region(list, &dst_loc.0, 0, 0, 0, &buf_src_loc.0, std::ptr::null()); + } + + list_x::transition(list, scratch_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + true +} + +unsafe fn sync_pair(list: *mut c_void, dev: &ID3D12Device, ty: D3D12_COMMAND_LIST_TYPE, pair: AliasPair, writer_state: u32) { + let w_ptr = pair.writer as *mut c_void; + let r_ptr = pair.reader as *mut c_void; + let (Some(writer_res), Some(reader_res)) = (ID3D12Resource::from_raw_borrowed(&w_ptr), ID3D12Resource::from_raw_borrowed(&r_ptr)) else { + return; + }; + let target_srv = if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { STATE_SRV_ALL } else { STATE_SRV_NON_PIXEL }; + + // Determine reader's incoming state on this list. + let (reader_before, reader_after) = match pair.reader_owner { + Owner::PlacedSrv => { + let cur = LIST_STATES + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .and_then(|s| s.srv_states.get(&pair.reader).copied()) + .unwrap_or(STATE_COMMON); + (cur, target_srv) + } + Owner::TitlePlaced => { + let Some(st) = TABLE + .lock() + .unwrap() + .as_ref() + .and_then(|t| t.by_res.get(&pair.reader)) + .and_then(TrackedTex::uniform_state) + else { + return; + }; + // On a compute list, never emit transitions referencing DIRECT-only states + // (`RENDER_TARGET`, `INDEX_BUFFER`, `VERTEX_AND_CONSTANT_BUFFER`, `DEPTH_*`, `PIXEL_SHADER_RESOURCE`). + if !state_valid_on_list(ty, st) { + return; + } + (st, st) + } + Owner::PlacedUav => return, + }; + + if writer_state != D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32 { + list_x::transition(list, pair.writer, D3D12_RESOURCE_STATES(writer_state as i32), D3D12_RESOURCE_STATE_COPY_SOURCE); + } + if reader_before != D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 { + list_x::transition(list, pair.reader, D3D12_RESOURCE_STATES(reader_before as i32), D3D12_RESOURCE_STATE_COPY_DEST); + } + + let ok = if pair.buffer_through { + copy_all_subresources_through_buffer(list, dev, reader_res, writer_res) + } else { + list_x::pc_copy_resource(list, pair.reader, pair.writer); + true + }; + + if writer_state != D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32 { + list_x::transition(list, pair.writer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATES(writer_state as i32)); + } + if reader_after != D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 { + list_x::transition(list, pair.reader, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATES(reader_after as i32)); + } + + if pair.reader_owner == Owner::PlacedSrv { + let mut g = LIST_STATES.lock().unwrap(); + let ls = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + ls.list_type = Some(ty); + ls.srv_states.insert(pair.reader, reader_after); + } + + if ok { + static SYNCED: AtomicU64 = AtomicU64::new(0); + let n = SYNCED.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: synced format-aliased texture {:#x} -> {:#x} ({}, {} syncs so far)", + pair.writer, + pair.reader, + if pair.buffer_through { "buffer-through" } else { "direct copy" }, + n + 1 + ); + } + } +} + +/// Sync active placed-UAV -> format-aliased SRV pairs after a UAV barrier on `list`. +/// When `specific_targets` is `Some(targets)`, only sync pairs whose `writer` is in `targets`; +/// when `None` (global UAV barrier), deduplicate against `bind::activity()`. +pub(super) unsafe fn on_uav_barrier(list: *mut c_void, specific_targets: Option<&[usize]>) { + if ACTIVE_PLACED_UAV_PAIRS.load(Ordering::Relaxed) == 0 || list.is_null() { + return; + } + let Some(ty) = list_x::tracked_list_type(list) else { + return; + }; + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return; + } + // Skip duplicate back-to-back global UAV barriers when no draw or dispatch executed in between. + if specific_targets.is_none() { + let act = super::bind::activity(); + let mut g = LIST_STATES.lock().unwrap(); + let ls = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + if ls.last_activity == act && act != (0, 0) { + return; + } + ls.last_activity = act; + ls.list_type = Some(ty); + } + let Some(dev) = list_x::device_of_list(list) else { + return; + }; + let dev_raw = dev.as_raw() as usize; + let pairs: Vec = { + let g = TABLE.lock().unwrap(); + match g.as_ref() { + Some(t) => t + .pairs + .iter() + .copied() + .filter(|p| { + p.writer_owner == Owner::PlacedUav + && p.device == dev_raw + && specific_targets.is_none_or(|targets| targets.contains(&p.writer)) + }) + .collect(), + None => return, + } + }; + for pair in pairs { + sync_pair(list, &dev, ty, pair, STATE_UAV); + } +} + +/// Sync format-aliased readers for title-owned writers that just transitioned out of write state. +pub(super) unsafe fn sync_title_writers(list: *mut c_void, writers: &[(usize, u32)]) { + if writers.is_empty() || ACTIVE_PAIRS.load(Ordering::Relaxed) == 0 || list.is_null() { + return; + } + let Some(ty) = list_x::tracked_list_type(list) else { + return; + }; + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return; + } + let Some(dev) = list_x::device_of_list(list) else { + return; + }; + let dev_raw = dev.as_raw() as usize; + let mut seen = HashSet::new(); + for &(writer, state) in writers { + if !seen.insert(writer) { + continue; + } + let pairs: Vec = { + let g = TABLE.lock().unwrap(); + match g.as_ref() { + Some(t) => t.pairs.iter().copied().filter(|p| p.writer == writer && p.device == dev_raw).collect(), + None => continue, + } + }; + for pair in pairs { + sync_pair(list, &dev, ty, pair, state); + } + } +} + +/// Return any `PlacedSrv` resources transitioned into read state on `list` back to `COMMON` +/// before `Close()`, keeping cross-queue state invariants clean. +pub(super) unsafe fn before_close(list: *mut c_void) { + if list.is_null() { + return; + } + let pending: Vec<(usize, u32)> = { + let mut g = LIST_STATES.lock().unwrap(); + match g.as_mut().and_then(|m| m.get_mut(&(list as usize))) { + Some(ls) if !ls.srv_states.is_empty() => ls.srv_states.drain().collect(), + _ => return, + } + }; + for (res, state) in pending { + if state != STATE_COMMON { + list_x::transition(list, res, D3D12_RESOURCE_STATES(state as i32), D3D12_RESOURCE_STATE_COMMON); + } + } +} + +/// Clear per-list sync state on `Reset` / `Create` / `Release`. +pub(super) fn list_reset(list: usize) { + if let Some(m) = LIST_STATES.lock().unwrap().as_mut() { + m.remove(&list); + } +} + +/// Intercept `CopyResource(dst, src)` between incompatible DXGI format families of equal texel +/// width (e.g. `R32_UINT` <-> `R9G9B9E5_SHAREDEXP`) and run it through an intermediate buffer. +/// Returns `true` if handled. +pub(super) unsafe fn try_copy_resource(list: *mut c_void, dst: usize, src: usize) -> bool { + if !enabled() || dst == 0 || src == 0 || dst == src { + return false; + } + let (dp, sp) = (dst as *mut c_void, src as *mut c_void); + let (Some(d), Some(s)) = (ID3D12Resource::from_raw_borrowed(&dp), ID3D12Resource::from_raw_borrowed(&sp)) else { + return false; + }; + let (dd, sd) = (d.GetDesc(), s.GetDesc()); + if dd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || sd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return false; + } + if !needs_buffer_through(dd.Format.0 as u32, sd.Format.0 as u32) { + return false; + } + let Some(dev) = list_x::device_of_list(list) else { + return false; + }; + let ok = copy_all_subresources_through_buffer(list, &dev, d, s); + if ok { + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed); + if k < 8 || k.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: format-aliased CopyResource fmt {} -> fmt {} ({}x{}) copied via intermediate buffer ({} so far)", + sd.Format.0, + dd.Format.0, + dd.Width, + dd.Height, + k + 1 + ); + } + } + ok +} + +/// Intercept full-subresource texture-to-texture `CopyTextureRegion` between incompatible DXGI +/// format families of equal texel width and run it through an intermediate buffer. +/// Returns `true` if handled. +pub(super) unsafe fn try_copy_texture_region( + list: *mut c_void, + dst: &D3D12_TEXTURE_COPY_LOCATION, + x: u32, + y: u32, + z: u32, + src: &D3D12_TEXTURE_COPY_LOCATION, + bx: *const D3D12_BOX, +) -> bool { + if !enabled() + || dst.Type != D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX + || src.Type != D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX + || x != 0 + || y != 0 + || z != 0 + || !bx.is_null() + { + return false; + } + let (Some(d), Some(s)) = (dst.pResource.as_ref(), src.pResource.as_ref()) else { + return false; + }; + let (dd, sd) = (d.GetDesc(), s.GetDesc()); + if dd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER || sd.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER { + return false; + } + if !needs_buffer_through(dd.Format.0 as u32, sd.Format.0 as u32) { + return false; + } + let Some(dev) = list_x::device_of_list(list) else { + return false; + }; + copy_one_subresource_through_buffer( + list, + &dev, + d, + &dd, + dst.Anonymous.SubresourceIndex, + s, + &sd, + src.Anonymous.SubresourceIndex, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn shape(fmt: u32, w: u64, h: u32, d: u16, mips: u16) -> TexShape { + TexShape { + dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, + width: w, + height: h, + depth_or_array: d, + mip_levels: mips, + format: fmt, + samples: 1, + } + } + + #[test] + fn r32_uint_and_r9g9b9e5_alias_needs_buffer_through() { + assert!(needs_buffer_through(67, 42)); // R9G9B9E5_SHAREDEXP vs R32_UINT + assert!(needs_buffer_through(67, 39)); // R9G9B9E5_SHAREDEXP vs R32_TYPELESS + assert!(!needs_buffer_through(42, 39)); // R32_UINT vs R32_TYPELESS (same family) + assert!(!needs_buffer_through(28, 27)); // R8G8B8A8_UNORM vs R8G8B8A8_TYPELESS + + let s_uav = shape(39, 128, 128, 6, 4); + let s_srv = shape(67, 128, 128, 6, 4); + assert!(can_copy_through_buffer(&s_srv, &s_uav)); + + // 3D volumetric fog froxel texture: R32_UINT UAV -> R9G9B9E5_SHAREDEXP SRV + let fog_uav = TexShape { dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D.0, ..shape(42, 160, 90, 64, 1) }; + let fog_srv = TexShape { dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D.0, ..shape(67, 160, 90, 64, 1) }; + assert!(can_copy_through_buffer(&fog_srv, &fog_uav)); + assert_eq!(fog_srv.subresource_count(), 1); + + // BC7 (16 B per 4x4 block) <-> R32G32B32A32_UINT (16 B per texel, 1/4 width & height) + let bc7 = shape(98, 256, 128, 1, 1); + let u32x4 = shape(3, 64, 32, 1, 1); + assert!(can_copy_through_buffer(&bc7, &u32x4)); + assert!(can_copy_through_buffer(&u32x4, &bc7)); + + // Mismatched dimensions or bpp rejected + assert!(!can_copy_through_buffer(&shape(67, 64, 64, 1, 1), &shape(42, 128, 128, 1, 1))); + assert!(!can_copy_through_buffer(&shape(10, 128, 128, 1, 1), &shape(42, 128, 128, 1, 1))); + } + + #[test] + fn placed_uav_and_srv_descs_are_sanitized() { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + x[0x20..0x24].copy_from_slice(&67u32.to_le_bytes()); // R9G9B9E5_SHAREDEXP + x[0x30..0x34].copy_from_slice(&0x30_0005u32.to_le_bytes()); // RTV | UAV + console bits + + // Placed UAV with R32_UINT view over R9G9B9E5 desc -> R32_TYPELESS + ALLOW_UNORDERED_ACCESS (no RTV) + let uav = prepare_placed_uav_desc(&x, 42); + let uav_fmt = u32::from_le_bytes(uav[0x20..0x24].try_into().unwrap()); + let uav_flags = u32::from_le_bytes(uav[0x30..0x34].try_into().unwrap()); + assert_eq!(uav_fmt, 39, "R32_UINT UAV over R9G9B9E5 must become R32_TYPELESS, not R11G11B10_FLOAT"); + assert!(uav_flags & FLAG_UAV != 0 && uav_flags & FLAG_RENDER_TARGET == 0); + + // Placed SRV with R9G9B9E5 view -> strips RTV|UAV so pc_resource_desc keeps format 67! + let srv = prepare_placed_srv_desc(&x, 67); + let srv_pc = super::super::device_x::pc_resource_desc(&srv); + let srv_fmt = u32::from_le_bytes(srv_pc[0x20..0x24].try_into().unwrap()); + let srv_flags = u32::from_le_bytes(srv_pc[0x30..0x34].try_into().unwrap()); + assert_eq!(srv_fmt, 67, "placed SRV must stay R9G9B9E5_SHAREDEXP"); + assert_eq!(srv_flags & (FLAG_RENDER_TARGET | FLAG_UAV), 0); + } + + #[test] + fn alias_table_links_in_both_creation_orders() { + let mut t = AliasTable::new(); + let va = 0x2_0000_0000usize; + let uav_shape = shape(39, 64, 64, 1, 1); + let srv_shape = shape(67, 64, 64, 1, 1); + + // Order 1: SRV created first, placed UAV created second -> links and marks SRV gpu_written + let m1 = t.insert(0x100, TrackedTex::new(1, va, srv_shape, Owner::TitlePlaced, 0, false)); + assert!(m1.is_empty()); + assert!(t.pairs.is_empty()); + + let m2 = t.insert(0x200, TrackedTex::new(1, va, uav_shape, Owner::PlacedUav, STATE_UAV, true)); + assert_eq!(m2, vec![0x100]); + assert_eq!(t.pairs.len(), 1); + assert!(t.pairs[0].buffer_through); + assert_eq!(t.placed_uav_pairs, 1); + + // Order 2: second SRV created after UAV -> links immediately and marks itself gpu_written + let m3 = t.insert(0x300, TrackedTex::new(1, va, srv_shape, Owner::PlacedSrv, 0, false)); + assert_eq!(m3, vec![0x300]); + assert_eq!(t.pairs.len(), 2); + + // Removing the reader cleans up its pair + t.remove(0x100); + assert_eq!(t.pairs.len(), 1); + assert_eq!(t.pairs[0].reader, 0x300); + + // Removing the writer cleans up remaining pairs + t.remove(0x200); + assert!(t.pairs.is_empty()); + assert_eq!(t.placed_uav_pairs, 0); + + // Compute-list state validation rejects RENDER_TARGET (0x4), INDEX_BUFFER (0x2), VCB (0x1), + // DEPTH_WRITE (0x10), PIXEL_SHADER_RESOURCE (0x80), while allowing COMMON/UAV/NON_PIXEL_SRV/COPY. + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_COMMON)); + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_UAV)); + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_SRV_NON_PIXEL)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_RENDER_TARGET)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, 0x1)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, 0x2)); + assert!(!state_valid_on_list(D3D12_COMMAND_LIST_TYPE_COMPUTE, STATE_SRV_ALL)); + assert!(state_valid_on_list(D3D12_COMMAND_LIST_TYPE_DIRECT, STATE_RENDER_TARGET)); + + // Subresource footprint compatibility rejects mismatched element byte widths even with equal RowPitch + let fp = |w, h, d| D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(0), + Width: w, + Height: h, + Depth: d, + RowPitch: 256, + }; + assert!(subresource_footprints_compatible(67, &fp(32, 32, 1), 42, &fp(32, 32, 1))); + assert!(!subresource_footprints_compatible(10, &fp(32, 32, 1), 42, &fp(32, 32, 1)), "8 Bpp vs 4 Bpp must be rejected"); + assert!(subresource_footprints_compatible(98, &fp(64, 64, 1), 3, &fp(16, 16, 1)), "BC7 64x64 == R32G32B32A32 16x16"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..07e8abb939 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -143,8 +143,13 @@ pub unsafe fn drain_known(seal_now: bool) { }; // (outside the lock: a release may end other objects, whose releases come back here) for res in gone { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(res as *mut c_void, 2)); - f(res as *mut c_void); + let ptr = res as *mut c_void; + let f: unsafe extern "system" fn(*mut c_void) -> u32 = if super::real::is_adopted(ptr) { + std::mem::transmute(super::real::orig_fn(ptr, 2)) + } else { + std::mem::transmute(*(*(ptr as *const *const usize)).add(2)) + }; + f(ptr); } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 7342be7b1e..283a695bd4 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -124,6 +124,84 @@ pub(super) unsafe fn transition(list: *mut c_void, res: usize, before: D3D12_RES pc::(list, PC_RESOURCE_BARRIER)(list, 1, &b); } +pub(super) unsafe fn pc_resource_barriers(list: *mut c_void, barriers: &[D3D12_RESOURCE_BARRIER]) { + if !barriers.is_empty() { + pc::(list, PC_RESOURCE_BARRIER)(list, barriers.len() as u32, barriers.as_ptr()); + } +} + +pub(super) unsafe fn pc_copy_resource(list: *mut c_void, dst: usize, src: usize) { + pc::(list, PC_COPY_RESOURCE)(list, dst, src); +} + +pub(super) unsafe fn pc_copy_texture_region( + list: *mut c_void, + dst: *const D3D12_TEXTURE_COPY_LOCATION, + x: u32, + y: u32, + z: u32, + src: *const D3D12_TEXTURE_COPY_LOCATION, + bx: *const D3D12_BOX, +) { + pc::(list, PC_COPY_TEXTURE_REGION)( + list, dst, x, y, z, src, bx, + ); +} + +pub(super) unsafe fn device_of_list(list: *mut c_void) -> Option { + device_of(list) +} + +/// Restore title bindings, PC root signatures, bound PSO, and dynamic/fallback depth-bias state +/// after an internal graphics/compute sync pass on `list`. +pub(super) unsafe fn restore_after_internal_pass(list: *mut c_void, clobbered_gfx: bool, clobbered_cs: bool) { + let (bindings, bound_pso, ty, depth_bias, native_bias, had_fallback) = { + let mut g = LISTS.lock().unwrap(); + match g.as_mut().and_then(|m| m.get_mut(&(list as usize))) { + Some(s) => { + let had_fallback = s.using_fallback_pso; + if had_fallback { + s.using_fallback_pso = false; + s.pso_dirty = true; + } + ( + s.bindings.clone(), + s.bound_pso, + s.list_type.unwrap_or(D3D12_COMMAND_LIST_TYPE_DIRECT), + s.depth_bias, + s.native_bias, + had_fallback, + ) + } + None => return, + } + }; + restore_bindings(list, &bindings, ty); + let (rs_gfx, rs_cs) = super::bind::tracked_root_sigs(list); + if clobbered_gfx && rs_gfx != 0 { + pc::(list, 30)(list, rs_gfx); + } + if clobbered_cs && rs_cs != 0 { + pc::(list, 29)(list, rs_cs); + } + if bound_pso != 0 { + let resolved = super::pso_async::resolve_for_bind(bound_pso); + pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); + if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE { + if let Some((true, static_bias)) = device_x::base_depth_bias_info(bound_pso) { + let target = depth_bias.unwrap_or(static_bias); + if target != DepthBias::ZERO || native_bias != DepthBias::ZERO { + let _ = try_native_depth_bias(list, target); + } + } else if depth_bias.is_some() && !had_fallback { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.pso_dirty = true; + } + } + } + } +} + /// `op` with the window buffer `res` as a copy destination (back to COMMON after it) unsafe fn as_copy_dest(list: *mut c_void, res: usize, op: impl FnOnce()) { transition(list, res, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); @@ -820,6 +898,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C }; drop(old); super::title_textures::list_reset(key); + super::format_alias::list_reset(key); // Dynamic-depth-bias PSOs ignore baked RasterizerState depth bias; seed the list with the // initial PSO's static bias if non-zero (CreateCommandList resets RSSetDepthBias to 0). if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE && pso != 0 { @@ -838,6 +917,7 @@ pub(super) fn on_release(list: usize) { super::alloc_pool::forget_list(list); release_copy_scratch(list); super::title_textures::list_reset(list); + super::format_alias::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { if !old.pending_waits.is_empty() { @@ -2153,12 +2233,17 @@ const MAX_COPY_SCRATCH: u64 = 64 << 20; struct CopyScratch { buffer: ID3D12Resource, bytes: u64, + extra: Vec<(ID3D12Resource, u64)>, recorded: bool, untracked_submission: bool, marks: HashMap, } impl CopyScratch { + fn total_bytes(&self) -> u64 { + self.bytes + self.extra.iter().map(|(_, b)| *b).sum::() + } + fn idle(&mut self) -> bool { self.marks.retain(|_, (fence, value)| unsafe { fence.GetCompletedValue() < *value }); !self.untracked_submission && self.marks.is_empty() @@ -2180,7 +2265,7 @@ impl CopyScratchCache { if !scratch.idle() { return true; } - self.bytes -= scratch.bytes; + self.bytes -= scratch.total_bytes(); false }); } @@ -2200,12 +2285,12 @@ impl CopyScratchCache { if !scratch.recorded && !scratch.idle() { return None; } - if scratch.recorded || scratch.bytes >= bytes || bytes > MAX_COPY_SCRATCH - self.bytes + scratch.bytes { + if scratch.recorded || scratch.bytes >= bytes || bytes > MAX_COPY_SCRATCH - self.bytes + scratch.total_bytes() { scratch.recorded = true; return Some((scratch.buffer.as_raw() as usize, scratch.bytes)); } // Drop the old allocation before growing so the peak stays within the budget. - self.bytes -= self.active.remove(&key).unwrap().bytes; + self.bytes -= self.active.remove(&key).unwrap().total_bytes(); } if bytes > MAX_COPY_SCRATCH - self.bytes { return None; @@ -2213,11 +2298,33 @@ impl CopyScratchCache { let buffer = make_copy_scratch(list, bytes)?; let raw = buffer.as_raw() as usize; self.active.insert(key, CopyScratch { - buffer, bytes, recorded: true, untracked_submission: false, marks: HashMap::new(), + buffer, bytes, extra: Vec::new(), recorded: true, untracked_submission: false, marks: HashMap::new(), }); self.bytes += bytes; Some((raw, bytes)) } + + /// Acquire a scratch buffer on `list` guaranteed to hold at least `bytes` bytes (allocating + /// an extra GPU-fenced buffer on `list` if an earlier smaller scratch was already recorded). + unsafe fn acquire_exact(&mut self, list: *mut c_void, bytes: u64) -> Option { + let (raw, cap) = self.acquire(list, bytes)?; + if cap >= bytes { + return Some(raw); + } + let key = list as usize; + let scratch = self.active.get_mut(&key)?; + if let Some((buf, _)) = scratch.extra.iter().find(|(_, b)| *b >= bytes) { + return Some(buf.as_raw() as usize); + } + if bytes > MAX_COPY_SCRATCH.saturating_sub(self.bytes) { + return None; + } + let buffer = make_copy_scratch(list, bytes)?; + let raw = buffer.as_raw() as usize; + scratch.extra.push((buffer, bytes)); + self.bytes += bytes; + Some(raw) + } } static COPY_SCRATCH: LazyLock> = LazyLock::new(|| Mutex::new(CopyScratchCache::default())); @@ -2251,6 +2358,18 @@ unsafe fn copy_scratch(list: *mut c_void, n: u64) -> Option<(usize, u64)> { COPY_SCRATCH.lock().unwrap().acquire(list, bytes) } +/// Acquire a per-list DEFAULT-heap scratch buffer in `COMMON` state large enough to hold `n` bytes. +pub(super) unsafe fn acquire_scratch_for_copy(list: *mut c_void, n: u64) -> Option { + if n == 0 || n > MAX_COPY_SCRATCH || list_type(list) == D3D12_COMMAND_LIST_TYPE_BUNDLE { + return None; + } + let bytes = n.next_power_of_two().max(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64); + if bytes > MAX_COPY_SCRATCH { + return COPY_SCRATCH.lock().unwrap().acquire_exact(list, n.next_multiple_of(D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64)); + } + COPY_SCRATCH.lock().unwrap().acquire_exact(list, bytes) +} + fn reset_copy_scratch(list: *mut c_void) { if let Some(scratch) = COPY_SCRATCH.lock().unwrap().active.get_mut(&(list as usize)) { scratch.recorded = false; @@ -2880,9 +2999,11 @@ pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u3 super::bind::dispatch(this, x, y, z); } -/// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH -/// build passes): emits a global UAV barrier so UMA writes become visible to the next pass -pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _barriers: *const c_void) { +/// command list #146 console enhanced/UAV barrier (`ID3D12GraphicsCommandList7::Barrier`, also +/// used by `XboxBvhBuilder.dll` between BVH build passes): emits a global PC UAV barrier so UMA +/// writes become visible, parses any readable `D3D12_BARRIER_GROUP` texture barriers targeting +/// tracked depth+UAV resources, and notifies `depth_uav` / `format_alias` of global UAV barriers. +pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, barriers: *const c_void) { let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -2891,6 +3012,18 @@ pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, _n: u32, _ }, }; pc::(this, PC_RESOURCE_BARRIER)(this, 1, &b); + if super::depth_uav::any() { + let is_direct = list_type(this) == D3D12_COMMAND_LIST_TYPE_DIRECT; + let mut depth_syncs = Vec::new(); + let had_global_uav = super::depth_uav::filter_enhanced_barriers(n, barriers, is_direct, &mut depth_syncs); + if !depth_syncs.is_empty() { + super::depth_uav::execute_syncs(this, &depth_syncs); + } + if had_global_uav { + super::depth_uav::on_global_uav_barrier(); + } + } + super::format_alias::on_uav_barrier(this, None); } /// command list #84 CopyResourceX(destination, source, flags); in place (the console's @@ -2947,7 +3080,11 @@ unsafe fn predication_buffer(list: *mut c_void) -> Option { /// Before `Close()` on a command list: return `pred_buf` to `COMMON` if it is currently in /// `D3D12_RESOURCE_STATE_PREDICATION`. pub(super) unsafe fn before_close(list: *mut c_void) { - if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + if list.is_null() { + return; + } + super::format_alias::before_close(list); + if !PREDICATION_USED.load(Ordering::Acquire) { return; } let pb = { @@ -2970,6 +3107,7 @@ pub(super) unsafe fn before_close(list: *mut c_void) { /// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); + super::format_alias::list_reset(list as usize); if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { return; } @@ -3880,6 +4018,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 } reset_copy_scratch(this); + super::format_alias::list_reset(this as usize); let is_bundle = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); @@ -3929,7 +4068,11 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } let mut out: Vec<[u32; 8]> = Vec::with_capacity(n as usize + 1); // a UAV barrier for all resources is in `out` / a transition from or to UNORDERED_ACCESS - let (mut any_uav, mut uav_transition) = (false, false); + let (mut any_uav, mut global_uav_barrier, mut uav_transition) = (false, false, false); + let mut uav_targets: Vec = Vec::new(); + let is_direct = tracked_list_type(this).is_none_or(|t| t == D3D12_COMMAND_LIST_TYPE_DIRECT); + let mut depth_syncs: Vec = Vec::new(); + let mut alias_writers: Vec<(usize, u32)> = Vec::new(); for k in 0..n as usize { let mut b = barriers.add(k).read_unaligned(); let (ty, flags) = (b[0], b[1]); @@ -3959,6 +4102,19 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } } if ty == 2 { + // Route resource-specific UAV barriers on tracked Depth+UAV textures to both their + // materialized depth and stencil color twins before emitting the wildcard UMA UAV barrier. + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + if res != 0 { + uav_targets.push(res); + for twin in super::depth_uav::on_uav_barrier(res) { + if twin != 0 { + out.push([2, 0, twin as u32, (twin as u64 >> 32) as u32, 0, 0, 0, 0]); + } + } + } else { + global_uav_barrier = true; + } // UAV (resource +8): translated shaders reach title memory through XCL's memory // window buffers – other resources over the same memory – which a UAV barrier for // the title's resource alone does not order (AMD drivers wait and flush for any UAV @@ -3977,18 +4133,30 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 } b[5] &= PC_STATES; b[6] &= PC_STATES; + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; // VERTEX_AND_CONSTANT_BUFFER / INDEX_BUFFER are buffer states on the PC; the console // takes them for textures too (Minecraft moves a texture to a generic-read // combination) – the PC list then fails to close - if (b[5] | b[6]) & BUFFER_ONLY_STATES != 0 && !is_buffer((b[2] as u64 | (b[3] as u64) << 32) as usize) { + if (b[5] | b[6]) & BUFFER_ONLY_STATES != 0 && !is_buffer(res) { b[5] &= !BUFFER_ONLY_STATES; b[6] &= !BUFFER_ONLY_STATES; } if b[5] == b[6] { continue; } + // Depth+UAV textures: rewrite invalid UNORDERED_ACCESS transitions on depth resources + // and lazily synchronize their writable color twins. + let (pass, need_uav) = super::depth_uav::filter_transition(&b, is_direct, &mut depth_syncs); + uav_transition |= need_uav; + if !pass { + continue; + } + super::format_alias::note_title_transition(res, b[4], b[5], b[6], flags, &mut alias_writers); // UAV writes before (or after) the transition: the same holds for the window buffers - uav_transition |= (b[5] | b[6]) & UNORDERED_ACCESS != 0; + if (b[5] | b[6]) & UNORDERED_ACCESS != 0 { + uav_transition = true; + uav_targets.push(res); + } } out.push(b); } @@ -4004,6 +4172,19 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 if !out.is_empty() { pc::(this, PC_RESOURCE_BARRIER)(this, out.len() as u32, out.as_ptr()); } + if !depth_syncs.is_empty() { + super::depth_uav::execute_syncs(this, &depth_syncs); + } + if !alias_writers.is_empty() { + super::format_alias::sync_title_writers(this, &alias_writers); + } + if any_uav || uav_transition { + if global_uav_barrier { + super::depth_uav::on_global_uav_barrier(); + } + let targets = if global_uav_barrier || uav_targets.is_empty() { None } else { Some(uav_targets.as_slice()) }; + super::format_alias::on_uav_barrier(this, targets); + } } /// D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER | INDEX_BUFFER: valid for buffers only @@ -4163,7 +4344,9 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds } } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; - pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); + if !super::format_alias::try_copy_texture_region(this, &d, x, y, z, &s, bx) { + pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); + } std::mem::forget((d, s)); // borrowed resource pointers } @@ -4189,6 +4372,7 @@ pub(super) unsafe extern "system" fn clear_depth_stencil_x(this: *mut c_void, ds ); } } + super::depth_uav::on_clear_dsv(dsv, flags); pc::(this, PC_CLEAR_DEPTH_STENCIL_VIEW)(this, dsv, flags, depth, stencil, n, rects) } @@ -4248,6 +4432,9 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi } let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { + if super::format_alias::try_copy_resource(this, dst, src) { + return; + } return pc::(this, PC_COPY_RESOURCE)(this, dst, src); } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f0357981..912e05d870 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -13,10 +13,12 @@ mod alloc_pool; pub mod bind; pub mod console_heap; pub mod console_list; +mod depth_uav; pub mod device_x; pub mod dxgi_device; mod cpu_writes; mod fence_x; +mod format_alias; pub mod frame; pub mod guard; mod late_release; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 51016f38ad..49be22f887 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1690,6 +1690,8 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::sparse::forget_buffer(this as usize); super::vram::forget(this as usize); super::title_textures::forget(this as usize); + super::depth_uav::forget(this as usize); + super::format_alias::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { if u.is_sparse(p) { @@ -2132,7 +2134,9 @@ unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, if copy.is_none() { copy = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| default_dsv(&r.GetDesc())); } - f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu) + let dsv_flags = copy.as_ref().map_or(0, |c| c.Flags.0 as u32); + f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu); + super::depth_uav::note_dsv(cpu as usize, res as usize, dsv_flags); } /// The view a DSV without a description has, for a depth buffer `pc_resource_desc` made @@ -2331,33 +2335,6 @@ fn cube_as_cube_array(v: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> Option *mut c_void { - type Key = (u64, [u8; 0x38]); - static MADE: Mutex>> = Mutex::new(None); - if desc.is_null() || va == 0 || !crate::gpu::shader::readable(desc as usize, 0x38) { - return std::ptr::null_mut(); - } - // the PC part of the desc; the flags (@0x30) are its last dword, padding follows - let mut x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); - x[0x34..].fill(0); - if let Some(&r) = MADE.lock().unwrap().get_or_insert_with(HashMap::new).get(&(va, x)) { - return r as *mut c_void; - } - let mut r = std::ptr::null_mut(); - let hr = super::device_x::create_placed_resource_x(this, va, x.as_ptr(), 0, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const GUID, &mut r); - if hr < 0 || r.is_null() { - static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 8 { - crate::xlog_warn!("D3D12.X: view at {va:#x}: the resource cannot be made ({hr:#x}); desc {x:02x?}"); - } - r = std::ptr::null_mut(); - } - MADE.lock().unwrap().get_or_insert_with(HashMap::new).insert((va, x), r as usize); - r -} - /// device #70 (a retail game): a shader resource view of memory, without a resource object: /// (resource desc, { the PC's SRV desc; GPU address @0x28; … }, destination). unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u8, view: *const u8, cpu: u64) { @@ -2373,7 +2350,7 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); return super::console_heap::write(&slot, &words); } - dev_create_srv_x(this, resource_at(this, rdesc, va), &v, cpu); + dev_create_srv_x(this, super::format_alias::placed_srv_resource(this, rdesc, va, v.Format.0 as u32), &v, cpu); } /// device #71: the same for an unordered access view ({ the PC's UAV desc; GPU address @0x28; @@ -2391,7 +2368,7 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); return super::console_heap::write(&slot, &words); } - dev_create_uav_x(this, resource_at(this, rdesc, va), std::ptr::null_mut(), &v, cpu); + dev_create_uav_x(this, super::format_alias::placed_uav_resource(this, rdesc, va, v.Format.0 as u32), std::ptr::null_mut(), &v, cpu); } /// V# of `n` elements from element `first` of the buffer at `va`. @@ -2595,21 +2572,30 @@ fn uav_companion_srv( } unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { + let orig_desc = desc.as_ref().copied(); + // Route depth+UAV textures (`ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS`) to their + // writable color twin so compute writes land on a real UAV instead of a null view. + let depth_twin = super::depth_uav::resolve_uav(this, res, orig_desc.as_ref()); // the view's format as the PC's for the resource (B5G5R5A1 of a target made R8G8B8A8, // `device_x::pc_resource_desc`: an invalid call, the device removed) - let mut copy = desc.as_ref().copied(); - if let Some(c) = copy.as_mut() { - if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { - let rf = r.GetDesc().Format.0 as u32; - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); - } else { - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_view_format(c.Format.0 as u32) as i32); - if c.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN && view_dim_to_image_type(c.ViewDimension.0).is_some() { - c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT; + let mut copy = orig_desc; + if depth_twin.is_none() { + if let Some(c) = copy.as_mut() { + if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { + let rf = r.GetDesc().Format.0 as u32; + c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_shader_view_format(rf, c.Format.0 as u32) as i32); + } else { + c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_view_format(c.Format.0 as u32) as i32); + if c.Format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN && view_dim_to_image_type(c.ViewDimension.0).is_some() { + c.Format = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT; + } } } } - let desc = copy.as_ref().map_or(desc, |c| c as *const _); + let (uav_res, uav_desc) = match &depth_twin { + Some((twin_res, patched)) => (*twin_res, patched as *const D3D12_UNORDERED_ACCESS_VIEW_DESC), + None => (res, copy.as_ref().map_or(desc, |c| c as *const _)), + }; super::present::note_use(res as usize, super::present::USE_UAV); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 19)); let rd_opt = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); @@ -2620,15 +2606,15 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, "frame trace: UAV of render target {res:p} {:?} at {cpu:#x}: console slot {:?}, view {:?}", rd_opt.map(|d| (d.Width, d.Height, d.Format.0)), s.as_ref().map(|s| (s.index, s.pc_uav, s.at)), - desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0)) + uav_desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0)) ); } } - // a resource without ALLOW_UNORDERED_ACCESS (a console depth buffer that also had it: the PC - // refuses the pair, `device_x::pc_resource_desc`): a null view – a UAV of it is an invalid - // call, and the device is removed (0x887A0001) - let no_uav = rd_opt.is_some_and(|d| d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0); - let null_desc = null_uav_desc(desc.as_ref(), rd_opt.as_ref()); + // a resource without ALLOW_UNORDERED_ACCESS (a console depth buffer without a twin or + // another non-UAV resource): a null view – a UAV of it is an invalid call (0x887A0001) + let uav_rd_opt = if uav_res == res { rd_opt } else { ID3D12Resource::from_raw_borrowed(&uav_res).map(|r| r.GetDesc()) }; + let no_uav = uav_rd_opt.is_some_and(|d| d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0); + let null_desc = null_uav_desc(uav_desc.as_ref(), uav_rd_opt.as_ref()); let pc_uav = |at: u64| { if no_uav { static N: AtomicU64 = AtomicU64::new(0); @@ -2637,18 +2623,18 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } f(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_desc, at) } else { - f(this, res, counter, desc, at) + f(this, uav_res, counter, uav_desc, at) } }; let Some(slot) = super::console_heap::slot(cpu) else { return pc_uav(cpu) }; pc_uav(slot.pc_uav); super::console_heap::publish(&slot, true); super::console_heap::note_resource(&slot, res as usize); - let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { + let Some(r) = ID3D12Resource::from_raw_borrowed(&uav_res) else { // A null image UAV was already created and published at `slot.index + 1`. Create a // matching null companion SRV at `slot.index` and write a valid T# referencing // `slot.index` so shaders never fall back to `ResourceDescriptorHeap[0]` / `[1]`. - if let Some(v) = desc.as_ref() { + if let Some(v) = uav_desc.as_ref() { if let Some(ty) = view_dim_to_image_type(v.ViewDimension.0) { if let Some(srv) = uav_companion_srv(None, Some(v), true) { let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); @@ -2661,14 +2647,14 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } return super::console_heap::write(&slot, &[0; 8]); }; - let rd = rd_opt.unwrap(); - if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { + let rd = uav_rd_opt.unwrap(); + if let Some(v) = uav_desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); } // UAV dimensions: 1 buffer, 2 tex1d, 3 tex1d array, 4 tex2d, 5 tex2d array, 8 tex3d - let (format, dim, array, mip) = match desc.as_ref() { + let (format, dim, array, mip) = match uav_desc.as_ref() { Some(v) => { let a = &v.Anonymous; let (array, mip) = match v.ViewDimension.0 { @@ -2689,9 +2675,10 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, }; // RDNA images have no SRV / UAV distinction: console shaders may read any image UAV slot // (`image_load`, `image_sample_*`, `image_get_resinfo` all index `ResourceDescriptorHeap[slot.index]`). + // Use `uav_res` / `uav_desc` so Depth+UAV routed slots pair their SRV against the color twin. let deny_srv = rd.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 != 0; - if let Some(srv) = uav_companion_srv(Some(&rd), desc.as_ref(), deny_srv) { - let srv_res = if deny_srv { std::ptr::null_mut() } else { res }; + if let Some(srv) = uav_companion_srv(Some(&rd), uav_desc.as_ref(), deny_srv) { + let srv_res = if deny_srv { std::ptr::null_mut() } else { uav_res }; let g: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); g(this, srv_res, &srv, slot.pc_srv); super::console_heap::publish(&slot, false); @@ -2793,8 +2780,8 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro // not placed in unified memory (e.g. its coherent window kept for readback heaps): a PC // resource of the PC's description – the console's flag bits (0x1000000, 0x300000 …) and // alignments made the PC refuse Fortnite's 3264x1836 scene targets (E_INVALIDARG, a crash) - let pc_full = (console_desc != 0 && crate::gpu::shader::readable(console_desc, 0x38)) - .then(|| super::device_x::pc_resource_desc_for_device(this, &(console_desc as *const [u8; 0x38]).read_unaligned())); + let console_raw = (console_desc != 0 && crate::gpu::shader::readable(console_desc, 0x38)).then(|| (console_desc as *const [u8; 0x38]).read_unaligned()); + let pc_full = console_raw.as_ref().map(|raw| super::device_x::pc_resource_desc_for_device(this, raw)); let desc = pc_full.as_ref().map_or(desc, |d| d.as_ptr() as usize); let mut clear_buf = [0u8; 24]; let clear = super::device_x::pc_clear(clear as *const c_void, &mut clear_buf) as usize; @@ -2806,6 +2793,11 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro super::device_x::pc_initial_state_for_desc(orig_flags, pc_flags, state as u32) }); let hr = dev_create_committed_resource(this, props, flags, desc, st as usize, clear, riid, ppv); + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + if let Some(ref raw_x) = console_raw { + super::depth_uav::register_if_depth_uav(this, *ppv, raw_x, st, state as u32); + } + } if hr < 0 { let pw = |o: usize| if props == 0 { 0 } else { *((props + o) as *const u32) }; crate::xlog_warn!( @@ -3230,7 +3222,11 @@ pub(super) unsafe extern "system" fn dev_create_placed_resource_x(this: *mut c_v u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u(0x20), u(0x2C), u(0x30) ); } - hr3.unwrap_or(hr2) + let out_hr = hr3.unwrap_or(hr2); + if out_hr >= 0 && is_texture && !ppv.is_null() && !(*ppv).is_null() { + super::depth_uav::register_if_depth_uav(this, *ppv, &x, st, state as u32); + } + out_hr } /// A texture the title placed in a heap by the console's size (`get_resource_allocation_info_x` @@ -3257,12 +3253,17 @@ unsafe fn own_memory_if_larger_on_the_pc(this: *mut c_void, heap: usize, offset: } let h = pc_heap_desc(heap)?; let st = super::device_x::pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state as u32); + let mut effective_st = st; let mut hr = dev_create_committed_resource(this, &h.Properties as *const _ as usize, 0, d.as_ptr() as usize, st as usize, clear, riid, ppv); if hr < 0 && st != 0 { // as in the past-the-end fallback: a state the PC refuses for this desc (e.g. UAV // without the UAV flag) – COMMON rather than falling back to the overlapping placement + effective_st = 0; hr = dev_create_committed_resource(this, &h.Properties as *const _ as usize, 0, d.as_ptr() as usize, 0, clear, riid, ppv); } + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::depth_uav::register_if_depth_uav(this, *ppv, &x, effective_st, state as u32); + } static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 8 { let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); @@ -6684,6 +6685,9 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co } unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { + if !dsv.is_null() { + super::depth_uav::before_bind_dsv(this, *dsv); + } type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "OMSetRenderTargets"))); f(this, n, rtvs, single, dsv); From 6602a7020122f508f72fed942286f488e3bd1bb9 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:41:26 +0530 Subject: [PATCH 004/258] kernelx: catch CPU writes to the views of physical pages, page by page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The upload of title memory to video memory (`d3d12x::sparse`) and the textures kept in step with title memory learn what the CPU wrote from the write watch, and a view of a section (`kernelx::sections`) cannot be write-watched: GetWriteWatch refuses any range that holds one. `kernelx::guards` keeps the views of a physical page read-only. The first write through any of them faults; a vectored handler makes that view writable, notes the page and lets the write go on. `take_dirty` hands over the pages of every view of each page written – a write through one view is a write to all of them – and guards those views again before their bytes are read, so a later write is caught again and an earlier one is in what is read. Kernel calls do not fault into the handler, they fail: `lazy::ensure`, which XCL already calls before a kernel call or its own code writes title memory, opens the guards there first and counts the write. A view committed by the lazy handler is writable and counts as written. Both take no lock until a view has been watched. Nothing watches a view yet. --- crates/xcl/src/hle/kernelx.rs | 2 + crates/xcl/src/hle/kernelx/guards.rs | 352 +++++++++++++++++++++++++++ crates/xcl/src/hle/kernelx/lazy.rs | 9 +- 3 files changed, 362 insertions(+), 1 deletion(-) create mode 100644 crates/xcl/src/hle/kernelx/guards.rs diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index c7fb934db9..74cdf34294 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -111,6 +111,8 @@ mod placeholders; pub mod lazy; #[allow(dead_code)] // used once physical pages alias (`XCL_PAGE_ALIAS`) pub mod sections; +#[allow(dead_code)] // `watch` / `take_dirty` used once physical pages alias (`XCL_PAGE_ALIAS`) +pub mod guards; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; const STD_PROTECT_MASK: u32 = 0xFF | 0x100 | 0x200 | 0x400; diff --git a/crates/xcl/src/hle/kernelx/guards.rs b/crates/xcl/src/hle/kernelx/guards.rs new file mode 100644 index 0000000000..6f90b025b0 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/guards.rs @@ -0,0 +1,352 @@ +//! CPU writes to the views of physical pages, caught page by page. +//! +//! The upload of title memory to video memory (`d3d12x::sparse`) learns what the CPU wrote from +//! the write watch, and a view of a section (`sections`) cannot be write-watched. So the views +//! of a physical page are kept read-only: the first write through any of them faults, the +//! handler makes that view writable again and notes the page, and the write goes on. Before the +//! title's next submit `take_dirty` hands over the pages of every view of each page written – +//! a write through one view is a write to all of them – and guards them again. +//! +//! A kernel call does not fault into the handler: it fails. Memory a kernel call or XCL is about +//! to write goes through `lazy::ensure`, which opens the guards there first (`open`). + +use std::collections::{HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Mutex, Once}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_READONLY, PAGE_READWRITE}; + +const PAGE: usize = 0x1_0000; +const EXCEPTION_CONTINUE_EXECUTION: i32 = -1; +const EXCEPTION_CONTINUE_SEARCH: i32 = 0; + +#[derive(Default)] +struct State { + /// view page (64 KiB aligned) → the physical page it shows + at: HashMap, + /// physical page → the view pages that show it + views: HashMap>, + /// physical pages written since the last `take_dirty` + dirty: HashSet, +} + +static STATE: Mutex> = Mutex::new(None); + +/// Whether any view was ever watched: `open` and `committed` sit on the file-read and +/// DirectStorage paths and take no lock before then. +static WATCHING: AtomicBool = AtomicBool::new(false); + +fn with(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +fn install() { + static ONCE: Once = Once::new(); + ONCE.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +unsafe fn protect(view: usize, p: u32) -> bool { + let mut old = 0; + VirtualProtect(view as *const c_void, PAGE, p, &mut old) != 0 +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + // a write (access 1) to a guarded view + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 || r.ExceptionInformation[0] != 1 { + return EXCEPTION_CONTINUE_SEARCH; + } + let view = r.ExceptionInformation[1] & !(PAGE - 1); + // (a view not committed yet cannot be opened: that fault is `lazy`'s, which commits the page + // and counts it as written – claimed here, the write would fault again for ever) + let ours = with(|s| match s.at.get(&view) { + Some(&page) if unsafe { protect(view, PAGE_READWRITE) } => { + s.dirty.insert(page); + true + } + _ => false, + }); + // (another thread may have opened the view between the fault and here: writable now) + if ours || writable(view) { + EXCEPTION_CONTINUE_EXECUTION + } else { + EXCEPTION_CONTINUE_SEARCH + } +} + +/// Whether `view` is a guarded view that is writable now. +fn writable(view: usize) -> bool { + if !with(|s| s.at.contains_key(&view)) { + return false; + } + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + let n = unsafe { VirtualQuery(view as *const c_void, &mut m, std::mem::size_of_val(&m)) }; + n != 0 && m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE +} + +/// Physical page `page` is shown at `view` (64 KiB aligned): writes there are caught from now on. +/// A view not committed yet cannot be guarded; `committed` notes it when it is. +pub fn watch(page: usize, view: usize) { + install(); + WATCHING.store(true, Ordering::Release); + with(|s| { + if let Some(old) = s.at.insert(view, page).filter(|&old| old != page) { + if let Some(v) = s.views.get_mut(&old) { + v.retain(|&a| a != view); + } + } + let v = s.views.entry(page).or_default(); + if !v.contains(&view) { + v.push(view); + } + unsafe { protect(view, PAGE_READONLY) }; + }); +} + +/// `view` no longer shows a physical page (it was unmapped): its writes are not looked for. +pub fn forget(view: usize) { + with(|s| { + if let Some(page) = s.at.remove(&view) { + if let Some(v) = s.views.get_mut(&page) { + v.retain(|&a| a != view); + if v.is_empty() { + s.views.remove(&page); + s.dirty.remove(&page); + } + } + } + }); +} + +/// `view` was committed just now (it reads zeros and is writable): its page counts as written. +pub fn committed(view: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if let Some(&page) = s.at.get(&(view & !(PAGE - 1))) { + s.dirty.insert(page); + } + }); +} + +/// `[p, p + len)` is about to be written by a kernel call or XCL: the views there are made +/// writable and their pages count as written. +pub fn open(p: usize, len: usize) { + if len == 0 || !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if s.at.is_empty() { + return; + } + let mut view = p & !(PAGE - 1); + while view < p.saturating_add(len) { + if let Some(&page) = s.at.get(&view) { + s.dirty.insert(page); + unsafe { protect(view, PAGE_READWRITE) }; + } + view += PAGE; + } + }); +} + +/// The pages written since the last call, as the `step`-sized pages (4 KiB for the write watch) +/// of every view of each, appended to `out`; those views are guarded again. +pub fn take_dirty(out: &mut Vec, step: usize) { + with(|s| { + for page in std::mem::take(&mut s.dirty) { + for &view in s.views.get(&page).map(Vec::as_slice).unwrap_or_default() { + // guarded before its bytes are read for the upload: a write from here on is + // caught again, one before this is in what the upload reads + unsafe { protect(view, PAGE_READONLY) }; + out.extend((view..view + PAGE).step_by(step)); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::super::sections::{commit, reserve, unmap, Section}; + use super::*; + use std::sync::Mutex as TestLock; + + /// the guard state is one per process: tests that use it run one at a time + static SERIAL: TestLock<()> = TestLock::new(()); + + /// A section of `pages` pages and placeholder space for `views` views; page `i` of the + /// section at view slot `j` is `space + j * PAGE`. + struct Fixture { + section: Section, + space: usize, + mapped: Vec, + } + impl Fixture { + fn new(pages: usize, views: usize) -> Fixture { + Fixture { section: Section::new(pages).unwrap(), space: unsafe { reserve(None, views * PAGE) }.unwrap(), mapped: Vec::new() } + } + /// Section page `page` at view slot `slot`, committed and guarded; its physical page id is `page`. + fn show(&mut self, page: usize, slot: usize) -> usize { + let at = self.space + slot * PAGE; + unsafe { + assert!(self.section.map(page, 1, at)); + assert!(commit(at, PAGE)); + } + watch(page, at); + self.mapped.push(at); + at + } + } + impl Drop for Fixture { + fn drop(&mut self) { + for &at in &self.mapped { + forget(at); + unsafe { unmap(at) }; + } + } + } + + fn dirty() -> Vec { + let mut out = Vec::new(); + take_dirty(&mut out, PAGE); + out.sort_unstable(); + out + } + + unsafe fn write(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + #[test] + fn a_write_through_one_view_reports_every_view_of_the_page() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(4, 8); + let a = f.show(2, 1); + let b = f.show(2, 5); + let c = f.show(3, 6); + dirty(); + unsafe { write(b + 16, 9) }; + assert_eq!(unsafe { std::ptr::read_volatile((a + 16) as *const u64) }, 9); + assert_eq!(dirty(), vec![a, b], "both views of the written page, not the other page's"); + assert_eq!(dirty(), Vec::::new(), "nothing written since"); + unsafe { write(a, 1) }; + unsafe { write(c, 1) }; + assert_eq!(dirty(), vec![a, b, c], "the views are guarded again after a take"); + } + + #[test] + fn steps_of_4_kib_cover_the_view() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 1); + let a = f.show(0, 0); + dirty(); + unsafe { write(a + 0x8000, 1) }; + let mut out = Vec::new(); + take_dirty(&mut out, 0x1000); + assert_eq!(out, (a..a + PAGE).step_by(0x1000).collect::>()); + } + + #[test] + fn open_makes_views_writable_for_a_kernel_call_and_counts_the_write() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(2, 4); + let a = f.show(0, 0); + let b = f.show(1, 1); + dirty(); + open(a + PAGE - 8, 16); // straddles both views + assert!(writable(a) && writable(b)); + assert_eq!(dirty(), vec![a, b]); + assert!(!writable(a), "guarded again after the take"); + } + + #[test] + fn a_forgotten_view_is_no_longer_reported() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 2); + let a = f.show(0, 0); + let b = f.show(0, 1); + dirty(); + forget(b); + unsafe { write(a, 3) }; + assert_eq!(dirty(), vec![a]); + } + + #[test] + fn writes_from_many_threads_are_all_caught_and_kept() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + const PAGES: usize = 64; + const THREADS: usize = 8; + let mut f = Fixture::new(PAGES, PAGES); + let views: Vec = (0..PAGES).map(|i| f.show(i, i)).collect(); + dirty(); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(THREADS)); + let handles: Vec<_> = (0..THREADS) + .map(|t| { + let (views, barrier) = (views.clone(), barrier.clone()); + std::thread::spawn(move || { + barrier.wait(); + for (i, &v) in views.iter().enumerate() { + unsafe { write(v + t * 64, (i * THREADS + t) as u64) }; + } + }) + }) + .collect(); + for h in handles { + h.join().unwrap(); + } + for (i, &v) in views.iter().enumerate() { + for t in 0..THREADS { + assert_eq!(unsafe { std::ptr::read_volatile((v + t * 64) as *const u64) }, (i * THREADS + t) as u64); + } + } + assert_eq!(dirty(), views); + } + + #[test] + fn a_write_to_a_view_not_committed_yet_is_left_to_the_next_handler() { + use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, EXCEPTION_RECORD}; + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(2, 2); + // page 0 mapped but never committed; page 1 committed and guarded + let fresh = f.space; + unsafe { assert!(f.section.map(0, 1, fresh)) }; + watch(0, fresh); + f.mapped.push(fresh); + let used = f.show(1, 1); + let fault = |at: usize| unsafe { + let mut rec: EXCEPTION_RECORD = std::mem::zeroed(); + rec.ExceptionCode = EXCEPTION_ACCESS_VIOLATION as NTSTATUS; + rec.NumberParameters = 2; + rec.ExceptionInformation[0] = 1; + rec.ExceptionInformation[1] = at + 8; + let mut ctx: CONTEXT = std::mem::zeroed(); + let mut ptrs = EXCEPTION_POINTERS { ExceptionRecord: &mut rec, ContextRecord: &mut ctx }; + handler(&mut ptrs) + }; + assert_eq!(fault(fresh), EXCEPTION_CONTINUE_SEARCH, "not committed: left to the lazy handler"); + assert_eq!(fault(used), EXCEPTION_CONTINUE_EXECUTION, "committed and guarded: opened here"); + } + + #[test] + fn a_view_committed_later_counts_as_written() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let f = Fixture::new(1, 1); + let at = f.space; + unsafe { assert!(f.section.map(0, 1, at)) }; + watch(0, at); // not committed: cannot be guarded yet + dirty(); + unsafe { assert!(commit(at, PAGE)) }; + committed(at); + assert_eq!(dirty(), vec![at]); + forget(at); + unsafe { unmap(at) }; + } +} diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index fa750b9a48..02a6bf58eb 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -41,7 +41,12 @@ unsafe fn commit(page: usize) -> bool { if !g.remove(&page) { return false; } - !VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() + if VirtualAlloc(page as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null() { + return false; + } + // (a view of a physical page committed here is writable, not guarded: count it as written) + super::guards::committed(page); + true } unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { @@ -88,6 +93,8 @@ pub fn ensure(p: usize, len: usize) { if len == 0 { return; } + // views of physical pages there are read-only until written: a kernel call cannot fault + super::guards::open(p, len); let pages: Vec = { let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); if g.is_empty() { From d660e3070bef6e3ae095393dc134ecd517ab4a35 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:31:10 +0530 Subject: [PATCH 005/258] kernelx: views of physical pages stay open across a write that cannot fault MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A guarded view of a physical page (`kernelx::guards`) is read-only until it is written. Code of XCL's own that writes there faults into the guard and goes on, but a kernel call does not fault: ReadFile into such a view fails. `lazy::ensure` opened the views first, yet the submit thread's `take_dirty` could guard them again before the write – between DirectStorage's check of its destination and the copy, or before the kernel wrote a ReadFile buffer. `guards::open` now returns `Opened`, which keeps its views writable until it is dropped; `take_dirty` uploads a pinned view but does not guard it again, and the end of the write counts as a write. `lazy::ensure` returns it and its callers hold it across their write: the routed ReadFile for a synchronous read, and the destination checks of DirectStorage and the CPU-side bottom-of-pipe writes. An overlapped ReadFile writes after the call returns: its views stay open until its OVERLAPPED is no longer STATUS_PENDING, which `take_dirty` reads without faulting (the title may free it once done). A retail title reads 271 MB that way into the CPU view of its 24 GB reservation 8.5 s after start. `guards::written` counts a page as written through all its views when XCL writes it by page number. Nothing watches a view yet, so nothing changes without views. --- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 3 +- crates/xcl/src/hle/dstorage.rs | 4 +- crates/xcl/src/hle/kernelx/guards.rs | 128 +++++++++++++++++++++--- crates/xcl/src/hle/kernelx/lazy.rs | 16 +-- crates/xcl/src/vfs_hooks.rs | 15 ++- 5 files changed, 142 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 3fedb32253..85bdfcb726 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -127,7 +127,8 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { return true; } - crate::hle::kernelx::lazy::ensure(va, bytes); + // (held while the protection is asked: a view of a physical page is not guarded again meanwhile) + let _open = crate::hle::kernelx::lazy::ensure(va, bytes); use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0; diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 5dd9d2e708..97755841df 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -806,7 +806,9 @@ unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { /// Whether `n` bytes at `p` are committed, writable memory. fn writable(p: usize, n: usize) -> bool { let Some(end) = p.checked_add(n) else { return false }; - crate::hle::kernelx::lazy::ensure(p, n); + // (held while the protection is asked: a view of a physical page is not guarded again + // meanwhile; the copy that follows faults into the guard if one is) + let _open = crate::hle::kernelx::lazy::ensure(p, n); if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, n)) { return true; } diff --git a/crates/xcl/src/hle/kernelx/guards.rs b/crates/xcl/src/hle/kernelx/guards.rs index 6f90b025b0..c91a13e379 100644 --- a/crates/xcl/src/hle/kernelx/guards.rs +++ b/crates/xcl/src/hle/kernelx/guards.rs @@ -31,6 +31,10 @@ struct State { views: HashMap>, /// physical pages written since the last `take_dirty` dirty: HashSet, + /// views opened for a write still going on (`Opened`): not guarded again until it ends + pinned: HashMap, + /// overlapped reads into views: (the OVERLAPPED, its views kept open until it is done) + pending: Vec<(usize, Opened)>, } static STATE: Mutex> = Mutex::new(None); @@ -137,36 +141,114 @@ pub fn committed(view: usize) { }); } +/// Physical page `page` was written other than through a view (XCL by page number, or the page +/// came back from an address outside the views): every view of it counts as written. +pub fn written(page: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + with(|s| { + if s.views.contains_key(&page) { + s.dirty.insert(page); + } + }); +} + +/// Views opened by `open` for a write: they stay writable until this is dropped, when the write +/// is over and their pages count as written again. +#[must_use = "the views stay open only while this lives"] +pub struct Opened(Vec); + +impl Drop for Opened { + fn drop(&mut self) { + if self.0.is_empty() { + return; + } + with(|s| { + for view in self.0.drain(..) { + if let Some(n) = s.pinned.get_mut(&view) { + *n -= 1; + if *n == 0 { + s.pinned.remove(&view); + } + } + if let Some(&page) = s.at.get(&view) { + s.dirty.insert(page); + } + } + }); + } +} + /// `[p, p + len)` is about to be written by a kernel call or XCL: the views there are made -/// writable and their pages count as written. -pub fn open(p: usize, len: usize) { +/// writable, stay so while the returned `Opened` lives (a kernel call fails on a view guarded +/// again under it), and their pages count as written. +pub fn open(p: usize, len: usize) -> Opened { if len == 0 || !WATCHING.load(Ordering::Acquire) { - return; + return Opened(Vec::new()); } with(|s| { + let mut opened = Vec::new(); if s.at.is_empty() { - return; + return Opened(opened); } let mut view = p & !(PAGE - 1); while view < p.saturating_add(len) { if let Some(&page) = s.at.get(&view) { s.dirty.insert(page); unsafe { protect(view, PAGE_READWRITE) }; + *s.pinned.entry(view).or_default() += 1; + opened.push(view); } view += PAGE; } - }); + Opened(opened) + }) +} + +/// An overlapped read (`ov`) writes into the views `opened` holds after its call returned: they +/// stay open until it is done (`take_dirty` looks). +pub fn open_until_done(opened: Opened, ov: usize) { + if !opened.0.is_empty() { + with(|s| s.pending.push((ov, opened))); + } +} + +/// Whether the overlapped I/O at `ov` is still going on (its `Internal` is STATUS_PENDING). The +/// title may have freed the OVERLAPPED once it is done, so it is read without faulting. +fn still_pending(ov: usize) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const STATUS_PENDING: usize = 0x103; + let mut internal = 0usize; + let mut n = 0usize; + // SAFETY: ReadProcessMemory on our own process fails instead of faulting on an unreadable address. + let ok = unsafe { ReadProcessMemory(GetCurrentProcess(), ov as *const c_void, &mut internal as *mut usize as *mut c_void, std::mem::size_of::(), &mut n) } != 0; + ok && n == std::mem::size_of::() && internal == STATUS_PENDING } /// The pages written since the last call, as the `step`-sized pages (4 KiB for the write watch) /// of every view of each, appended to `out`; those views are guarded again. pub fn take_dirty(out: &mut Vec, step: usize) { + if !WATCHING.load(Ordering::Acquire) { + return; + } + // overlapped reads that are done let their views go (dropped outside the lock: it takes it) + let done: Vec<(usize, Opened)> = with(|s| { + let (done, pending) = std::mem::take(&mut s.pending).into_iter().partition(|&(ov, _)| !still_pending(ov)); + s.pending = pending; + done + }); + drop(done); with(|s| { for page in std::mem::take(&mut s.dirty) { for &view in s.views.get(&page).map(Vec::as_slice).unwrap_or_default() { // guarded before its bytes are read for the upload: a write from here on is - // caught again, one before this is in what the upload reads - unsafe { protect(view, PAGE_READONLY) }; + // caught again, one before this is in what the upload reads. A view opened for a + // write still going on stays open (`Opened` counts its page as written at the end) + if !s.pinned.contains_key(&view) { + unsafe { protect(view, PAGE_READONLY) }; + } out.extend((view..view + PAGE).step_by(step)); } } @@ -174,13 +256,13 @@ pub fn take_dirty(out: &mut Vec, step: usize) { } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::super::sections::{commit, reserve, unmap, Section}; use super::*; use std::sync::Mutex as TestLock; - /// the guard state is one per process: tests that use it run one at a time - static SERIAL: TestLock<()> = TestLock::new(()); + /// the guard state is one per process: tests that use it (here and in `alias`) run one at a time + pub(in crate::hle::kernelx) static SERIAL: TestLock<()> = TestLock::new(()); /// A section of `pages` pages and placeholder space for `views` views; page `i` of the /// section at view slot `j` is `space + j * PAGE`. @@ -261,10 +343,29 @@ mod tests { let a = f.show(0, 0); let b = f.show(1, 1); dirty(); - open(a + PAGE - 8, 16); // straddles both views + let opened = open(a + PAGE - 8, 16); // straddles both views assert!(writable(a) && writable(b)); assert_eq!(dirty(), vec![a, b]); - assert!(!writable(a), "guarded again after the take"); + assert!(writable(a) && writable(b), "a take leaves views open while their write goes on"); + drop(opened); + assert_eq!(dirty(), vec![a, b], "the end of the write counts as a write"); + assert!(!writable(a), "guarded again after the take that follows"); + } + + #[test] + fn views_an_overlapped_read_writes_stay_open_until_it_is_done() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut f = Fixture::new(1, 1); + let a = f.show(0, 0); + dirty(); + // an OVERLAPPED whose Internal says pending, then done + let mut ov = [0x103usize, 0, 0, 0]; + open_until_done(open(a, 16), ov.as_mut_ptr() as usize); + assert_eq!(dirty(), vec![a]); + assert!(writable(a), "still open while the read is pending"); + ov[0] = 0; + assert_eq!(dirty(), vec![a], "the end of the read counts as a write"); + assert!(!writable(a), "guarded again once the read is done"); } #[test] @@ -310,6 +411,9 @@ mod tests { assert_eq!(dirty(), views); } + /// A write to a guarded view that is not committed yet is not the guards' to handle (the + /// lazy handler commits it): claimed, it faulted again for ever whenever this handler ran + /// before the lazy one. #[test] fn a_write_to_a_view_not_committed_yet_is_left_to_the_next_handler() { use windows_sys::Win32::System::Diagnostics::Debug::{CONTEXT, EXCEPTION_RECORD}; diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index 02a6bf58eb..e92fa56b2d 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -88,23 +88,25 @@ pub(super) fn unmark(page: usize) -> bool { LAZY.write().unwrap_or_else(|e| e.into_inner()).remove(&page) } -/// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. -pub fn ensure(p: usize, len: usize) { +/// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. Views of +/// physical pages there are read-only until written and a kernel call cannot fault: they are +/// opened, and stay open while the returned value lives (hold it across the write). +pub fn ensure(p: usize, len: usize) -> super::guards::Opened { + let opened = super::guards::open(p, len); if len == 0 { - return; + return opened; } - // views of physical pages there are read-only until written: a kernel call cannot fault - super::guards::open(p, len); let pages: Vec = { let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); if g.is_empty() { - return; + return opened; } g.range(p & !(PAGE - 1)..p.saturating_add(len)).copied().collect() }; for page in pages { unsafe { commit(page) }; } + opened } #[cfg(test)] @@ -124,7 +126,7 @@ mod tests { std::ptr::write_volatile((r + 8) as *mut u32, 7); assert_eq!(std::ptr::read_volatile((r + 8) as *const u32), 7); assert!(!unmark(r), "used: no longer lazy"); - ensure(r + PAGE + 4, 4); + let _open = ensure(r + PAGE + 4, 4); assert!(!LAZY.read().unwrap().contains(&(r + PAGE))); assert!(crate::gpu::shader::readable(r + PAGE, 4)); VirtualFree(r as *mut c_void, 0, MEM_RELEASE); diff --git a/crates/xcl/src/vfs_hooks.rs b/crates/xcl/src/vfs_hooks.rs index 0767cf1e1c..6af3e534d2 100644 --- a/crates/xcl/src/vfs_hooks.rs +++ b/crates/xcl/src/vfs_hooks.rs @@ -531,10 +531,19 @@ unsafe extern "system" fn hk_remove_dir_w(n: *const u16) -> i32 { unsafe extern "system" fn hk_read_file(h: *mut c_void, buf: *mut c_void, n: u32, read: *mut u32, ov: *mut c_void) -> i32 { type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut u32, *mut c_void) -> i32; let orig = orig!(O_READ_FILE as F); - if !buf.is_null() { - crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); + if buf.is_null() { + return orig(h, buf, n, read, ov); + } + // (views of physical pages stay writable until the read is over: a synchronous one when it + // returns, an overlapped one – it writes after this returns – when its OVERLAPPED says done) + let open = crate::hle::kernelx::lazy::ensure(buf as usize, n as usize); + let r = orig(h, buf, n, read, ov); + if ov.is_null() { + drop(open); + } else { + crate::hle::kernelx::guards::open_until_done(open, ov as usize); } - orig(h, buf, n, read, ov) + r } unsafe extern "system" fn hk_delete_file_w(n: *const u16) -> i32 { From dae8b4a5a76c425ba690f5d26661b867ecbc48ff Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 13:02:38 +0100 Subject: [PATCH 006/258] local: two-pass heap addresses --- crates/xcl/src/hle/d3d12x/bind.rs | 40 +++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index b07164f137..5884f45060 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -434,10 +434,12 @@ unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D1 /// The `io` block of a two-pass stage: its user SGPRs (`compute_pass`: the MS layout) with the /// argument table at `table_at`, and the high dword of unified memory's base, as the other binds -/// write it (the translated pair picks each access's memory window from it). -fn two_pass_io(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize) -> Vec { +/// write it (the translated pair picks each access's memory window from it). The compute pass +/// runs the console MS: when its layout says the shaders index the heaps themselves, the heaps' +/// addresses (`State::heaps`) follow the mesh root arguments, as `bind_abi` places them. +fn two_pass_io(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize, heaps: [u32; 2]) -> Vec { let mut io = match layout { - Some(l) if compute_pass => console_list::user_data_ms(l, args, table_at), + Some(l) if compute_pass => console_list::with_heaps(l, None, console_list::user_data_ms(l, args, table_at), heaps), Some(l) => console_list::user_data_gfx(l, args, table_at), None if compute_pass => { let mut v = vec![0u32; 16]; @@ -465,7 +467,7 @@ unsafe fn bind_two_pass_stage( let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; - let (layout, args) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone())); + let (layout, args, heaps) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone(), s.heaps)); let copy = |bytes: &[u8]| -> Result { let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); @@ -476,7 +478,7 @@ unsafe fn bind_two_pass_stage( .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) .min(args.len()); let table_at = copy(&args[inline..])?; - let io = two_pass_io(layout.as_deref(), &args, table_at as u64, compute_pass, u.base()); + let io = two_pass_io(layout.as_deref(), &args, table_at as u64, compute_pass, u.base(), heaps); let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); let rs_raw = if compute_pass { tp.compute_rs } else { tp.mesh_rs } as *mut c_void; @@ -2209,14 +2211,38 @@ void main(uint t : SV_GroupIndex) { use crate::gpu::recomp::{IO_UMA_BASE_HI, KERNEL_SGPRS}; let base = 0x4_0000_0000usize; for compute_pass in [true, false] { - let io = two_pass_io(None, &[], 0x4_1234_5600, compute_pass, base); + let io = two_pass_io(None, &[], 0x4_1234_5600, compute_pass, base, [0; 2]); assert_eq!(io.len(), KERNEL_SGPRS); assert_eq!(io[IO_UMA_BASE_HI], 4, "compute pass {compute_pass}"); } - let io = two_pass_io(None, &[], 0x4_1234_5600, true, base); + let io = two_pass_io(None, &[], 0x4_1234_5600, true, base, [0; 2]); assert_eq!((io[8], io[9]), (0x1234_5600, 4)); } + /// The compute pass of a mesh draw whose shaders index the heaps: the heaps' addresses right + /// after the mesh root arguments (from s16), the view heap's first – the 5-slot mesh layout + /// [table, table, table, root SRV, 2 constants] a retail title's mesh programs are built for + /// reads its view heap from s23. + #[test] + fn two_pass_compute_pass_gets_the_heap_addresses() { + // RTS0 v2: tables (0), an SRV (3), two constants (1); both DIRECTLY_INDEXED flags + let params = [(0u32, 0u32), (0, 0), (0, 0), (3, 0), (1, 2)]; + let mut r = vec![2u32, 5, 24, 0, 0, 0x400 | 0x800]; + r.extend(params.iter().enumerate().flat_map(|(k, &(ty, _))| [ty, 0, 24 + 12 * 5 + 12 * k as u32])); + r.extend(params.iter().flat_map(|&(_, count)| [0, 0, count])); + let l = console_list::layout_from_blob(&r.iter().flat_map(|w| w.to_le_bytes()).collect::>()).unwrap(); + assert_eq!(l.heaps, [true, true]); + let args: Vec = [0x100u32, 0x120, 0x140, 0x5000, 7, 1, 2].iter().flat_map(|w| w.to_le_bytes()).collect(); + let heaps = [0x4c61_0000, 0x6381_0000]; + let io = two_pass_io(Some(&l), &args, 0x7_0000_0200, true, 0x4_0000_0000, heaps); + assert_eq!((io[8], io[9]), (0x200, 7)); + assert_eq!(&io[16..25], &[0x100, 0x120, 0x140, 0x5000, 7, 1, 2, 0x4c61_0000, 0x6381_0000]); + // a layout without the flags: nothing after the arguments + let mut l = l; + l.heaps = [false; 2]; + assert_eq!(two_pass_io(Some(&l), &args, 0x7_0000_0200, true, 0x4_0000_0000, heaps)[23..25], [0, 0]); + } + #[test] fn two_pass_groups_stay_inside_the_record_buffer() { // #304's transform record: 11 908 dwords From c800900d60ed1e3661cc244affbfdb77cfeb682a Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 13:03:33 +0100 Subject: [PATCH 007/258] local: precompile chains, place timers --- crates/xcl/src/hle/d3d12x/device_x.rs | 12 ++- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/place_times.rs | 114 +++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/vram.rs | 16 ++++ crates/xcl/src/shaders.rs | 37 ++++++-- 5 files changed, 170 insertions(+), 10 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/place_times.rs diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 9a88430b4a..a1a9c0a02f 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -13,6 +13,7 @@ //! Console queue and list types add DMA (0x10, the copy engine); console queue priorities //! are mapped onto PC ones. +use super::place_times::{self, Step}; use std::collections::HashMap; use std::ffi::{c_char, c_void, CStr, CString}; use std::sync::atomic::{AtomicI8, AtomicU64, Ordering}; @@ -1065,9 +1066,13 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, // placement takes no time (`pso_async::title_held`) let _in_pc = super::pso_async::pc_call(); let x: [u8; 0x38] = (desc as *const [u8; 0x38]).read_unaligned(); + let texture = u32::from_le_bytes(x[0..4].try_into().unwrap()) != D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; + let _total = texture.then(|| place_times::step(Step::Total)); + let timer = texture.then(|| place_times::step(Step::Desc)); let d = pc_resource_desc_for_device(this, &x); let buffer = u32::from_le_bytes(d[0..4].try_into().unwrap()) == D3D12_RESOURCE_DIMENSION_BUFFER.0 as u32; note_alias(va as usize, &x); + drop(timer); // console-only state bits (Unicorn Overlord's 4K display target: 0x100000) are not the // PC's: the PC refused the resource (E_INVALIDARG) and the title threw let state = pc_initial_state(u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()), state); @@ -1093,7 +1098,9 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, let mut placed_hr = None; if !buffer { let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); + let timer = place_times::step(Step::Desc); let console_bytes = crate::hle::xg::Texture::new(&x).ok().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); + drop(timer); if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { if hr >= 0 && !(*ppv).is_null() { @@ -1117,7 +1124,10 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, }; if hr >= 0 && !buffer && !(*ppv).is_null() { static M: AtomicU64 = AtomicU64::new(0); - match super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)) { + let timer = place_times::step(Step::Register); + let registered = super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)); + drop(timer); + match registered { Ok(()) => { real::note_title_address(*ppv as usize, va as usize); return hr; diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index f3f0357981..20806e702d 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -23,6 +23,7 @@ mod late_release; pub mod layout; pub mod list_x; pub mod null; +mod place_times; pub mod present; pub mod pso_async; pub mod real; diff --git a/crates/xcl/src/hle/d3d12x/place_times.rs b/crates/xcl/src/hle/d3d12x/place_times.rs new file mode 100644 index 0000000000..c005f4dd1b --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/place_times.rs @@ -0,0 +1,114 @@ +//! `XCL_PLACE_TIMES=1`: where the time of the title's texture placements goes +//! (`CreatePlacedResourceX` → `vram::place_pages`), logged every 4096 of them. Off: one load each. + +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::OnceLock; +use std::time::Instant; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Step { + /// the whole call, for a texture + Total, + /// the PC description, the alias note, the console's texture layout + Desc, + /// the CPU view of a GPU-view address (`canonical_va`) + Va, + /// waiting for the page table's lock, twice a placement + Lock, + /// `CreateReservedResource` + Reserved, + /// `GetResourceTiling` + Tiling, + /// pages gone idle, under the lock + Sweep, + /// `CreateHeap` of a pool heap, under the lock + Heap, + /// `UpdateTileMappings`, under the lock + Map, + /// the fence signal after them, under the lock + Signal, + /// `title_textures::register` + Register, +} + +const STEPS: [Step; 11] = [ + Step::Total, + Step::Desc, + Step::Va, + Step::Lock, + Step::Reserved, + Step::Tiling, + Step::Sweep, + Step::Heap, + Step::Map, + Step::Signal, + Step::Register, +]; +const EVERY: u64 = 4096; + +struct Sum { + calls: AtomicU64, + ns: AtomicU64, + max: AtomicU64, +} + +static SUMS: [Sum; STEPS.len()] = [const { Sum { calls: AtomicU64::new(0), ns: AtomicU64::new(0), max: AtomicU64::new(0) } }; STEPS.len()]; + +fn on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PLACE_TIMES").is_ok_and(|v| v.trim() == "1")) +} + +/// Times a step until dropped. +pub(super) struct Timer(Option<(Step, Instant)>); + +pub(super) fn step(step: Step) -> Timer { + Timer(on().then(|| (step, Instant::now()))) +} + +impl Drop for Timer { + fn drop(&mut self) { + let Some((step, since)) = self.0.take() else { return }; + let calls = add(step, since.elapsed().as_nanos() as u64); + if step == Step::Total && calls % EVERY == 0 { + crate::xlog_info!("D3D12.X: texture placements: {}", text()); + } + } +} + +/// How many times `step` has been counted, this one included. +fn add(step: Step, ns: u64) -> u64 { + let s = &SUMS[step as usize]; + s.ns.fetch_add(ns, Relaxed); + s.max.fetch_max(ns, Relaxed); + s.calls.fetch_add(1, Relaxed) + 1 +} + +fn text() -> String { + STEPS + .iter() + .map(|&s| { + let v = &SUMS[s as usize]; + let (calls, ns, max) = (v.calls.load(Relaxed), v.ns.load(Relaxed), v.max.load(Relaxed)); + format!("{s:?} {calls}x {} ms (max {:.1})", ns / 1_000_000, max as f64 / 1e6) + }) + .collect::>() + .join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_line_names_every_step_with_its_count_sum_and_longest() { + for (i, s) in STEPS.iter().enumerate() { + assert_eq!(*s as usize, i, "{s:?} has its own sum"); + } + assert_eq!(add(Step::Heap, 2_000_000), 1); + assert_eq!(add(Step::Heap, 5_500_000), 2); + let t = text(); + assert!(t.contains("Heap 2x 7 ms (max 5.5)"), "{t}"); + assert!(t.starts_with("Total 0x 0 ms"), "{t}"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 6ac17631f7..6ed4304ad5 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -23,6 +23,7 @@ //! driver does not make reserved: D32S8, MSAA): heaps of the placement's size, shared by //! placements inside them, let go 2 s after their last resource (256 MiB ones: 2.8 GB of D32S8). +use super::place_times::{step, Step}; use std::collections::HashSet; use std::ffi::c_void; use std::sync::Mutex; @@ -617,6 +618,7 @@ impl Pages { } let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: num_tiles, UseBox: false.into(), ..Default::default() }; + let _timer = step(Step::Map); self.queue.UpdateTileMappings( res, 1, @@ -630,6 +632,7 @@ impl Pages { D3D12_TILE_MAPPING_FLAG_NONE, ); } + let _timer = step(Step::Signal); self.value += 1; let _ = self.queue.Signal(&self.fence, self.value); } @@ -696,7 +699,9 @@ impl Pages { unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); + let timer = step(Step::Sweep); self.sweep(now); + drop(timer); let mut missing = 0usize; let mut preferred: Option = None; @@ -716,6 +721,7 @@ impl Pages { let pools = &mut self.pools; let pool = &mut self.pool; let fresh = pool.take_batch(missing, preferred, now, POOL_PAGES, || { + let _timer = step(Step::Heap); let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) })?; @@ -865,7 +871,9 @@ unsafe fn place_on_pages( riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void, ) -> Option { + let timer = step(Step::Va); let va = canonical_va(va); + drop(timer); if desc.Layout != D3D12_TEXTURE_LAYOUT_UNKNOWN || desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE1D { return None; } @@ -882,7 +890,9 @@ unsafe fn place_on_pages( }; let dev_key = dev.as_raw() as usize; let is_reservable = { + let timer = step(Step::Lock); let mut g = PAGES.lock().unwrap(); + drop(timer); let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)) }; @@ -892,7 +902,9 @@ unsafe fn place_on_pages( } // CreateReservedResource and GetResourceTiling do not touch `PAGES`; keep them outside the // lock so concurrent streaming threads, `before_execute`, and `page_bytes` do not serialize. + let timer = step(Step::Reserved); let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); + drop(timer); if hr < 0 || (*ppv).is_null() { log(&format!("{hr:#x}")); return None; @@ -900,9 +912,13 @@ unsafe fn place_on_pages( let raw = *ppv; let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; + let timer = step(Step::Tiling); dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + drop(timer); let bound = { + let timer = step(Step::Lock); let mut g = PAGES.lock().unwrap(); + drop(timer); if let Some(Some(pages)) = g.get_mut(&dev_key) { if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index ff9ac68b2e..a94f11bda7 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1220,19 +1220,38 @@ impl Pipelines { } } - /// The compute pipeline of `c` (made and released). + /// The compute pipeline of `c` (made and released). Of a program split into a dispatch chain + /// each piece's, and the whole form's an `ExecuteIndirect` runs: as the runtime makes them, + /// with the chain's root signature (`real::dispatch_chain`). fn make(&self, c: &recomp::pso::Compiled) { - self.make_with_cache_path(c, None); + match &c.dispatch_chain { + Some(chain) => { + for piece in &chain.pieces { + self.make_code(piece, &c.samplers, true, None); + } + self.make_code(&c.dxil, &c.samplers, true, None); + } + None => self.make_code(&c.dxil, &c.samplers, false, None), + } } + #[cfg(test)] fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { + self.make_code(&c.dxil, &c.samplers, false, path_override); + } + + fn make_code(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], split: bool, path_override: Option) { use windows::Win32::Graphics::Direct3D12::*; - let key: Vec = c.samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect(); + let key: Vec = samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).chain([split as u32]).collect(); let rs = { let mut g = self.signatures.lock().unwrap(); match g.get(&key) { Some(rs) => rs.clone(), - None => match recomp::pso::abi_root_signature_with(&self.dev, true, &c.samplers) { + None => match if split { + recomp::pso::dispatch_chain_root_signature(&self.dev, samplers) + } else { + recomp::pso::abi_root_signature_with(&self.dev, true, samplers) + } { Ok(rs) => { g.insert(key, rs.clone()); rs @@ -1246,19 +1265,19 @@ impl Pipelines { }; let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs)), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: c.dxil.as_ptr() as *const _, BytecodeLength: c.dxil.len() }, + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const _, BytecodeLength: dxil.len() }, ..Default::default() }; use crate::hle::d3d12x::real::driver_cache; - let path = path_override.or_else(|| driver_cache::path(&c.dxil, desc.Flags.0)); + let path = path_override.or_else(|| driver_cache::path(dxil, desc.Flags.0)); let cached = path.as_deref().and_then(driver_cache::load); - let over_cap = self.max_dxil != 0 && c.dxil.len() > self.max_dxil; + let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it // when a title needs the pipeline. `XCL_PIPELINE_MAX_KB` 0 turns the cap off. if cached.is_none() && over_cap { self.capped.fetch_add(1, Ordering::Relaxed); - self.capped_bytes.fetch_add(c.dxil.len(), Ordering::Relaxed); + self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); return; } @@ -1286,7 +1305,7 @@ impl Pipelines { *self.running.0.lock().unwrap() -= 1; self.running.1.notify_one(); self.capped.fetch_add(1, Ordering::Relaxed); - self.capped_bytes.fetch_add(c.dxil.len(), Ordering::Relaxed); + self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); return; } From 92f33421440be7c6a3be8276a8ca4527ccce2e8c Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 13:23:59 +0100 Subject: [PATCH 008/258] local: build cap, chain blob names --- crates/xcl/src/hle/d3d12x/real.rs | 25 +++++++++++++++++++++++++ crates/xcl/src/shaders.rs | 3 ++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 03ddc64d6e..0b5d4d33a2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4364,6 +4364,27 @@ pub(crate) use dispatch_chain::log_counts as log_dispatch_chain_counts; /// `chained`: built with the dispatch chain's root signature (`dispatch_chain`), whose driver blobs /// are kept apart on disk from the same DXIL's under the title's. +/// `XCL_PSO_MAX_KB`: a compute program of more KiB of DXIL that no earlier run left a driver blob +/// for is refused at once, as a driver that runs out of memory on it would after minutes (its +/// dispatches are skipped). 0 or unset: off. +fn build_cap_bytes() -> usize { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_PSO_MAX_KB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0usize).saturating_mul(1024)) +} + +fn over_build_cap(dxil: usize, cap: usize) -> bool { + cap != 0 && dxil > cap +} + +#[cfg(test)] +mod build_cap_tests { + #[test] + fn only_a_program_over_a_set_cap_is_refused() { + assert!(!super::over_build_cap(usize::MAX, 0), "off"); + assert!(!super::over_build_cap(2048, 2048) && super::over_build_cap(2049, 2048)); + } +} + unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, dxil: &[u8], record: u64, riid: *const GUID, ppv: *mut *mut c_void, chained: bool) -> (HRESULT, std::time::Duration, bool) { let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); @@ -4383,6 +4404,10 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL if let Some(b) = &cached { copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } + if cached.is_none() && over_build_cap(dxil.len(), build_cap_bytes()) { + crate::xlog_warn!("D3D12.X: compute PSO of record {record:016x} ({} B DXIL) not built: over XCL_PSO_MAX_KB and without a saved blob", dxil.len()); + return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); + } // in the background, a few at a time and within the commit headroom the program asks for let (mut hr, mut in_driver) = driver_compile_identified( "compute", diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index a94f11bda7..169bed743e 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1269,7 +1269,8 @@ impl Pipelines { ..Default::default() }; use crate::hle::d3d12x::real::driver_cache; - let path = path_override.or_else(|| driver_cache::path(dxil, desc.Flags.0)); + // (a chain's blobs are kept apart: `real::compute_container`) + let path = path_override.or_else(|| driver_cache::path(dxil, desc.Flags.0).map(|p| if split { p.with_extension("chain.pso") } else { p })); let cached = path.as_deref().and_then(driver_cache::load); let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes From f30ca3f037e474fe1ca1720835313db161b36004 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:35:24 +0530 Subject: [PATCH 009/258] kernelx: XCL_PAGE_ALIAS=1 shows a physical page at every address it is mapped at Without it XCL keeps a physical page at one address at a time and copies it when the title maps it elsewhere; the console shows the page at every address it is mapped at. A retail title maps its streamed pages into a pool, into the CPU view of a 24 GB reservation and into that reservation's GPU view (#1031). With `XCL_PAGE_ALIAS=1` (`kernelx::alias`): - a block of physical pages is a section (`kernelx::sections`) with a view of its own, through which XCL reads and writes pages by number (DirectStorage); the title never maps a page there; - the title's reservations of 64 KiB pages with no commit (its CPU view, GPU view and pool) are placeholders, and a page mapped there is a view of its slice, guarded (`kernelx::guards`) so that a write through one view is uploaded at all of them; `title_textures` adds those pages to what the write watch found; - a page mapped anywhere else (a placeholder region the title made in a sparse window) is moved there and back with its bytes, as before. Pages are committed on first use as before (`kernelx::lazy`); whether a page is committed is a bit per page: asking Windows walked the rest of a fresh block, and a title mapping 100 000 new pages one at a time took 20 s longer to its first frame. Measured in a traced run of a retail title: 3 blocks (11 360, 2 960 and 99 776 pages), 131 072 map calls in 150 s, nearly all single pages into its plain reservations, none at a page's home, no commit inside them. --- crates/xcl/src/hle/d3d12x/title_textures.rs | 3 + crates/xcl/src/hle/kernelx.rs | 70 ++- crates/xcl/src/hle/kernelx/alias.rs | 503 ++++++++++++++++++++ crates/xcl/src/hle/kernelx/lazy.rs | 1 + crates/xcl/src/hle/kernelx/sections.rs | 16 + 5 files changed, 591 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/hle/kernelx/alias.rs diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ac38429be7..caa0083fe0 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -705,6 +705,9 @@ unsafe fn refresh_once(queue: *mut c_void) { take_written(base, size, &mut buf, &mut dirty, &mut page); } }); + // views of physical pages are not write-watched: their writes are caught by guards + // (`XCL_PAGE_ALIAS`), a write through one view counting for all of them + crate::hle::kernelx::guards::take_dirty(&mut dirty, page as usize); dirty.sort_unstable(); dirty.len() }); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 74cdf34294..85b1d00a71 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -109,10 +109,10 @@ pub fn exports() -> Vec<(&'static str, usize)> { pub const MEM_GRAPHICS: u32 = 0x1000_0000; mod placeholders; pub mod lazy; -#[allow(dead_code)] // used once physical pages alias (`XCL_PAGE_ALIAS`) +#[allow(dead_code)] // `replace_with_reservation` and its inverse: not used yet pub mod sections; -#[allow(dead_code)] // `watch` / `take_dirty` used once physical pages alias (`XCL_PAGE_ALIAS`) pub mod guards; +pub mod alias; pub const MEM_TITLE: u32 = 0x4000_0000; const STD_ALLOC_MASK: u32 = 0x1000 | 0x2000 | 0x8_0000 | 0x10_0000 | 0x20_0000 | 0x100_0000; const STD_PROTECT_MASK: u32 = 0xFF | 0x100 | 0x200 | 0x400; @@ -252,6 +252,21 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: return q; } let uma = crate::gpu::uma::get(); + // physical page aliasing: the title's reservations of 64 KiB pages hold views of its pages, + // so it maps pages there and does not commit memory of its own (a retail title never does) + if alias::enabled() && !addr.is_null() && t & 0x1000 != 0 && alias::in_space(addr as usize) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("VirtualAlloc: a commit at {addr:p} in a reservation of 64 KiB pages that holds physical pages (XCL_PAGE_ALIAS) – refused")); + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return std::ptr::null_mut(); + } + if alias::enabled() && addr.is_null() && t & 0x2000 != 0 && t & 0x1000 == 0 && t & MEM_64K_PAGES == MEM_64K_PAGES { + if let Some(q) = alias::reserve_space(size) { + mirrors::reserved(q, size, t, p); + trace_mem("VirtualAlloc (64K pages, physical page space)", 0, size, t as u64, p, q); + return q as *mut c_void; + } + } // committing inside one of the title's reservations in a sparse window if !addr.is_null() && t & 0x1000 != 0 && uma.is_some_and(|u| u.is_sparse(addr as usize)) { let q = commit_sparse(addr as usize, size, p); @@ -413,6 +428,14 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 if let Some(ok) = placeholders::free(addr, size, t) { return ok; } + if alias::enabled() { + if let Some(ok) = alias::free_space(addr as usize, size, t) { + if ok && t & mem::MEM_RELEASE != 0 { + mirrors::released(addr as usize); + } + return ok as BOOL; + } + } // the title's reservations in a sparse window: decommit (and on release give the address // space back); their video memory goes with it if let Some(u) = crate::gpu::uma::get().filter(|u| u.is_sparse(addr as usize)) { @@ -476,6 +499,7 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si let a = addr as usize; if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a)) || (t & 0x8000 != 0 && in_graphics_reservation(a)) + || alias::in_space(a) { return VirtualFree(addr, size, t); } @@ -897,6 +921,9 @@ static AWAY: std::sync::Mutex> = std::sync::Mutex::new(None); /// Whether a physical page is mapped at the page holding `va` away from its home – committed /// or not yet (`lazy`: a page never used is committed at its first access). pub fn physical_page_at(va: usize) -> bool { + if alias::enabled() { + return alias::physical_page_at(va); + } AWAY.lock().unwrap().as_ref().is_some_and(|a| a.at.contains_key(&(va & !(PHYS_PAGE - 1)))) } @@ -969,6 +996,9 @@ unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: u /// number from `AllocateTitlePhysicalPages`). Returns `false` if `offset >= PHYS_PAGE_SIZE`, /// `pages` is too short, or any page is not a live allocation. pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8]) -> bool { + if alias::enabled() { + return alias::read(pages, offset, dst); + } if dst.is_empty() { return offset < PHYS_PAGE; } @@ -988,6 +1018,9 @@ pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8] /// Copy `src` into `pages` starting at `offset` within the first page. Validates every page /// before writing so the destination gets all bytes or nothing. pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) -> bool { + if alias::enabled() { + return alias::write(pages, offset, src); + } if src.is_empty() { return offset < PHYS_PAGE; } @@ -1220,6 +1253,13 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return 0; }; + if alias::enabled() { + if alias::allocate(n, arr) { + return 1; + } + fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); + return 0; + } let Some(u) = crate::gpu::uma::get() else { fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); return 0; @@ -1247,6 +1287,14 @@ pub unsafe extern "system" fn AllocateTitlePhysicalPages(_p: HANDLE, _t: u32, nu } pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: *mut usize) -> BOOL { + if alias::enabled() { + if arr.is_null() { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return 0; + } + alias::free(std::slice::from_raw_parts(arr, n)); + return 1; + } let Some(u) = crate::gpu::uma::get() else { return 0 }; if arr.is_null() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); @@ -1286,6 +1334,9 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: } pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _t: u32, _p: u32, arr: *mut usize) -> *mut c_void { + if alias::enabled() { + return map_aliased(va, n, arr); + } let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); let r = map_pages(away, va, n, arr); @@ -1293,6 +1344,18 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _ r } +/// `MapTitlePhysicalPages` with physical page aliasing (`alias`): the title always names the +/// address (a retail title never maps a page at its home, which is XCL's own view here). +unsafe fn map_aliased(va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { + if va.is_null() || n == 0 { + fnd::SetLastError(if va.is_null() { fnd::ERROR_NOT_SUPPORTED } else { fnd::ERROR_INVALID_PARAMETER }); + return std::ptr::null_mut(); + } + note_mapping_at(va as usize); + let pages: Vec = if arr.is_null() { vec![0; n] } else { std::slice::from_raw_parts(arr, n).to_vec() }; + if alias::map(va as usize, &pages) { va } else { std::ptr::null_mut() } +} + /// `MapTitlePhysicalPages` with `AWAY` held; the homes it moves away are given back by the /// caller (`give_back_homes`). unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { @@ -1413,6 +1476,9 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } + if alias::enabled() { + return (0..n).all(|i| !map_aliased(*addresses.add(i), 1, pages.add(i) as *mut usize).is_null()) as BOOL; + } if crate::gpu::uma::get().is_none() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs new file mode 100644 index 0000000000..9963212807 --- /dev/null +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -0,0 +1,503 @@ +//! Physical pages that show at every address they are mapped at (`XCL_PAGE_ALIAS=1`). +//! +//! Without it a physical page is kept at one address at a time and moved (copied) when the +//! title maps it elsewhere. With it a block of physical pages is a section (`sections`): the +//! title's reservations of 64 KiB pages are placeholders ("spaces"), and mapping a page there +//! maps a view of its slice, so every address the title mapped it at shows the same memory. +//! The views are guarded (`guards`): a write through one is uploaded at all of them. +//! +//! Each block also has a view of its own (its home, never given to the title) through which +//! XCL reads and writes pages by number (DirectStorage destinations). A retail title never maps +//! a page at its home, so homes are plain address space, not the GPU-visible sparse windows. +//! +//! A page mapped at an address outside a space (a placeholder region the title made in a +//! sparse window) is moved there as before: its bytes are copied there and back again when it +//! is unmapped. While it is away its views show what it held when it left. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use windows_sys::Win32::Foundation as fnd; +use windows_sys::Win32::System::Memory as mem; + +use super::sections::{self, Section, PAGE}; +use super::{guards, lazy, page_index, page_number, NEXT_PAGE_INDEX}; + +/// `XCL_PAGE_ALIAS=1` turns physical page aliasing on (default: off). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PAGE_ALIAS").is_ok_and(|v| v.trim() == "1")) +} + +struct Block { + section: Arc
, + /// XCL's own view of the whole block + home: usize, + /// pages not freed yet + live: usize, + /// one bit a page: committed (asking Windows walked the rest of a block's uncommitted run – + /// a retail title mapping 100 000 fresh pages one at a time waited 20 s for its first frame) + committed: Arc>, +} + +#[derive(Default)] +struct State { + /// first page index → block + blocks: BTreeMap, + /// the title's reservations kept as placeholders: base → size + spaces: BTreeMap, + /// address (64 KiB) in a space → (page number, its section, the page's index in it) + views: BTreeMap, usize)>, + /// pages moved to an address outside the spaces: page → address, and address → page + away: HashMap, + away_at: BTreeMap, +} + +static STATE: Mutex> = Mutex::new(None); + +fn with(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +impl State { + /// (block's section, the page's index in it, its address in the home view) of page number `page` + fn page(&self, page: usize) -> Option<(Arc
, usize, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + let i = index - first; + (i < b.section.pages()).then(|| (b.section.clone(), i, b.home + i * PAGE)) + } + + /// The commit bits of page number `page`'s block and its index there. + fn bits(&self, page: usize) -> Option<(Arc>, usize)> { + let index = page_index(page)?; + let (&first, b) = self.blocks.range(..=index).next_back()?; + (index - first < b.section.pages()).then(|| (b.committed.clone(), index - first)) + } + + fn in_space(&self, at: usize) -> bool { + self.spaces.range(..=at).next_back().is_some_and(|(&b, &n)| at < b + n) + } +} + +/// Whether page number `page` is committed (a page never used is not). +fn committed(page: usize) -> bool { + with(|s| s.bits(page)).is_some_and(|(b, i)| b[i / 64].load(Ordering::Acquire) & (1 << (i % 64)) != 0) +} + +/// Page number `page` is committed now. +fn note_committed(page: usize) { + if let Some((b, i)) = with(|s| s.bits(page)) { + b[i / 64].fetch_or(1 << (i % 64), Ordering::AcqRel); + } +} + +/// The view at `view` was committed by the lazy handler (its page's first use). +pub fn committed_at(view: usize) { + if let Some(page) = with(|s| s.views.get(&(view & !(PAGE - 1))).map(|v| v.0)) { + note_committed(page); + } +} + +/// A reservation of 64 KiB pages the title will map physical pages into: a space. None if +/// Windows refuses the address space. +pub fn reserve_space(size: usize) -> Option { + let len = size.checked_next_multiple_of(PAGE)?; + // SAFETY: only address space is reserved; `free_space` releases it. + let at = unsafe { sections::reserve(None, len) }?; + with(|s| s.spaces.insert(at, len)); + Some(at) +} + +/// Whether `p` lies in a space. +pub fn in_space(p: usize) -> bool { + enabled() && with(|s| s.in_space(p)) +} + +/// `VirtualFree` of an address in a space: release (the whole space) unmaps its pages and gives +/// the address space back; decommit unmaps the pages of the range. None: not a space. +pub unsafe fn free_space(addr: usize, size: usize, t: u32) -> Option { + let (base, len) = with(|s| s.spaces.range(..=addr).next_back().filter(|(&b, &n)| addr < b + n).map(|(&b, &n)| (b, n)))?; + if t & mem::MEM_RELEASE != 0 { + if addr != base || size != 0 { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return Some(false); + } + unmap_range(base, len); + with(|s| s.spaces.remove(&base)); + sections::release_all(base, len); + return Some(true); + } + let end = if size == 0 { base + len } else { addr.saturating_add(size).min(base + len) }; + unmap_range(addr & !(PAGE - 1), end - (addr & !(PAGE - 1))); + Some(true) +} + +unsafe fn unmap_range(at: usize, len: usize) { + let views: Vec = with(|s| s.views.range(at..at + len).map(|(&a, _)| a).collect()); + for a in views { + unmap_view(a); + } +} + +/// The view at `at` (if any) unmapped, leaving a placeholder. +unsafe fn unmap_view(at: usize) { + if with(|s| s.views.remove(&at)).is_some() { + guards::forget(at); + lazy::unmark(at); + sections::unmap(at); + } +} + +/// `count` physical pages for the title; their numbers in `arr`. +pub unsafe fn allocate(n: usize, arr: *mut usize) -> bool { + let Some(section) = Section::new(n) else { + crate::xlog_warn!("physical pages: a section of {n} pages could not be made"); + return false; + }; + let Some(home) = sections::reserve(None, n * PAGE) else { return false }; + if !section.map(0, n, home) { + sections::release(home); + return false; + } + let first = NEXT_PAGE_INDEX.fetch_add(n, Ordering::Relaxed); + for i in 0..n { + *arr.add(i) = page_number(first + i); + } + let committed = Arc::new((0..n.div_ceil(64)).map(|_| AtomicU64::new(0)).collect()); + with(|s| s.blocks.insert(first, Block { section: Arc::new(section), home, live: n, committed })); + true +} + +/// The title frees `pages`. Addresses that show one keep showing it (the title is meant to unmap +/// first); a block whose pages are all freed loses its home. +pub unsafe fn free(pages: &[usize]) { + let mut homes = Vec::new(); + with(|s| { + for &page in pages { + if let Some(at) = s.away.remove(&page) { + s.away_at.remove(&at); + } + let Some(index) = page_index(page) else { continue }; + let Some((&first, b)) = s.blocks.range_mut(..=index).next_back() else { continue }; + if index >= first + b.section.pages() { + continue; + } + b.live = b.live.saturating_sub(1); + if b.live == 0 { + homes.push(b.home); + s.blocks.remove(&first); + } + } + }); + for home in homes { + sections::unmap(home); + sections::release(home); + } +} + +/// Map `n` pages (`pages[i]`, 0: unmap) at `va`. Pages at an address in a space are views of +/// them; elsewhere they are moved there. False with the last error set if a page is not one of +/// the title's or Windows refuses. +pub unsafe fn map(va: usize, pages: &[usize]) -> bool { + if !va.is_multiple_of(PAGE) || pages.iter().any(|&p| p != 0 && with(|s| s.page(p)).is_none()) { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return false; + } + for (i, &page) in pages.iter().enumerate() { + let at = va + i * PAGE; + if !map_one(at, page) { + fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); + return false; + } + } + true +} + +unsafe fn map_one(at: usize, page: usize) -> bool { + // what was at `at` goes first + unmap_view(at); + unmap_away(at); + if page == 0 { + return true; + } + // a page moved elsewhere comes home first (it is at one address outside the spaces at most, + // as before): its views then show what it holds + if let Some(old) = with(|s| s.away.get(&page).copied()) { + unmap_away(old); + } + let (section, index, home) = with(|s| s.page(page)).unwrap(); + if with(|s| s.in_space(at)) { + if !section.map(index, 1, at) { + return false; + } + with(|s| s.views.insert(at, (page, section, index))); + guards::watch(page, at); + if !committed(page) { + // a page never used: committed at its first touch here (or through its home) + lazy::mark(at); + } + return true; + } + move_to(at, page, home) +} + +/// Page `page` moved to `at`, an address outside the spaces: committed there with its bytes. +unsafe fn move_to(at: usize, page: usize, home: usize) -> bool { + let u = crate::gpu::uma::get(); + let ok = if u.is_some_and(|u| u.is_committed(at)) { + true + } else if u.is_some_and(|u| u.is_sparse(at)) { + !super::commit_sparse(at, PAGE, mem::PAGE_READWRITE).is_null() + } else { + !mem::VirtualAlloc(at as *const c_void, PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() + }; + if !ok { + return false; + } + if committed(page) { + std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PAGE); + } else { + std::ptr::write_bytes(at as *mut u8, 0, PAGE); + } + with(|s| { + s.away.insert(page, at); + s.away_at.insert(at, page); + }); + true +} + +/// The page moved to `at` (if any) goes home with what `at` holds; `at` is decommitted. +unsafe fn unmap_away(at: usize) { + let Some((page, home)) = with(|s| { + let page = s.away_at.remove(&at)?; + s.away.remove(&page); + Some((page, s.page(page)?.2)) + }) else { + return; + }; + if sections::commit(home, PAGE) { + note_committed(page); + std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PAGE); + guards::written(page); + } + let u = crate::gpu::uma::get(); + if u.is_some_and(|u| u.is_committed(at)) { + return; + } + if u.is_some_and(|u| u.is_sparse(at)) { + crate::hle::d3d12x::sparse::decommitted(at, PAGE); + } + mem::VirtualFree(at as *mut c_void, PAGE, mem::MEM_DECOMMIT); +} + +/// Whether a physical page is mapped at the page holding `va` (a view, or a page moved there). +pub fn physical_page_at(va: usize) -> bool { + let at = va & !(PAGE - 1); + with(|s| s.views.contains_key(&at) || s.away_at.contains_key(&at)) +} + +/// Where page `page`'s bytes are now (committing its home if `write`), or None. +unsafe fn bytes_of(page: usize, write: bool) -> Option<(usize, bool)> { + let (away, home) = with(|s| (s.away.get(&page).copied(), s.page(page).map(|p| p.2))); + if let Some(at) = away { + return Some((at, true)); + } + let home = home?; + if committed(page) { + return Some((home, true)); + } + if write { + if !sections::commit(home, PAGE) { + return None; + } + note_committed(page); + return Some((home, true)); + } + Some((home, false)) +} + +/// `read_physical_pages` in alias mode. +pub unsafe fn read(pages: &[usize], offset: usize, dst: &mut [u8]) -> bool { + copy_pages(pages, offset, dst.len(), |addr, done, n| { + match addr { + Some(a) => std::ptr::copy_nonoverlapping(a as *const u8, dst.as_mut_ptr().add(done), n), + None => std::ptr::write_bytes(dst.as_mut_ptr().add(done), 0, n), + } + }, false) +} + +/// `write_physical_pages` in alias mode. +pub unsafe fn write(pages: &[usize], offset: usize, src: &[u8]) -> bool { + copy_pages(pages, offset, src.len(), |addr, done, n| { + if let Some(a) = addr { + std::ptr::copy_nonoverlapping(src.as_ptr().add(done), a as *mut u8, n); + } + }, true) +} + +/// Walk `len` bytes from `offset` in `pages`, calling `f(address or None for a page never used, +/// bytes done, bytes here)`. All pages are checked before any byte is touched. +unsafe fn copy_pages(pages: &[usize], offset: usize, len: usize, mut f: impl FnMut(Option, usize, usize), write: bool) -> bool { + if len == 0 { + return offset < PAGE; + } + let Some(need) = offset.checked_add(len).map(|end| end.div_ceil(PAGE)) else { return false }; + if offset >= PAGE || pages.len() < need { + return false; + } + let mut addrs = Vec::with_capacity(need); + for &p in &pages[..need] { + let Some(a) = bytes_of(p, write) else { return false }; + addrs.push((p, a)); + } + let (mut done, mut off) = (0, offset); + for (page, (addr, used)) in addrs { + let n = (PAGE - off).min(len - done); + f(used.then_some(addr + off), done, n); + if write && with(|s| !s.away.contains_key(&page)) { + guards::written(page); + } + done += n; + off = 0; + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + /// alias state and guards are one per process: these tests run one at a time, and not + /// beside the guards' own + use super::guards::tests::SERIAL; + + unsafe fn read64(at: usize) -> u64 { + std::ptr::read_volatile(at as *const u64) + } + + unsafe fn write64(at: usize, v: u64) { + std::ptr::write_volatile(at as *mut u64, v) + } + + fn pages(n: usize) -> Vec { + let mut arr = vec![0usize; n]; + assert!(unsafe { allocate(n, arr.as_mut_ptr()) }); + arr + } + + fn dirty() -> Vec { + let mut out = Vec::new(); + guards::take_dirty(&mut out, PAGE); + out.sort_unstable(); + out + } + + #[test] + fn a_page_mapped_into_two_spaces_is_one_page_and_writes_reach_both() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(4); + let cpu = reserve_space(8 * PAGE).unwrap(); + let gpu = reserve_space(8 * PAGE).unwrap(); + unsafe { + assert!(map(cpu + 2 * PAGE, &p[1..3])); + assert!(map(gpu + 5 * PAGE, &[p[2]])); + assert!(physical_page_at(gpu + 5 * PAGE + 123)); + write64(cpu + 3 * PAGE + 8, 0xABCD); // page p[2] through the first space + assert_eq!(read64(gpu + 5 * PAGE + 8), 0xABCD, "the other space shows the same page"); + dirty(); + write64(gpu + 5 * PAGE, 1); + assert_eq!(dirty(), vec![cpu + 3 * PAGE, gpu + 5 * PAGE], "a write through one view: both are uploaded"); + assert_eq!(free_space(cpu, 0, mem::MEM_RELEASE), Some(true)); + assert_eq!(read64(gpu + 5 * PAGE + 8), 0xABCD, "releasing one space leaves the page at the other"); + assert_eq!(free_space(gpu, 0, mem::MEM_RELEASE), Some(true)); + free(&p); + } + } + + #[test] + fn remapping_an_address_shows_the_new_page_and_keeps_the_old_one() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(2); + let s = reserve_space(2 * PAGE).unwrap(); + unsafe { + assert!(map(s, &[p[0]])); + write64(s, 11); + assert!(map(s, &[p[1]])); + assert_eq!(read64(s), 0, "a page never written reads zeros"); + assert!(map(s, &[0])); + assert!(!physical_page_at(s)); + assert!(map(s + PAGE, &[p[0]])); + assert_eq!(read64(s + PAGE), 11, "the first page kept what was written to it"); + free_space(s, 0, mem::MEM_RELEASE); + free(&p); + } + } + + #[test] + fn pages_read_and_written_by_number_are_the_pages_the_title_sees() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(3); + let s = reserve_space(3 * PAGE).unwrap(); + unsafe { + assert!(map(s, &p)); + dirty(); + // a DirectStorage destination: 16 bytes across the boundary of the first two pages + assert!(write(&p, PAGE - 8, &[7u8; 16])); + assert_eq!(read64(s + PAGE - 8), 0x0707_0707_0707_0707); + assert_eq!(read64(s + PAGE), 0x0707_0707_0707_0707); + assert_eq!(dirty(), vec![s, s + PAGE], "pages written by number are uploaded where they are mapped"); + write64(s + 2 * PAGE + 16, 5); + let mut back = [0u8; 8]; + assert!(read(&p[2..], 16, &mut back)); + assert_eq!(u64::from_le_bytes(back), 5); + let mut fresh = [1u8; 4]; + let q = pages(1); + assert!(read(&q, 0, &mut fresh)); + assert_eq!(fresh, [0; 4], "a page never used reads zeros without being committed"); + assert!(!read(&p, PAGE, &mut back), "an offset past the first page is refused"); + free_space(s, 0, mem::MEM_RELEASE); + free(&p); + free(&q); + } + } + + #[test] + fn a_page_moved_outside_the_spaces_goes_and_comes_back_with_its_bytes() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(1); + let s = reserve_space(PAGE).unwrap(); + // address space outside the spaces (as a title's own placeholder region would be) + let out = unsafe { mem::VirtualAlloc(std::ptr::null(), PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) } as usize; + unsafe { + assert!(map(s, &p)); + write64(s, 21); + assert!(map(out, &p)); + assert_eq!(read64(out), 21, "moved with its bytes"); + assert!(physical_page_at(out)); + write64(out, 22); + let mut b = [0u8; 8]; + assert!(read(&p, 0, &mut b)); + assert_eq!(u64::from_le_bytes(b), 22, "read by number where it is now"); + assert!(map(out, &[0])); + assert_eq!(read64(s), 22, "back home with what it held there"); + free_space(s, 0, mem::MEM_RELEASE); + mem::VirtualFree(out as *mut c_void, 0, mem::MEM_RELEASE); + free(&p); + } + } + + #[test] + fn a_page_not_from_the_title_is_refused() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let s = reserve_space(PAGE).unwrap(); + unsafe { + assert!(!map(s, &[page_number(1 << 40)])); + assert!(!map(s + 4, &[0]), "an address not on a page boundary is refused"); + free_space(s, 0, mem::MEM_RELEASE); + } + } +} diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index e92fa56b2d..fc0f11de8d 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -46,6 +46,7 @@ unsafe fn commit(page: usize) -> bool { } // (a view of a physical page committed here is writable, not guarded: count it as written) super::guards::committed(page); + super::alias::committed_at(page); true } diff --git a/crates/xcl/src/hle/kernelx/sections.rs b/crates/xcl/src/hle/kernelx/sections.rs index 9935686253..7af7bc4a02 100644 --- a/crates/xcl/src/hle/kernelx/sections.rs +++ b/crates/xcl/src/hle/kernelx/sections.rs @@ -155,6 +155,22 @@ pub unsafe fn reservation_to_placeholder(at: usize, len: usize) -> bool { VirtualFree(at as *mut c_void, len, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != 0 } +/// Release every placeholder in `[at, at + len)`, which splitting may have cut into many (views +/// in it must be unmapped first). True if all of it went. +/// +/// # Safety +/// `[at, at + len)` must be placeholders the caller owns. +pub unsafe fn release_all(at: usize, len: usize) -> bool { + let mut p = at; + while p < at + len { + match allocation_at(p) { + Some((base, size, MEM_RESERVE, _)) if base == p && release(p) => p += size, + _ => return false, + } + } + true +} + /// Release the placeholder at `at` (its whole extent; views in it must be unmapped first). /// /// # Safety From 4f34c8d0bb78f5fee5a9b62cd3c72fc9e064bf65 Mon Sep 17 00:00:00 2001 From: Xeltax <85458421+Xeltax@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:45:41 +0100 Subject: [PATCH 010/258] kernelx: queue CopyPageMappingsBatchX records the physical page each GPU-view page shows Queue method #31 (#29 of the older layout) maps pages of the title's memory into GPU views; it was a stub. Its batches are now decoded and checked against the batch count and the pool, and each 64 KiB page of a GPU view records the pool page it was given and the physical page the title had mapped there (kernelx::mirrors). A bad call records nothing; releasing a view drops its pages. XCL keeps a physical page's data where it was mapped last, and the title maps most streamed pages into the CPU view behind the GPU view too, so `mapped_source` answers where that page is now (`page_now`), else the pool page itself. Each title mapping is remembered per address (Away::title), written once the page is in place and forgotten when the reservation goes; a page freed while its allocation lives is no longer looked for (Away::freed). Nothing reads the record yet: textures are unchanged; the queue logs its counts. (#1031) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 29 +++ crates/xcl/src/hle/kernelx.rs | 346 +++++++++++++++++++++++++++++- 2 files changed, 367 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9241a3a18d..814cdc6399 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6123,6 +6123,7 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a f(this, a1) } 23 => q_signal_x(this, a1 as *mut c_void, a2 as u64, a3 as u32) as u32 as usize, + 29 => q_copy_page_mappings(a1 as u32, a2, a3, a4 as u32) as u32 as usize, 30 => super::present::present_x(this, a1 as u32, a2 as *const u8, a3 as *const u8) as u32 as usize, // the newer layout's #35: ExecuteCommandListsX(count, lists, a value, flags) – a retail // game submits all its command lists this way (flags 3; 0 for the one it recorded at @@ -6169,6 +6170,34 @@ macro_rules! queue_slots { } queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35); +/// command queue #29 (#31 in the newer layout) `CopyPageMappingsBatchX(count, batches, pool, +/// pool pages, flags)`: the title maps pages of its memory into GPU views – a retail game the +/// pages its texture streaming fills (a 6 GB pool) into the GPU views its textures are in, +/// tens of thousands of them while its world loads. Recorded per page (`kernelx::mirrors`); +/// as a stub every mapping was dropped (#1031). +unsafe fn q_copy_page_mappings(count: u32, batches: usize, pool: usize, pool_pages: u32) -> HRESULT { + static CALLS: AtomicU64 = AtomicU64::new(0); + static MAPPED: AtomicU64 = AtomicU64::new(0); + static UNMAPPED: AtomicU64 = AtomicU64::new(0); + static ELSEWHERE: AtomicU64 = AtomicU64::new(0); + static PHYSICAL: AtomicU64 = AtomicU64::new(0); + let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + match crate::hle::kernelx::mirrors::apply_batches(count, batches, pool, pool_pages) { + Some(d) => { + let add = |total: &AtomicU64, k: u64| total.fetch_add(k, Ordering::Relaxed) + k; + let (m, p, u, e) = (add(&MAPPED, d.mapped), add(&PHYSICAL, d.physical), add(&UNMAPPED, d.unmapped), add(&ELSEWHERE, d.elsewhere)); + if n == 1 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: queue CopyPageMappingsBatchX: {n} calls; GPU-view pages so far: {m} mapped ({p} to a physical page the title mapped there), {u} unmapped; {e} pages elsewhere ignored (pool {pool:#x}, {pool_pages} pages of 64 KiB)"); + } + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: queue CopyPageMappingsBatchX({count}, {batches:#x}, {pool:#x}, {pool_pages}): a batch or range is unreadable or leaves the pool – the call is ignored")); + } + } + S_OK +} + /// command queue #23 SignalX(fence, value, flush flags): Signal with the console's cache flush /// options – the PC's Signal makes the queue's writes visible itself. (A stub that signalled /// nothing left Fortnite's render fences pending: its render thread waited, textures were diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 85b1d00a71..71033f1b0b 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -217,8 +217,134 @@ pub mod mirrors { pub fn released(base: usize) { let mut s = STATE.lock().unwrap(); s.cpu.retain(|&(b, _)| b != base); - s.gpu.remove(&base); - s.gpu.retain(|_, &mut (_, c)| c != base); + // the GPU views that go with it, and the pages mapped into them + let gone: Vec<(usize, usize)> = s.gpu.iter().filter(|&(&g, &(_, c))| g == base || c == base).map(|(&g, &(n, _))| (g, n)).collect(); + for (g, n) in gone { + s.gpu.remove(&g); + let mut pages = PAGES.lock().unwrap(); + let keys: Vec = pages.range(g..g + n).map(|(&k, _)| k).collect(); + for k in keys { + pages.remove(&k); + } + } + } + + /// Bytes of a page the queue's page-mapping method maps (the console's 64 KiB pages). + pub const PAGE: usize = 0x1_0000; + + /// What a GPU-view page shows after the page-mapping method: the pool page it was given, + /// and the physical page the title had mapped there then (`None`: none). The console maps + /// that physical page, which the title often maps into the CPU view too – XCL keeps its + /// data where it was mapped last (`super::page_now`). + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub struct Shown { + pub pool: usize, + pub page: Option, + } + + /// Pages of GPU views the title pointed somewhere else with the queue's page-mapping + /// method (`CopyPageMappingsBatchX`, `apply_batches`): GPU-view page → what it shows, or + /// `None` for a page left unmapped. A page not listed shows its CPU view (`source`). + static PAGES: Mutex>> = Mutex::new(BTreeMap::new()); + + /// What the page-mapping method put under `va`: `Some(Some(a))` – `va` shows the bytes at + /// `a` (where XCL keeps the physical page now, else the pool page itself), `Some(None)` – + /// nothing (unmapped), `None` – the method never mapped that page. + pub fn mapped_source(va: usize) -> Option> { + let off = va & (PAGE - 1); + let shown = *PAGES.lock().unwrap().get(&(va - off))?; + Some(shown.map(|s| s.page.and_then(super::page_now).unwrap_or(s.pool) + off)) + } + + /// One call of the queue's page-mapping method, `CopyPageMappingsBatchX(count, batches, + /// pool, pool pages, flags)` (queue #29; #31 in the newer layout). `count` batches of 24 + /// bytes – the first destination address (u64), the number of ranges (u32), a pointer to + /// them at +16 – each range three u32: the kind (0: `count` pool pages from `start` on, + /// 1: pool page `start` at each of `count` pages, 2: unmapped, 3: left as they are), + /// `start` and `count`. Pages are 64 KiB; the pool is `pool_pages` of them at `pool`. + /// The layout as VIctory describes it (`crates/victory-gpu/src/queue.rs`, a reference + /// only: no code taken). Only pages of GPU views are recorded (the retail title maps into + /// nothing else). `None` – nothing recorded – when a batch or a range is not readable, a + /// range leaves the pool or has an unknown kind, or the call names over `MOST` pages. + pub unsafe fn apply_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option { + const BATCH: usize = 24; + const RANGE: usize = 12; + const MOST: usize = 1 << 20; + let readable = crate::gpu::shader::readable; + let n = count as usize; + if n == 0 { + return Some(Mapped::default()); + } + if n > MOST || !readable(batches, n * BATCH) { + return None; + } + // checked whole first, so a bad call records nothing + let mut changes: Vec<(usize, Option)> = Vec::new(); + for b in 0..n { + let p = batches + b * BATCH; + let dest = (p as *const u64).read_unaligned() as usize & !(PAGE - 1); + let ranges_n = ((p + 8) as *const u32).read_unaligned() as usize; + let ranges = ((p + 16) as *const usize).read_unaligned(); + if ranges_n == 0 { + continue; + } + if ranges_n > MOST || !readable(ranges, ranges_n * RANGE) { + return None; + } + let mut at = dest; + for r in 0..ranges_n { + let q = (ranges + r * RANGE) as *const u32; + let (kind, start, len) = (q.read_unaligned(), q.add(1).read_unaligned() as usize, q.add(2).read_unaligned() as usize); + let inside = |k: usize| start.checked_add(k).is_some_and(|e| e <= pool_pages as usize); + if changes.len() + len > MOST || at.checked_add(len * PAGE).is_none() { + return None; + } + match kind { + 0 if inside(len) => changes.extend((0..len).map(|k| (at + k * PAGE, Some(pool + (start + k) * PAGE)))), + 1 if inside(1) => changes.extend((0..len).map(|k| (at + k * PAGE, Some(pool + start * PAGE)))), + 2 => changes.extend((0..len).map(|k| (at + k * PAGE, None))), + 3 => {} + _ => return None, + } + at += len * PAGE; + } + } + // the physical page the title has mapped at each pool page: what the console maps + let changes: Vec<(usize, Option)> = { + let away = super::AWAY.lock().unwrap(); + let title = |pool: usize| away.as_ref().and_then(|a| a.title_page(pool)); + changes.into_iter().map(|(va, to)| (va, to.map(|pool| Shown { pool, page: title(pool) }))).collect() + }; + let s = STATE.lock().unwrap(); + let in_view = |va: usize| s.gpu.range(..=va).next_back().is_some_and(|(&g, &(size, _))| va < g + size); + let mut out = Mapped::default(); + let mut pages = PAGES.lock().unwrap(); + for (va, to) in changes { + if !in_view(va) { + out.elsewhere += 1; + continue; + } + match to { + Some(s) => { + out.mapped += 1; + out.physical += s.page.is_some() as u64; + } + None => out.unmapped += 1, + } + pages.insert(va, to); + } + Some(out) + } + + /// What one `apply_batches` call did, in 64 KiB pages. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub struct Mapped { + pub mapped: u64, + /// of those, pages whose pool page had a physical page the title mapped there + pub physical: u64, + pub unmapped: u64, + /// pages outside any GPU view: not recorded + pub elsewhere: u64, } /// The CPU-view address behind `va` when `va` lies in a GPU view. @@ -474,6 +600,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 if release { u.sparse_release(a); mirrors::released(a); + forget_title_mappings(a, n); } return 1; } @@ -487,9 +614,13 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 return 1; } let ok = mem::VirtualFree(addr, size, t); - if ok != 0 && t & 0x8000 != 0 && GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)).is_some() { - GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); - mirrors::released(addr as usize); + if ok != 0 && t & 0x8000 != 0 { + let released = GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)); + if let Some(len) = released { + GRAPHICS_RESERVATIONS_GEN.fetch_add(1, Ordering::Release); + mirrors::released(addr as usize); + forget_title_mappings(addr as usize, len); + } } ok } @@ -915,9 +1046,45 @@ struct Away { /// homes in a sparse window whose pages went away in this call, given back at its end in /// runs (`give_back_homes`): one page at a time, a retail game's start took 20 s gone: Vec, + /// address → the page the title mapped there last. On the console a page stays mapped at + /// every address it was mapped at; here its data is in one place (`page`), so an address it + /// moved away from still names it here (the queue's page-mapping method maps the pages of + /// such addresses: `mirrors::apply_batches`). + title: std::collections::HashMap, + /// pages the title freed while others of their allocation live (`page_home` still knows + /// the block): no page is behind such a number any more (numbers are never handed out + /// again), so `page_now` answers none for it + freed: std::collections::HashSet, +} + +impl Away { + /// The page the title mapped at `at` last, if the title has not freed it. + fn title_page(&self, at: usize) -> Option { + self.title.get(&at).copied().filter(|p| !self.freed.contains(p)) + } +} + +/// The title released `[base, base + len)`: the pages it mapped there are mapped there no more. +fn forget_title_mappings(base: usize, len: usize) { + if let Some(a) = AWAY.lock().unwrap().as_mut() { + a.title.retain(|&at, _| at < base || at >= base.saturating_add(len)); + } } static AWAY: std::sync::Mutex> = std::sync::Mutex::new(None); +/// Where page `page`'s data is now: the address it is mapped at away from home, else its home +/// (`None`: no allocated page has that number). +fn page_now(page: usize) -> Option { + let (freed, away) = match AWAY.lock().unwrap().as_ref() { + Some(a) => (a.freed.contains(&page), a.page.get(&page).copied()), + None => (false, None), + }; + if freed { + return None; + } + away.or_else(|| page_home(page)) +} + /// Whether a physical page is mapped at the page holding `va` away from its home – committed /// or not yet (`lazy`: a page never used is committed at its first access). pub fn physical_page_at(va: usize) -> bool { @@ -1301,14 +1468,22 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: return 0; } // freed pages mapped elsewhere: that address keeps whatever it holds, the mapping goes - if let Some(away) = AWAY.lock().unwrap().as_mut() { + { + let mut g = AWAY.lock().unwrap(); + let away = g.get_or_insert_with(Away::default); for i in 0..n { - if let Some(at) = away.page.remove(&*arr.add(i)) { + let page = *arr.add(i); + if let Some(at) = away.page.remove(&page) { away.at.remove(&at); note_mapping_at(at); } + if page_index(page).is_some() { + away.freed.insert(page); + } } } + // (blocks gone whole: their numbers need no `freed` entries) + let mut gone: Vec<(usize, usize)> = Vec::new(); let mut g = PHYS_BLOCKS.lock().unwrap(); for i in 0..n { let Some(page) = page_index(*arr.add(i)) else { continue }; @@ -1321,6 +1496,7 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: e.1 = e.1.saturating_sub(1); if e.1 == 0 { g.remove(&first); + gone.push((first, count)); if u.is_sparse(home) { crate::hle::d3d12x::sparse::free(home); } else if u.contains(home) { @@ -1330,6 +1506,12 @@ pub unsafe extern "system" fn FreeTitlePhysicalPages(_p: HANDLE, n: usize, arr: } } } + drop(g); + if !gone.is_empty() { + if let Some(away) = AWAY.lock().unwrap().as_mut() { + away.freed.retain(|&p| page_index(p).is_none_or(|i| !gone.iter().any(|&(f, c)| i >= f && i < f + c))); + } + } 1 } @@ -1383,6 +1565,9 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) } // (pages this call moved away and back are home again, not given back) away.gone.retain(|&h| h < home || h >= home + n * PHYS_PAGE); + for (i, &p) in pages.iter().enumerate() { + away.title.insert(home + i * PHYS_PAGE, p); + } for &p in &pages { if let Some(&at) = away.page.get(&p) { unmap_away(away, at, &(home..home + n * PHYS_PAGE)); @@ -1404,6 +1589,8 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let (mut at_run, mut home_run) = (StateRun::default(), StateRun::default()); for (i, &p) in pages.iter().enumerate() { let at = base + i * PHYS_PAGE; + // what was mapped at `at` goes; the new page is written down once it is in place + away.title.remove(&at); if unmap_away(away, at, &(0..0)) { (at_run, home_run) = Default::default(); } @@ -1416,6 +1603,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) match move_away(away, old, at, p, in_uma(at)) { Ok(true) => { (at_run, home_run) = Default::default(); + away.title.insert(at, p); continue; } // a lazy page is only unmarked: memory is as it was, the runs stay @@ -1435,6 +1623,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) lazy::mark(at); away.at.insert(at, p); away.page.insert(p, at); + away.title.insert(at, p); continue; } if !in_uma(at) && mem::VirtualAlloc(at as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { @@ -1454,6 +1643,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) } away.at.insert(at, p); away.page.insert(p, at); + away.title.insert(at, p); } va } @@ -2720,7 +2910,7 @@ mod tests { let at = mem::VirtualAlloc(std::ptr::null(), PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; mem::VirtualFree(at as *mut c_void, 0, mem::MEM_RELEASE); let page = 0x7E57_0000usize; - let mut away = Away { at: Default::default(), page: Default::default(), gone: Vec::new() }; + let mut away = Away::default(); away.at.insert(old, page); away.page.insert(page, old); assert!(move_away(&mut away, old, at, page, false).is_err()); @@ -2975,6 +3165,146 @@ mod tests { mirrors::released(other); } + /// A batch of the queue's page-mapping method: the first destination, the number of ranges + /// (`kind, start, count` each) and a pointer to them. + #[repr(C)] + struct Batch { + dest: u64, + ranges_n: u32, + _pad: u32, + ranges: usize, + } + fn batch(dest: usize, r: &[[u32; 3]]) -> Batch { + Batch { dest: dest as u64, ranges_n: r.len() as u32, _pad: 0, ranges: r.as_ptr() as usize } + } + + /// A GPU-view page given a pool page shows the physical page the title mapped there, where + /// XCL keeps it: at the pool page, then – once the title maps it into another address too + /// (the CPU view of a retail title's streamed textures) – there. + #[test] + fn a_gpu_view_page_shows_the_physical_page_where_it_is_kept() { + use mirrors::{apply_batches, mapped_source, Mapped, PAGE}; + let null = std::ptr::null_mut(); + unsafe { + let mut n = 1usize; + let mut page = [0usize; 1]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, page.as_mut_ptr()), 1); + // used at its home first, so the moves below copy it (no lazy page) + let home = MapTitlePhysicalPages(null, 1, 0, 4, page.as_mut_ptr()) as usize; + assert_ne!(home, 0); + *(home as *mut u32) = 0x600D; + // the pool: a reservation of the title's, the page mapped at its page 1 + let pool = mem::VirtualAlloc(std::ptr::null(), 4 * PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages((pool + PAGE) as *mut c_void, 1, 0, 4, page.as_mut_ptr()) as usize, pool + PAGE); + let (cpu, gpu, size) = (0x7140_0000_0000usize, 0x7146_0000_0000usize, 0x125 * PAGE); + mirrors::reserved(cpu, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + // pool pages 0 (nothing mapped there) and 1 at the GPU view's pages 2 and 3 + let r = [[0, 0, 2]]; + assert_eq!(apply_batches(1, [batch(gpu + 2 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 2, physical: 1, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + 2 * PAGE + 8), Some(Some(pool + 8)), "no physical page: the pool page itself"); + assert_eq!(mapped_source(gpu + 3 * PAGE + 8), Some(Some(pool + PAGE + 8))); + assert_eq!(*(pool as *const u8).add(PAGE).cast::(), 0x600D); + // the title maps the page at another address too: XCL moves its data there, and the + // GPU view shows it there + let other = mem::VirtualAlloc(std::ptr::null(), PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages(other as *mut c_void, 1, 0, 4, page.as_mut_ptr()) as usize, other); + assert_eq!(*(other as *const u32), 0x600D); + assert_eq!(mapped_source(gpu + 3 * PAGE + 8), Some(Some(other + 8))); + mirrors::released(cpu); + assert_eq!(FreeTitlePhysicalPages(null, 1, page.as_mut_ptr()), 1); + mem::VirtualFree(other as *mut c_void, 0, mem::MEM_RELEASE); + mem::VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// A page the title frees while the rest of its allocation lives is no longer looked for: + /// the GPU-view page given its pool page reads the pool page, which keeps its bytes; a later + /// call naming that pool page records no physical page (review of #1055). + #[test] + fn a_freed_page_is_read_at_its_pool_page() { + use mirrors::{apply_batches, mapped_source, Mapped, PAGE}; + let null = std::ptr::null_mut(); + unsafe { + let mut n = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let home = MapTitlePhysicalPages(null, 2, 0, 4, pages.as_mut_ptr()) as usize; + assert_ne!(home, 0); + *((home + PAGE) as *mut u32) = 0xBEEF; + let pool = mem::VirtualAlloc(std::ptr::null(), 4 * PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_eq!(MapTitlePhysicalPages((pool + 2 * PAGE) as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(1)) as usize, pool + 2 * PAGE); + let (cpu, gpu, size) = (0x7150_0000_0000usize, 0x7156_0000_0000usize, 0x126 * PAGE); + mirrors::reserved(cpu, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + let r = [[0u32, 2, 1]]; + assert_eq!(apply_batches(1, [batch(gpu + PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, physical: 1, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + PAGE), Some(Some(pool + 2 * PAGE))); + // page 1 freed alone: its block lives on (page 0), the pool page keeps the bytes + assert_eq!(FreeTitlePhysicalPages(null, 1, pages.as_mut_ptr().add(1)), 1); + assert!(page_home(pages[1]).is_some(), "the block is still allocated"); + assert_eq!(mapped_source(gpu + PAGE + 4), Some(Some(pool + 2 * PAGE + 4)), "the pool page, not the page's home"); + assert_eq!(*((pool + 2 * PAGE) as *const u32), 0xBEEF); + assert_eq!(apply_batches(1, [batch(gpu + 2 * PAGE, &r)].as_ptr() as usize, pool, 4), Some(Mapped { mapped: 1, ..Mapped::default() }), "no physical page behind it now"); + mirrors::released(cpu); + assert_eq!(FreeTitlePhysicalPages(null, 1, pages.as_mut_ptr()), 1); + assert!(AWAY.lock().unwrap().as_ref().is_some_and(|a| !a.freed.contains(&pages[1])), "the whole block gone: its numbers are forgotten"); + mem::VirtualFree(pool as *mut c_void, 0, mem::MEM_RELEASE); + } + } + + /// The queue's page-mapping method (`CopyPageMappingsBatchX`) points pages of a GPU view + /// at pool pages or at nothing; a bad call records nothing; releasing the view drops them. + #[test] + fn page_mappings_point_gpu_view_pages_at_pool_pages() { + use mirrors::{apply_batches, mapped_source, Mapped, PAGE}; + // (a size no other test uses, so the GPU view pairs with this CPU view) + let (cpu, gpu, size) = (0x7100_0000_0000usize, 0x7106_0000_0000usize, 0x123 * PAGE); + let (pool, pool_pages) = (0x7200_0000_0000usize, 64u32); + mirrors::reserved(cpu, size, 0x2040_2000, mem::PAGE_READWRITE); + mirrors::reserved(gpu, size, 0x2040_2000, 0x801); + assert_eq!(mirrors::source(gpu), Some(cpu)); + unsafe { + // two pool pages from 10 on, one page kept, pool page 5 three times, one unmapped; + // then two pages outside any GPU view + let r1 = [[0, 10, 2], [3, 0, 1], [1, 5, 3], [2, 0, 1]]; + let r2 = [[0, 0, 2]]; + let b = [batch(gpu + 4 * PAGE + 0x1234, &r1), batch(0x7300_0000_0000, &r2)]; + assert_eq!(apply_batches(2, b.as_ptr() as usize, pool, pool_pages), Some(Mapped { mapped: 5, unmapped: 1, elsewhere: 2, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + 4 * PAGE + 0x20), Some(Some(pool + 10 * PAGE + 0x20))); + assert_eq!(mapped_source(gpu + 5 * PAGE), Some(Some(pool + 11 * PAGE))); + assert_eq!(mapped_source(gpu + 6 * PAGE), None, "kept"); + for k in 7..10 { + assert_eq!(mapped_source(gpu + k * PAGE + 8), Some(Some(pool + 5 * PAGE + 8))); + } + assert_eq!(mapped_source(gpu + 10 * PAGE), Some(None), "unmapped"); + assert_eq!(mapped_source(gpu + 11 * PAGE), None, "past the ranges"); + assert_eq!(mapped_source(gpu + 3 * PAGE), None, "before the destination"); + assert_eq!(mapped_source(0x7300_0000_0000), None, "outside any GPU view"); + + // a later call maps the unmapped page + let r = [[1, 1, 1]]; + assert_eq!(apply_batches(1, [batch(gpu + 10 * PAGE, &r)].as_ptr() as usize, pool, pool_pages), Some(Mapped { mapped: 1, ..Mapped::default() })); + assert_eq!(mapped_source(gpu + 10 * PAGE), Some(Some(pool + PAGE))); + + // bad calls record nothing: a range leaving the pool (after a good one), an unknown + // kind, ranges that are not readable + let leaves = [[0, 0, 1], [0, 63, 2]]; + assert_eq!(apply_batches(1, [batch(gpu + 20 * PAGE, &leaves)].as_ptr() as usize, pool, pool_pages), None); + assert_eq!(mapped_source(gpu + 20 * PAGE), None); + let unknown = [[7, 0, 1]]; + assert_eq!(apply_batches(1, [batch(gpu + 20 * PAGE, &unknown)].as_ptr() as usize, pool, pool_pages), None); + let unreadable = Batch { dest: (gpu + 20 * PAGE) as u64, ranges_n: 1, _pad: 0, ranges: 0 }; + assert_eq!(apply_batches(1, [unreadable].as_ptr() as usize, pool, pool_pages), None); + assert_eq!(apply_batches(1, 0, pool, pool_pages), None, "batches not readable"); + assert_eq!(apply_batches(0, 0, pool, pool_pages), Some(Mapped::default()), "no batches"); + } + mirrors::released(cpu); + assert_eq!(mirrors::source(gpu), None); + assert_eq!(mapped_source(gpu + 4 * PAGE), None, "released with its GPU view"); + assert_eq!(mapped_source(gpu + 10 * PAGE), None); + } + /// GPU-visible title memory that reaches the plain-memory fallback (64 KiB pages, large /// pages, a graphics protection) is write-watched: a texture placed there sees the CPU's /// writes. The fallback is called directly: through `VirtualAlloc` these sizes land in a From 31fe59c037b3b43bf119f5ad7cff467211964b76 Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:40:24 +0530 Subject: [PATCH 011/258] kernelx: the page-mapping method's decoding apart from its record `mirrors::decode_batches` checks and decodes one call of the queue's CopyPageMappingsBatchX into (GPU-view page, pool page or unmapped) pairs; `apply_batches` records them as before. No change in behaviour: the next commit maps the decoded pages for real when physical pages alias. --- crates/xcl/src/hle/kernelx.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 71033f1b0b..5770b2ecb7 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -267,13 +267,22 @@ pub mod mirrors { /// nothing else). `None` – nothing recorded – when a batch or a range is not readable, a /// range leaves the pool or has an unknown kind, or the call names over `MOST` pages. pub unsafe fn apply_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option { + let changes = decode_batches(count, batches, pool, pool_pages)?; + record(changes) + } + + /// The mappings of one call of the page-mapping method (`apply_batches`), checked whole: + /// (GPU-view page, the pool page it is given or `None`: unmapped), in the call's order. + /// `None` when a batch or a range is not readable, a range leaves the pool or has an unknown + /// kind, or the call names over `MOST` pages. + pub unsafe fn decode_batches(count: u32, batches: usize, pool: usize, pool_pages: u32) -> Option)>> { const BATCH: usize = 24; const RANGE: usize = 12; const MOST: usize = 1 << 20; let readable = crate::gpu::shader::readable; let n = count as usize; if n == 0 { - return Some(Mapped::default()); + return Some(Vec::new()); } if n > MOST || !readable(batches, n * BATCH) { return None; @@ -309,6 +318,11 @@ pub mod mirrors { at += len * PAGE; } } + Some(changes) + } + + /// `apply_batches`'s record of the decoded mappings. + unsafe fn record(changes: Vec<(usize, Option)>) -> Option { // the physical page the title has mapped at each pool page: what the console maps let changes: Vec<(usize, Option)> = { let away = super::AWAY.lock().unwrap(); From 64ad64ce6bcae6a0b5847b54c24ff12d12d5324b Mon Sep 17 00:00:00 2001 From: Aditya Tripathi <9266227+adiologydev@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:42:10 +0530 Subject: [PATCH 012/258] kernelx: with XCL_PAGE_ALIAS=1 the queue's page mappings show real pages The queue's CopyPageMappingsBatchX maps pool pages into GPU views; on the console a GPU-view page then shows the physical page mapped at its pool page at the time of the call. #1055 decodes the calls and keeps a record of them; with physical pages aliasing (`kernelx::alias`) the GPU view is a reservation of views, so the decoded mappings are made for real: each GPU-view page becomes a view of the physical page mapped at its pool page now, or is unmapped (kind 2, or nothing mapped at the pool page). Textures in the GPU view then read the page at their own address (`title_textures` prefers an address with a physical page mapped), and a write through any view of the page is uploaded at all of them. Without the switch nothing changes: the call is recorded as in #1055. --- crates/xcl/src/hle/d3d12x/real.rs | 23 +++++++++ crates/xcl/src/hle/kernelx.rs | 6 +++ crates/xcl/src/hle/kernelx/alias.rs | 72 +++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 814cdc6399..89e013969c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6182,6 +6182,29 @@ unsafe fn q_copy_page_mappings(count: u32, batches: usize, pool: usize, pool_pag static ELSEWHERE: AtomicU64 = AtomicU64::new(0); static PHYSICAL: AtomicU64 = AtomicU64::new(0); let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + // physical pages alias (`XCL_PAGE_ALIAS`): the GPU-view pages show the pool pages' physical + // pages for real, instead of a record of them + if crate::hle::kernelx::alias::enabled() { + static EMPTY: AtomicU64 = AtomicU64::new(0); + let done = crate::hle::kernelx::mirrors::decode_batches(count, batches, pool, pool_pages).and_then(|changes| { + crate::hle::kernelx::note_gpu_view_mapping(changes.first().map_or(0, |c| c.0)); + crate::hle::kernelx::alias::apply_page_mappings(&changes) + }); + match done { + Some(d) => { + let add = |total: &AtomicU64, k: u64| total.fetch_add(k, Ordering::Relaxed) + k; + let (m, u, e) = (add(&MAPPED, d.mapped), add(&UNMAPPED, d.unmapped), add(&EMPTY, d.empty_pool)); + if n == 1 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: queue CopyPageMappingsBatchX: {n} calls; pages mapped so far: {m} showing a physical page, {u} unmapped ({e} of them for a pool page with nothing mapped; pool {pool:#x}, {pool_pages} pages of 64 KiB)"); + } + } + None => { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: queue CopyPageMappingsBatchX({count}, {batches:#x}, {pool:#x}, {pool_pages}): a batch or range is unreadable or leaves the pool, or a page could not be mapped")); + } + } + return S_OK; + } match crate::hle::kernelx::mirrors::apply_batches(count, batches, pool, pool_pages) { Some(d) => { let add = |total: &AtomicU64, k: u64| total.fetch_add(k, Ordering::Relaxed) + k; diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 5770b2ecb7..9ba91c677c 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1117,6 +1117,12 @@ pub fn gpu_view_map_gen() -> u64 { GPU_VIEW_MAP_GEN.load(Ordering::Acquire) } +/// The queue's page-mapping method mapped pages at `va`: a GPU view's mappings changed if it +/// lies in one (textures there look again). +pub fn note_gpu_view_mapping(va: usize) { + note_mapping_at(va); +} + /// Pages are mapped or unmapped at `va`: a GPU view's mappings changed if it lies in one. fn note_mapping_at(va: usize) { if mirrors::source(va).is_some() { diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs index 9963212807..5cf51b7603 100644 --- a/crates/xcl/src/hle/kernelx/alias.rs +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -300,6 +300,45 @@ pub fn physical_page_at(va: usize) -> bool { with(|s| s.views.contains_key(&at) || s.away_at.contains_key(&at)) } +/// The physical page mapped at the page holding `va` (a view, or a page moved there), or None. +pub fn page_at(va: usize) -> Option { + let at = va & !(PAGE - 1); + with(|s| s.views.get(&at).map(|v| v.0).or_else(|| s.away_at.get(&at).copied())) +} + +/// What one call of the queue's page-mapping method did, in 64 KiB pages. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Applied { + /// destination pages that show a physical page now + pub mapped: u64, + /// destination pages unmapped (by the call, or because nothing was mapped at their pool page) + pub unmapped: u64, + /// of those, pages whose pool page had nothing mapped + pub empty_pool: u64, +} + +/// The queue's page-mapping method (`CopyPageMappingsBatchX`, decoded by +/// `mirrors::decode_batches`): each destination page shows the physical page mapped at its pool +/// page now – on the console the method copies the pool page's mapping – or nothing. +pub unsafe fn apply_page_mappings(changes: &[(usize, Option)]) -> Option { + let mut out = Applied::default(); + for &(dest, pool) in changes { + let page = pool.and_then(page_at); + if !map_one(dest & !(PAGE - 1), page.unwrap_or(0)) { + return None; + } + match (pool, page) { + (_, Some(_)) => out.mapped += 1, + (Some(_), None) => { + out.unmapped += 1; + out.empty_pool += 1; + } + (None, _) => out.unmapped += 1, + } + } + Some(out) +} + /// Where page `page`'s bytes are now (committing its home if `write`), or None. unsafe fn bytes_of(page: usize, write: bool) -> Option<(usize, bool)> { let (away, home) = with(|s| (s.away.get(&page).copied(), s.page(page).map(|p| p.2))); @@ -490,6 +529,39 @@ mod tests { } } + #[test] + fn the_queue_page_mapping_method_shows_the_pool_pages_physical_page_in_the_gpu_view() { + let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + let p = pages(2); + let pool = reserve_space(4 * PAGE).unwrap(); + let cpu = reserve_space(4 * PAGE).unwrap(); + let gpu = reserve_space(4 * PAGE).unwrap(); + unsafe { + // a streamed page: in the pool and in the CPU view, written through the CPU view + assert!(map(pool + PAGE, &[p[0]])); + assert!(map(cpu + 2 * PAGE, &[p[0]])); + write64(cpu + 2 * PAGE, 0x5EED); + // kind 0 / 1: pool pages at GPU-view pages; pool page 3 holds nothing; kind 2: unmapped + let changes = [(gpu, Some(pool + PAGE)), (gpu + PAGE, Some(pool + PAGE)), (gpu + 2 * PAGE, Some(pool + 3 * PAGE)), (gpu + 3 * PAGE, None)]; + let done = apply_page_mappings(&changes).unwrap(); + assert_eq!(done, Applied { mapped: 2, unmapped: 2, empty_pool: 1 }); + assert_eq!(read64(gpu), 0x5EED, "the GPU view shows the page the CPU view wrote"); + assert_eq!(read64(gpu + PAGE), 0x5EED, "one pool page at two GPU-view pages"); + assert!(!physical_page_at(gpu + 2 * PAGE) && !physical_page_at(gpu + 3 * PAGE)); + dirty(); + write64(gpu + PAGE + 8, 1); + assert_eq!(dirty(), vec![pool + PAGE, cpu + 2 * PAGE, gpu, gpu + PAGE], "a write in the GPU view: every view of the page is uploaded"); + // the pool page is given another physical page later: the GPU view keeps the one it was given + assert!(map(pool + PAGE, &[p[1]])); + assert_eq!(read64(gpu), 0x5EED); + assert_eq!(page_at(gpu), Some(p[0])); + for s in [pool, cpu, gpu] { + free_space(s, 0, mem::MEM_RELEASE); + } + free(&p); + } + } + #[test] fn a_page_not_from_the_title_is_refused() { let _g = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); From 9ae786c5d3e0d8af37ee3ad53afadb7617c12112 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 13:45:35 +0100 Subject: [PATCH 013/258] D3D12.X: stand-ins of pipelines not built yet share the driver's pipelines --- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/pso_async.rs | 57 +++- crates/xcl/src/hle/d3d12x/real.rs | 86 +++++- crates/xcl/src/hle/d3d12x/standin.rs | 375 +++++++++++++++++++++++++ 4 files changed, 508 insertions(+), 11 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/standin.rs diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 20806e702d..a9439550e7 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -29,6 +29,7 @@ pub mod pso_async; pub mod real; mod shader_cache_session; pub mod sparse; +mod standin; pub mod title_list; pub mod title_textures; pub mod vram; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index b1fd4c2255..9db4ae2eb9 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -18,6 +18,8 @@ struct Pending { sent: std::sync::atomic::AtomicBool, /// the real pipeline state (raw pointer), 0 while building or when building failed real: AtomicUsize, + /// the driver pipeline binds get till then (`shared`); 0: the stand-in is one itself + driver: AtomicUsize, done: Mutex, cv: Condvar, compute: bool, @@ -349,6 +351,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(send), real: AtomicUsize::new(0), + driver: AtomicUsize::new(0), done: Mutex::new(false), cv: Condvar::new(), compute, @@ -579,6 +582,26 @@ mod used_tests { let _ = released(standin); } + /// A stand-in that is no driver object (`shared`) never reaches the driver: binds get the + /// driver pipeline shared with other stand-ins until the real one is built, and after a build + /// that failed. + #[test] + fn a_bind_of_a_shared_stand_in_gets_its_driver_pipeline() { + let (fails, builds, driver) = (0x7E57_B011usize, 0x7E57_B012usize, 0x7E57_B013usize); + submit_lazy(fails, false, Box::new(|| 0), 0); + submit_lazy(builds, false, Box::new(|| 0x1234), 0); + for s in [fails, builds] { + shared(s, driver); + assert_eq!(entry(s).unwrap().stand(s), driver); + } + assert_eq!(resolve_wait_for(fails, None), driver, "its build failed"); + assert_eq!(resolve(fails), driver); + assert_eq!(resolve_wait_for(builds, None), 0x1234); + assert_eq!(resolve_for_bind(builds), 0x1234); + // (0x1234 is no pipeline: taken, not released) + assert_eq!((released(fails), released(builds)), (0, 0x1234)); + } + /// A bind does not wait for a compute pipeline that writes only images: it gets the stand-in /// at once, with no budget, the build goes to the workers /// unwanted, and once built the bind gets the real one. Without `image_only` the same bind @@ -791,17 +814,37 @@ fn entry(pso: usize) -> Option> { PENDING.lock().unwrap().as_ref()?.get(&pso).cloned() } -/// The pipeline to use for `pso` now: the real one once built, else `pso` itself. +impl Pending { + /// What a bind of the stand-in `pso` gives the driver while the pipeline is not built. + fn stand(&self, pso: usize) -> usize { + match self.driver.load(Ordering::Acquire) { + 0 => pso, + d => d, + } + } +} + +/// Stand-in `standin` is no driver object (`standin::shell`): binds get `driver` in its place. +/// Told before the title has the stand-in. +pub fn shared(standin: usize, driver: usize) { + if let Some(p) = entry(standin) { + p.driver.store(driver, Ordering::Release); + } +} + +/// The pipeline to use for `pso` now: the real one once built, else the stand-in's driver +/// pipeline (`pso` itself when it is one). pub fn resolve(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); match p.real.load(Ordering::Acquire) { 0 => { // a lazy one is wanted now: to the workers + let stand = p.stand(pso); if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p); } - pso + stand } r => r, } @@ -835,7 +878,7 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { done = p.cv.wait(done).unwrap(); } match p.real.load(Ordering::Acquire) { - 0 => pso, + 0 => p.stand(pso), r => r, } } @@ -854,7 +897,7 @@ fn wait_budget() -> Option { /// dispatches are skipped) until a worker has built it. fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> usize { let built = |p: &Pending| match p.real.load(Ordering::Acquire) { - 0 => pso, + 0 => p.stand(pso), r => r, }; if *p.done.lock().unwrap() { @@ -864,7 +907,7 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> enqueue(p.clone()); } if p.late.load(Ordering::Acquire) { - return pso; + return p.stand(pso); } p.want(); let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); @@ -878,7 +921,7 @@ fn resolve_within(p: &Arc, pso: usize, budget: std::time::Duration) -> if n < 16 || n.is_power_of_two() { crate::xlog_warn!("D3D12.X: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far)", budget.as_millis(), n + 1); } - pso + p.stand(pso) } /// `XCL_PSO_IMAGE_SKIP=1`: a bind does not wait for a big compute program that writes nothing @@ -918,7 +961,7 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { crate::xlog_info!("D3D12.X: a compute program that writes only images is still being built: its dispatches are left out until it is ({} so far)", n + 1); } } - pso + p.stand(pso) } r => r, } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 0b5d4d33a2..e2505c7f12 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1709,6 +1709,12 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { n } +/// A stand-in that is no driver object (`standin`) was released for good. +pub(super) fn standin_released(pso: usize) { + forget_pso(pso); + super::pso_async::release(super::pso_async::released(pso)); +} + /// A stand-in pipeline released for good takes its background-built real pipeline with it. unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); @@ -5446,6 +5452,55 @@ unsafe fn standin_stream(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: finish_pso(this, f, new_desc.as_ptr() as *const c_void, riid, ppv) } +/// What the stand-in of `desc` shares its driver pipeline by (`standin::Key`): None for a desc +/// that cannot be read. The blend, rasterizer and depth state are not in it – a stand-in draws +/// nothing. +unsafe fn graphics_key(this: *mut c_void, desc: *const c_void) -> Option { + let d = &*(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC); + let mut state = Vec::with_capacity(64); + for w in [ + d.PrimitiveTopologyType.0 as u32, + d.IBStripCutValue.0 as u32, + d.NumRenderTargets, + d.DSVFormat.0 as u32, + d.SampleDesc.Count, + d.SampleDesc.Quality, + d.NodeMask, + d.Flags.0 as u32, + ] + .into_iter() + .chain(d.RTVFormats.iter().map(|f| f.0 as u32)) + { + state.extend_from_slice(&w.to_le_bytes()); + } + Some(super::standin::Key { device: this as usize, root_signature: std::mem::transmute_copy::<_, usize>(&d.pRootSignature), kind: 0, state }) +} + +unsafe fn compute_key(this: *mut c_void, desc: *const c_void) -> Option { + let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + let state = [d.NodeMask, d.Flags.0 as u32].iter().flat_map(|w| w.to_le_bytes()).collect(); + Some(super::standin::Key { device: this as usize, root_signature: std::mem::transmute_copy::<_, usize>(&d.pRootSignature), kind: 1, state }) +} + +/// `graphics_key` of a pipeline stream: its subobjects with the stand-in's shaders in place of +/// the title's, but the state a stand-in does not need. +unsafe fn stream_key(this: *mut c_void, desc: *const c_void) -> Option { + let (buf, _) = fallback_stream(desc as *const u8)?; + let (mut state, mut root_signature) = (Vec::new(), 0usize); + for (ty, p) in stream_subobjects(&buf)? { + match ty { + 0 => root_signature = u64::from_le_bytes(p.get(..8)?.try_into().ok()?) as usize, + // blend, sample mask, rasterizer, depth-stencil (and its later forms), cached blob + 8..=11 | 19 | 21 | 26..=28 => {} + _ => { + state.extend_from_slice(&ty.to_le_bytes()); + state.extend_from_slice(p); + } + } + } + Some(super::standin::Key { device: this as usize, root_signature, kind: 2, state }) +} + /// Hand the title `standin`'s result now and build the real pipeline with `build` on a worker. unsafe fn go_background( this: *mut c_void, @@ -5456,9 +5511,29 @@ unsafe fn go_background( compute: bool, owned: OwnedDesc, standin: unsafe fn(*mut c_void, PsoFn, *const c_void, *const GUID, *mut *mut c_void) -> HRESULT, + shared_by: unsafe fn(*mut c_void, *const c_void) -> Option, build: unsafe fn(Dev, &OwnedDesc, *mut *mut c_void) -> bool, ) -> Option { - let hr = standin(this, f, desc, riid, ppv); + let key = if super::standin::enabled() && !ppv.is_null() { shared_by(this, desc) } else { None }; + let mut driver = 0; + let hr = match key { + Some(key) => { + let made = super::standin::shell(key, || { + let mut out = std::ptr::null_mut(); + let hr = standin(this, f, desc, &pc_iid(Kind::PipelineState), &mut out); + if hr < 0 || out.is_null() { Err(hr) } else { Ok(out as usize) } + }); + match made { + Ok((shell, d)) => { + *ppv = shell; + driver = d; + S_OK + } + Err(hr) => hr, + } + } + None => standin(this, f, desc, riid, ppv), + }; if hr < 0 || ppv.is_null() || (*ppv).is_null() { static ONCE: AtomicU64 = AtomicU64::new(0); if ONCE.fetch_add(1, Ordering::Relaxed) < 3 { @@ -5483,6 +5558,9 @@ unsafe fn go_background( } else { super::pso_async::submit(*ppv as usize, compute, job); } + if driver != 0 { + super::pso_async::shared(*ppv as usize, driver); + } if image_only { super::pso_async::image_only(*ppv as usize); } @@ -5514,7 +5592,7 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv)) } else { (translated_graphics_pso(this, f, desc, riid, ppv), false) }; if missed { - if let Some(hr) = own_graphics(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_graphics, build_graphics)) { + if let Some(hr) = own_graphics(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_graphics, graphics_key, build_graphics)) { return hr; } if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv) { @@ -5559,7 +5637,7 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; if missed { - if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, build_compute)) { + if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, compute_key, build_compute)) { // a console program the worker is translating (its root signature comes with it); // the real PSO registers itself in TRANSLATED_COMPUTE once build_compute succeeds // (if build_compute fails, the stand-in stays unregistered so Dispatch / @@ -6784,7 +6862,7 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_mesh_stream(this, desc, riid, ppv)) } else { (translated_mesh_stream(this, desc, riid, ppv), false) }; if missed { - if let Some(hr) = own_stream(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_stream, build_stream)) { + if let Some(hr) = own_stream(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_stream, stream_key, build_stream)) { return hr; } if let Some(hr) = translated_mesh_stream(this, desc, riid, ppv) { diff --git a/crates/xcl/src/hle/d3d12x/standin.rs b/crates/xcl/src/hle/d3d12x/standin.rs new file mode 100644 index 0000000000..27bec34145 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/standin.rs @@ -0,0 +1,375 @@ +//! The stand-ins of pipelines not built yet (`pso_async`) share the driver's pipelines. +//! +//! A title gets an object of its own for each pipeline it makes, and a lazy one may never be +//! built. With a driver pipeline behind each of them a retail title's ~82 000 pipelines left +//! ~90 000 copies of the dummy shaders' programs on the process heap (4.8 GB in all). A stand-in +//! draws nothing whatever its state is, so those that differ only in what cannot matter (`Key`) +//! get one driver pipeline, and the title a small object (`Shell`) that is never given to the +//! driver: `pso_async::resolve` and its kin return the driver pipeline in its place. +//! +//! `XCL_SHARED_STANDINS=0`: off (a driver pipeline for each, as the title's own object). + +use std::collections::HashMap; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; + +use windows::core::GUID; + +use crate::util::{HRESULT, E_INVALIDARG, S_OK}; + +const DXGI_ERROR_NOT_FOUND: HRESULT = 0x887A_0002u32 as HRESULT; +const DXGI_ERROR_MORE_DATA: HRESULT = 0x887A_0003u32 as HRESULT; + +pub fn enabled() -> bool { + static E: OnceLock = OnceLock::new(); + // (console-shaped lists give the PC list their pipelines' objects themselves) + *E.get_or_init(|| std::env::var("XCL_SHARED_STANDINS").map_or(true, |v| v != "0") && !super::console_list::enabled()) +} + +/// What a driver pipeline must agree on with the pipelines it stands in for: the device, the +/// root signature and what the output merger checks. +#[derive(Clone, PartialEq, Eq, Hash, Debug)] +pub struct Key { + pub device: usize, + pub root_signature: usize, + pub kind: u8, + pub state: Vec, +} + +/// A driver pipeline and the root signature it was made with, held by the shells it stands for. +struct Shared { + pipeline: usize, + root_signature: usize, +} + +impl Drop for Shared { + fn drop(&mut self) { + unsafe { + unref(self.pipeline); + if self.root_signature != 0 { + unref(self.root_signature); + } + } + } +} + +static SHARED: Mutex>>> = Mutex::new(None); + +unsafe fn method(obj: usize, slot: usize) -> usize { + *(*(obj as *const *const usize)).add(slot) +} + +unsafe fn addref(obj: usize) { + let f: unsafe extern "system" fn(usize) -> u32 = std::mem::transmute(method(obj, 1)); + f(obj); +} + +unsafe fn unref(obj: usize) { + let f: unsafe extern "system" fn(usize) -> u32 = std::mem::transmute(method(obj, 2)); + f(obj); +} + +/// A title's object for a pipeline, and the driver pipeline that stands in for it. `make` makes +/// that one (its reference is taken over) when no other stand-in of `key` is alive. +/// +/// # Safety +/// `key.root_signature` is 0 or a live object; `make` returns a live pipeline or an error. +pub unsafe fn shell(key: Key, make: impl FnOnce() -> Result) -> Result<(*mut c_void, usize), HRESULT> { + let found = SHARED.lock().unwrap().as_ref().and_then(|m| m.get(&key)).and_then(Weak::upgrade); + let shared = match found { + Some(s) => s, + None => { + // (outside the lock: the driver's call; a second thread's pipeline of the same key + // replaces the first in the table, both live as long as their shells) + let pipeline = make()?; + if key.root_signature != 0 { + // a root signature's address must not come back for another one while the key lives + addref(key.root_signature); + } + let s = Arc::new(Shared { pipeline, root_signature: key.root_signature }); + let mut g = SHARED.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if m.len() >= 64 && m.len().is_power_of_two() { + m.retain(|_, w| w.strong_count() != 0); + } + m.insert(key, Arc::downgrade(&s)); + let n = m.len(); + drop(g); + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} driver pipelines stand in for the pipelines not built yet"); + } + s + } + }; + let pipeline = shared.pipeline; + let p = Box::into_raw(Box::new(Shell { vtable: vtable() as *const usize, refs: AtomicU32::new(1), shared, data: Mutex::new(Vec::new()) })); + Ok((p as *mut c_void, pipeline)) +} + +/// ID3D12PipelineState as the title sees it. +#[repr(C)] +struct Shell { + vtable: *const usize, + refs: AtomicU32, + shared: Arc, + /// private data (an object's own: the driver pipeline is shared) + data: Mutex>, +} + +enum Data { + Bytes(Vec), + /// an interface, with a reference + Interface(usize), +} + +impl Drop for Data { + fn drop(&mut self) { + if let Data::Interface(p) = self { + unsafe { unref(*p) }; + } + } +} + +unsafe extern "system" fn query_interface(this: *mut c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + if ppv.is_null() || riid.is_null() { + return E_INVALIDARG; + } + // the interfaces the driver's object has + let pipeline = (&*(this as *const Shell)).shared.pipeline; + let f: unsafe extern "system" fn(usize, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(method(pipeline, 0)); + let mut out = std::ptr::null_mut(); + let hr = f(pipeline, riid, &mut out); + *ppv = std::ptr::null_mut(); + if hr < 0 || out.is_null() { + return hr; + } + unref(out as usize); + add_ref(this); + *ppv = this; + S_OK +} + +unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (&*(this as *const Shell)).refs.fetch_add(1, Ordering::AcqRel) + 1 +} + +unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let n = (&*(this as *const Shell)).refs.fetch_sub(1, Ordering::AcqRel) - 1; + if n == 0 { + super::real::standin_released(this as usize); + drop(Box::from_raw(this as *mut Shell)); + } + n +} + +unsafe extern "system" fn get_private_data(this: *mut c_void, guid: *const GUID, size: *mut u32, out: *mut u8) -> HRESULT { + if guid.is_null() || size.is_null() { + return E_INVALIDARG; + } + let data = (&*(this as *const Shell)).data.lock().unwrap(); + let Some((_, d)) = data.iter().find(|(g, _)| *g == (*guid).to_u128()) else { + *size = 0; + return DXGI_ERROR_NOT_FOUND; + }; + let interface; + let bytes: &[u8] = match d { + Data::Bytes(b) => b, + Data::Interface(p) => { + interface = p.to_le_bytes(); + &interface + } + }; + let room = std::mem::replace(&mut *size, bytes.len() as u32) as usize; + if out.is_null() { + return S_OK; + } + if room < bytes.len() { + return DXGI_ERROR_MORE_DATA; + } + std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len()); + if let Data::Interface(p) = d { + addref(*p); + } + S_OK +} + +unsafe fn put(this: *mut c_void, guid: *const GUID, d: Option) -> HRESULT { + if guid.is_null() { + return E_INVALIDARG; + } + let id = (*guid).to_u128(); + let old = { + let mut data = (&*(this as *const Shell)).data.lock().unwrap(); + let old = data.iter().position(|(g, _)| *g == id).map(|i| data.swap_remove(i)); + if let Some(d) = d { + data.push((id, d)); + } + old + }; + // (outside the lock: an interface's Release is the title's code) + drop(old); + S_OK +} + +unsafe extern "system" fn set_private_data(this: *mut c_void, guid: *const GUID, size: u32, data: *const u8) -> HRESULT { + put(this, guid, (!data.is_null()).then(|| Data::Bytes(std::slice::from_raw_parts(data, size as usize).to_vec()))) +} + +unsafe extern "system" fn set_private_data_interface(this: *mut c_void, guid: *const GUID, obj: usize) -> HRESULT { + if obj != 0 { + addref(obj); + } + put(this, guid, (obj != 0).then_some(Data::Interface(obj))) +} + +unsafe extern "system" fn set_name(_this: *mut c_void, _name: *const u16) -> HRESULT { + S_OK +} + +unsafe extern "system" fn get_device(this: *mut c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let pipeline = (&*(this as *const Shell)).shared.pipeline; + let f: unsafe extern "system" fn(usize, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(method(pipeline, 7)); + f(pipeline, riid, ppv) +} + +unsafe extern "system" fn get_cached_blob(this: *mut c_void, ppv: *mut *mut c_void) -> HRESULT { + let pipeline = (&*(this as *const Shell)).shared.pipeline; + let f: unsafe extern "system" fn(usize, *mut *mut c_void) -> HRESULT = std::mem::transmute(method(pipeline, 8)); + f(pipeline, ppv) +} + +const SLOTS: usize = 64; + +fn vtable() -> usize { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| { + let known: [usize; 9] = [ + query_interface as usize, + add_ref as usize, + release as usize, + get_private_data as usize, + set_private_data as usize, + set_private_data_interface as usize, + set_name as usize, + get_device as usize, + get_cached_blob as usize, + ]; + let v: Vec = (0..SLOTS) + .map(|i| known.get(i).copied().unwrap_or_else(|| crate::stubs::make_stub_info("d3d12_xs.dll", &format!("ID3D12PipelineState(stand-in)::#{i}"), 0).0)) + .collect(); + Box::leak(v.into_boxed_slice()).as_ptr() as usize + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A COM object that counts its references and has one interface. + #[repr(C)] + struct Counted { + vtable: *const usize, + refs: AtomicU32, + } + + const KNOWN: GUID = GUID::from_u128(0x765a30f3_f624_4c6f_a828_ace948622445); + + unsafe extern "system" fn qi(this: *mut c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + if *riid != KNOWN { + *ppv = std::ptr::null_mut(); + return 0x8000_4002u32 as HRESULT; + } + up(this); + *ppv = this; + S_OK + } + unsafe extern "system" fn up(this: *mut c_void) -> u32 { + (*(this as *const Counted)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn down(this: *mut c_void) -> u32 { + (*(this as *const Counted)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + + fn counted() -> &'static Counted { + let v: &'static [usize; 3] = Box::leak(Box::new([qi as usize, up as usize, down as usize])); + Box::leak(Box::new(Counted { vtable: v.as_ptr(), refs: AtomicU32::new(1) })) + } + + fn at(c: &Counted) -> usize { + c as *const _ as usize + } + + fn refs(c: &Counted) -> u32 { + c.refs.load(Ordering::Acquire) + } + + fn key(rs: &Counted, state: u8) -> Key { + Key { device: 1, root_signature: at(rs), kind: 0, state: vec![state] } + } + + #[test] + fn pipelines_of_one_key_share_a_driver_pipeline_while_one_of_them_lives() { + let (rs, a, b) = (counted(), counted(), counted()); + unsafe { + let (s1, d1) = shell(key(rs, 1), || Ok(at(a))).unwrap(); + let (s2, d2) = shell(key(rs, 1), || panic!("made again")).unwrap(); + assert_ne!(s1, s2, "the title's objects are its own"); + assert_eq!((d1, d2), (at(a), at(a))); + let (s3, d3) = shell(key(rs, 2), || Ok(at(b))).unwrap(); + assert_eq!(d3, at(b), "another state, another pipeline"); + assert_eq!(refs(rs), 3, "the root signature is held by each driver pipeline"); + assert_eq!(release(s1), 0); + assert_eq!(refs(a), 1, "still stands in for the second"); + assert_eq!(release(s2), 0); + assert_eq!((refs(a), refs(rs)), (0, 2), "gone with the last"); + let c = counted(); + let (s4, d4) = shell(key(rs, 1), || Ok(at(c))).unwrap(); + assert_eq!(d4, at(c), "made again when none of its key is alive"); + release(s3); + release(s4); + assert_eq!(refs(rs), 1); + assert_eq!(shell(key(rs, 9), || Err(E_INVALIDARG)).err(), Some(E_INVALIDARG)); + assert_eq!(refs(rs), 1); + } + } + + #[test] + fn a_shell_has_the_drivers_interfaces_and_its_own_references_and_private_data() { + let (rs, a, held) = (counted(), counted(), counted()); + unsafe { + let (s, _) = shell(key(rs, 3), || Ok(at(a))).unwrap(); + let (other, _) = shell(key(rs, 3), || panic!("made again")).unwrap(); + let mut out = std::ptr::null_mut(); + assert_eq!(query_interface(s, &KNOWN, &mut out), S_OK); + assert_eq!(out, s, "the title keeps its object"); + assert_eq!(refs(a), 1, "the driver's is not handed out"); + assert_eq!(release(s), 1); + assert!(query_interface(s, &GUID::from_u128(7), &mut out) < 0 && out.is_null()); + + let id = GUID::from_u128(0x1234); + let mut n = 99u32; + assert_eq!(get_private_data(s, &id, &mut n, std::ptr::null_mut()), DXGI_ERROR_NOT_FOUND); + assert_eq!(n, 0); + assert_eq!(set_private_data(s, &id, 3, [1u8, 2, 3].as_ptr()), S_OK); + let mut buf = [0u8; 8]; + n = 2; + assert_eq!(get_private_data(s, &id, &mut n, buf.as_mut_ptr()), DXGI_ERROR_MORE_DATA); + assert_eq!(n, 3); + assert_eq!(get_private_data(s, &id, &mut n, buf.as_mut_ptr()), S_OK); + assert_eq!(&buf[..3], &[1, 2, 3]); + assert_eq!(get_private_data(other, &id, &mut n, buf.as_mut_ptr()), DXGI_ERROR_NOT_FOUND, "another object's data is its own"); + assert_eq!(set_private_data_interface(s, &id, at(held)), S_OK); + n = 8; + assert_eq!(get_private_data(s, &id, &mut n, buf.as_mut_ptr()), S_OK); + assert_eq!((usize::from_le_bytes(buf), refs(held)), (at(held), 3), "handed out with a reference"); + assert_eq!(set_private_data(s, &id, 0, std::ptr::null()), S_OK); + assert_eq!(refs(held), 2, "removed"); + assert_eq!(set_private_data_interface(s, &id, at(held)), S_OK); + release(s); + assert_eq!(refs(held), 2, "let go with the object"); + release(other); + assert_eq!(refs(a), 0); + } + } +} From 6c8d787e249dba87b60ec285c967d92b37a38704 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 14:02:38 +0100 Subject: [PATCH 014/258] D3D12.X: a split dispatch runs in slabs that share a bounded scratch Each chained dispatch made a scratch buffer for all its groups and kept it until the allocator's reset. A retail title's 176 split programs need 187 KB a group (median), 3 GB for 960x540 pixels in groups of 8x4. At most XCL_SPLIT_SCRATCH_MB (256) of groups now run at once, each piece adding the slab's origin to the group ids, and the chains recorded on one list share the buffer. --- crates/xcl/src/gpu/dxil/module/split.rs | 51 +++++++++++--- crates/xcl/src/gpu/recomp/pso.rs | 69 +++++++++++++++--- crates/xcl/src/gpu/recomp/runner.rs | 21 ++++-- crates/xcl/src/hle/d3d12x/list_x.rs | 1 + .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 70 ++++++++++++++++--- 5 files changed, 181 insertions(+), 31 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index f147fbab04..f14751b43b 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -31,13 +31,41 @@ struct Scratch { bytes_per_slot: u32, } +/// The part of a dispatch a chain runs at once (`pso::record_dispatch_chain`): its groups in X +/// and Y, and the dispatch's group its first one is. +struct Slab { + width: Value, + height: Value, + origin: [Value; 3], +} + +impl Slab { + fn new(s: &mut Shader) -> Self { + let cb = s.cbv(0, 2, 32); + let ty = s.m.i32(); + let [size, origin] = [0, 1].map(|row| { + let row = s.m.i32c(row); + s.cbuffer_load_legacy(cb, row, ty) + }); + Self { width: size[0], height: size[1], origin: [origin[0], origin[1], origin[2]] } + } + + /// The program's value for its copied instruction `v`: a group id is the dispatch's, not the slab's. + fn group_id(&self, src: &Module, op: &Op, m: &mut Module, v: Value) -> Value { + match op { + Op::Call(f, args) if src.funcs[*f as usize].name.starts_with("dx.op.groupId") => match args.get(1).and_then(|&a| src.const_u64(a)) { + Some(axis @ 0..=2) => m.bin(BinOp::Add, v, self.origin[axis as usize]), + _ => v, + }, + _ => v, + } + } +} + impl Scratch { - fn new(s: &mut Shader, stride: u32, threads: u32, lane: Value) -> Self { + fn new(s: &mut Shader, slab: &Slab, stride: u32, threads: u32, lane: Value) -> Self { let uav = s.raw_uav(0, 2); - let cb = s.cbv(0, 2, 16); - let zero = s.m.i32c(0); - let ty = s.m.i32(); - let [width, height, _, _] = s.cbuffer_load_legacy(cb, zero, ty); + let (width, height) = (slab.width, slab.height); let [x, y, z] = [0, 1, 2].map(|axis| s.group_id(axis)); let row = s.m.bin(BinOp::Mul, z, height); let row = s.m.bin(BinOp::Add, row, y); @@ -126,14 +154,16 @@ impl Shader { let src = &self.m; let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); + let slab = Slab::new(&mut dst); for &id in prefix { let def = &src.insts[id as usize]; let mut op = def.op.clone(); op.map_operands(|v| *values.get(&v).unwrap_or(&v)); - values.insert(Value::Inst(id), dst.m.push(op, def.ty)); + let v = dst.m.push(op, def.ty); + values.insert(Value::Inst(id), slab.group_id(src, &def.op, &mut dst.m, v)); } let lane = prefix.last().map(|&i| values[&Value::Inst(i)]).unwrap_or_else(|| dst.wave_lane_index()); - let scratch = Scratch::new(&mut dst, stride, threads[0], lane); + let scratch = Scratch::new(&mut dst, &slab, stride, threads[0], lane); let local: HashMap<_, _> = plan.blocks[stage].iter().map(|&b| (b, dst.m.new_block())).collect(); let mut hops = HashMap::new(); let mut exits = HashMap::new(); @@ -188,7 +218,7 @@ impl Shader { dst.raw_store(scratch.uav, scratch.base, &[zero]); } let v = dst.m.push(old.op.clone(), old.ty); - values.insert(Value::Inst(i), v); + values.insert(Value::Inst(i), slab.group_id(src, &old.op, &mut dst.m, v)); copied.push((block, inst(v)?)); } } @@ -1042,6 +1072,11 @@ mod tests { assert_eq!(reference, expected, "unsplit {threads}"); let result = runner::dispatch_split(&chain, [2, 3, 2], &initial).unwrap(); assert_eq!(result, expected, "split {threads}"); + // in slabs: single groups, a row (and a part of one), a plane, all + for most in [1, 2, 3, 6, 7, 12] { + let result = runner::dispatch_split_by(&chain, [2, 3, 2], &initial, most).unwrap(); + assert_eq!(result, expected, "split {threads}, {most} groups at once"); + } println!("CHAIN_BRANCH threads={threads} pieces={} scratch_words_per_group={} checked_words={words} guards=16", chain.pieces.len(), chain.dwords_per_group); } } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 00ac0a064b..4dd688c9de 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1183,23 +1183,46 @@ pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[S } /// Record all piece dispatches after the six common root views have been bound. +/// The slabs of at most `most` groups a chain runs a dispatch of `grid` groups in, as (first +/// group, groups): whole planes, else whole rows, else parts of one. Each uses the same scratch. +pub(crate) fn dispatch_slabs(grid: [u32; 3], most: u64) -> Vec<([u32; 3], [u32; 3])> { + let [x, y, z] = grid; + let fit = |n: u32, of: u64| (n as u64).min((most / of.max(1)).max(1)) as u32; + let sx = fit(x, 1); + let sy = if sx == x { fit(y, x as u64) } else { 1 }; + let sz = if sx == x && sy == y { fit(z, x as u64 * y as u64) } else { 1 }; + let at = |n: u32, step: u32| (0..n).step_by(step.max(1) as usize).map(move |k| (k, step.min(n - k))); + let mut out = Vec::new(); + for (oz, nz) in at(z, sz) { + for (oy, ny) in at(y, sy) { + for (ox, nx) in at(x, sx) { + out.push(([ox, oy, oz], [nx, ny, nz])); + } + } + } + out +} + +/// A chain's dispatch of `grid` groups, `most` of them at once (`dispatch_slabs`). `used`: the +/// list (or one before it) has used `scratch`. pub(crate) unsafe fn record_dispatch_chain<'a>( - list: &ID3D12GraphicsCommandList, grid: [u32; 3], scratch: &ID3D12Resource, - pieces: impl IntoIterator, + list: &ID3D12GraphicsCommandList, grid: [u32; 3], most: u64, scratch: &ID3D12Resource, used: bool, + pieces: impl IntoIterator + Clone, ) { - let [x, y, z] = grid; list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); - for (i, piece) in pieces.into_iter().enumerate() { - if i != 0 { + for (slab, (origin, size)) in dispatch_slabs(grid, most).into_iter().enumerate() { + let ([x, y, z], [ox, oy, oz]) = (size, origin); + for (i, piece) in pieces.clone().into_iter().enumerate() { + if i != 0 || slab != 0 || used { list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); } - let constants = [x, y, z, i as u32]; - list.SetComputeRoot32BitConstants(7, 4, constants.as_ptr().cast(), 0); + let constants = [x, y, z, i as u32, ox, oy, oz, 0]; + list.SetComputeRoot32BitConstants(7, 8, constants.as_ptr().cast(), 0); list.SetPipelineState(piece); list.Dispatch(x, y, z); } - + } } pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[StaticSampler]) -> Result { @@ -1230,7 +1253,7 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], params.push(D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, Anonymous: D3D12_ROOT_PARAMETER1_0 { Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, RegisterSpace: 2, Num32BitValues: 4, + ShaderRegister: 0, RegisterSpace: 2, Num32BitValues: 8, } }, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); @@ -1258,6 +1281,34 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], } } +#[cfg(test)] +mod slab_tests { + use super::dispatch_slabs; + + #[test] + fn slabs_cover_a_dispatch_once_within_their_size() { + for grid in [[1, 1, 1], [2, 3, 2], [240, 135, 1], [65_535, 2, 1], [5, 1, 7]] { + for most in [0, 1, 3, 239, 240, 1000, u64::MAX] { + let slabs = dispatch_slabs(grid, most); + let groups = |s: [u32; 3]| s.into_iter().map(u64::from).product::(); + assert_eq!(slabs.iter().map(|s| groups(s.1)).sum::(), groups(grid), "{grid:?} {most}"); + assert!(slabs.iter().all(|s| groups(s.1) <= most.max(1)), "{grid:?} {most}"); + for (o, n) in &slabs { + assert!((0..3).all(|k| n[k] > 0 && o[k] + n[k] <= grid[k]), "{grid:?} {most}"); + } + let mut firsts: Vec<_> = slabs.iter().map(|s| s.0).collect(); + firsts.sort(); + firsts.dedup(); + assert_eq!(firsts.len(), slabs.len()); + // the first is the largest: the scratch is made for it + assert!(slabs.iter().all(|s| groups(s.1) <= groups(slabs[0].1))); + } + } + assert_eq!(dispatch_slabs([240, 135, 1], 1400).len(), 27, "five rows of 240 at once"); + assert!(dispatch_slabs([0, 4, 4], 8).is_empty()); + } +} + #[cfg(test)] mod shader_cache_tests { use super::*; diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index f43382b3b1..459c7021a8 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1623,6 +1623,14 @@ pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Re #[cfg(test)] pub(crate) fn dispatch_split( chain: &crate::gpu::dxil::kernel::DispatchChain, groups: [u32; 3], mem: &[u32], +) -> Result, String> { + dispatch_split_by(chain, groups, mem, u64::MAX) +} + +/// `dispatch_split`, at most `most` groups at once (`pso::dispatch_slabs`). +#[cfg(test)] +pub(crate) fn dispatch_split_by( + chain: &crate::gpu::dxil::kernel::DispatchChain, groups: [u32; 3], mem: &[u32], most: u64, ) -> Result, String> { let mut g = GPU.lock().unwrap(); let gpu = g.get_or_insert_with(init).as_mut().map_err(|e| e.clone())?; @@ -1635,7 +1643,7 @@ pub(crate) fn dispatch_split( }).map_err(e) }).collect::>()?; dispatch_with(&gpu.dev, &gpu.queue, &gpu.fence, &mut gpu.value, &pieces[0], &rs, groups, &[], mem, 1, false, - Some((&pieces, chain.dwords_per_group))).map(|(m,_)| m) + Some((&pieces, chain.dwords_per_group, most))).map(|(m,_)| m) } /// `dispatch` run `reps` times in one command list (a UAV barrier between them, memory not @@ -1679,7 +1687,7 @@ fn dispatch_with( mem: &[u32], reps: usize, timed: bool, - chain: Option<(&[ID3D12PipelineState], u32)>, + chain: Option<(&[ID3D12PipelineState], u32, u64)>, ) -> Result<(Vec, Vec), String> { let mut io = sgprs.to_vec(); io.resize(KERNEL_SGPRS, 0); @@ -1734,8 +1742,9 @@ fn dispatch_with( for k in 2..6 { list.SetComputeRootUnorderedAccessView(k, mem_buf.GetGPUVirtualAddress()); } - let scratch = chain.map(|(_, words)| { - let bytes = groups.iter().fold(4 * u64::from(words), |n, &g| n * u64::from(g)); + let scratch = chain.map(|(_, words, most)| { + let first = super::pso::dispatch_slabs(groups, most)[0].1; + let bytes = first.iter().fold(4 * u64::from(words), |n, &g| n * u64::from(g)); buffer(dev, bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, true) }).transpose()?; // `reps` dispatches, each between two timestamps when `timed` @@ -1756,8 +1765,8 @@ fn dispatch_with( if let Some((heap, _)) = &queries { list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k); } - if let (Some((pieces, _)), Some(scratch)) = (chain, &scratch) { - super::pso::record_dispatch_chain(&list, groups, scratch, pieces); + if let (Some((pieces, _, most)), Some(scratch)) = (chain, &scratch) { + super::pso::record_dispatch_chain(&list, groups, most, scratch, k > 0, pieces); } else { list.Dispatch(groups[0], groups[1], groups[2]); } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 081824a59e..9d506a5a40 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2263,6 +2263,7 @@ unsafe fn copy_scratch(list: *mut c_void, n: u64) -> Option<(usize, u64)> { } fn reset_copy_scratch(list: *mut c_void) { + real::dispatch_chain::list_reset(list as usize); if let Some(scratch) = COPY_SCRATCH.lock().unwrap().active.get_mut(&(list as usize)) { scratch.recorded = false; } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6621821f49..54d3543076 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -7,10 +7,26 @@ use std::sync::{Arc, LazyLock, OnceLock}; static PROGRAMS: AtomicU64 = AtomicU64::new(0); static PIECES: AtomicU64 = AtomicU64::new(0); static DISPATCHES: AtomicU64 = AtomicU64::new(0); +/// slabs dispatched (`pso::dispatch_slabs`) +static SLABS: AtomicU64 = AtomicU64::new(0); +/// scratch alive now, the most there was, and the most a dispatch would have needed at once (bytes) +static LIVE: AtomicU64 = AtomicU64::new(0); +static PEAK: AtomicU64 = AtomicU64::new(0); +static WANTED: AtomicU64 = AtomicU64::new(0); pub(crate) fn log_counts() { - crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued", - PROGRAMS.load(Ordering::Relaxed), PIECES.load(Ordering::Relaxed), DISPATCHES.load(Ordering::Relaxed)); + let mib = |a: &AtomicU64| a.load(Ordering::Relaxed) >> 20; + crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab)", + PROGRAMS.load(Ordering::Relaxed), PIECES.load(Ordering::Relaxed), DISPATCHES.load(Ordering::Relaxed), SLABS.load(Ordering::Relaxed), + mib(&LIVE), mib(&PEAK), mib(&WANTED)); +} + +/// The scratch a dispatch uses at once, `XCL_SPLIT_SCRATCH_MB` (256): more groups than fit run in +/// slabs. A retail title's split programs need 190 KB for each group (median), 3 GB for 960x540 +/// pixels in groups of 8x4. +fn scratch_budget() -> u64 { + static B: OnceLock = OnceLock::new(); + *B.get_or_init(|| std::env::var("XCL_SPLIT_SCRATCH_MB").ok().and_then(|v| v.trim().parse().ok()).filter(|&m| m > 0).unwrap_or(256u64).min(4096) << 20) } struct PipelineBuilder { @@ -93,13 +109,46 @@ pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result, first: ID3D12PipelineState, chain: Arc, } static RECORDINGS: LazyLock>>>> = LazyLock::new(Default::default); +/// list → the allocator it records on and the scratch its chains share: they are dispatched one +/// after another, with a barrier between them (the recordings keep it alive) +static SHARED: LazyLock)>>> = LazyLock::new(Default::default); + +/// `list` begins another recording, which the GPU may run beside the last one. +pub(in crate::hle::d3d12x) fn list_reset(list: usize) { + SHARED.lock().unwrap().remove(&list); +} + +/// A scratch of `bytes` for a chain recorded on `list` with `allocator`, and whether a chain +/// before it on the list used it. +unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, bytes: u64) -> Option<(Arc, bool)> { + let had = SHARED.lock().unwrap().get(&list).filter(|s| s.0 == allocator).and_then(|s| s.1.upgrade()); + if let Some(s) = had.filter(|s| s.bytes >= bytes) { + return Some((s, true)); + } + let s = Arc::new(Scratch { buffer: scratch_buffer(dev, bytes)?, bytes }); + let live = LIVE.fetch_add(bytes, Ordering::Relaxed) + bytes; + PEAK.fetch_max(live, Ordering::Relaxed); + SHARED.lock().unwrap().insert(list, (allocator, Arc::downgrade(&s))); + Some((s, false)) +} pub(in crate::hle::d3d12x) fn allocator_reset(allocator: usize) { let recordings = RECORDINGS.lock().unwrap().remove(&allocator); @@ -131,10 +180,14 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, let allocator = if super::super::alloc_pool::enabled() { super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) } else { allocator }; - let size = grid.into_iter().try_fold(u64::from(chain.words) * 4, |s, n| s.checked_mul(n as u64)); - let scratch = size.filter(|&n| n <= u32::MAX as u64 + 1 && allocator != 0 && list.GetType() != D3D12_COMMAND_LIST_TYPE_BUNDLE) - .and_then(|n| scratch_buffer(&chain.builder.device, n)); - let Some(scratch) = scratch else { + let group = u64::from(chain.words) * 4; + let most = (scratch_budget() / group).max(1); + let slabs = pso::dispatch_slabs(grid, most); + let first = slabs[0].1.into_iter().map(u64::from).product::(); + WANTED.fetch_max(grid.into_iter().fold(group, |s, n| s.saturating_mul(n as u64)), Ordering::Relaxed); + let scratch = (allocator != 0 && list.GetType() != D3D12_COMMAND_LIST_TYPE_BUNDLE) + .then(|| scratch_for(&chain.builder.device, list.as_raw() as usize, allocator, first * group)).flatten(); + let Some((scratch, used)) = scratch else { list.SetPipelineState(&chain.whole()?); list.Dispatch(x, y, z); return Ok(()); @@ -143,6 +196,7 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, let held = Arc::new(Recording { scratch, first, chain }); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); DISPATCHES.fetch_add(1, Ordering::Relaxed); - pso::record_dispatch_chain(list, grid, &held.scratch, std::iter::once(&held.first).chain(&held.chain.tail)); + SLABS.fetch_add(slabs.len() as u64, Ordering::Relaxed); + pso::record_dispatch_chain(list, grid, most, &held.scratch.buffer, used, std::iter::once(&held.first).chain(&held.chain.tail)); Ok(()) } From 6ec402b16a2d5ce076361a1fb6d01cfa7e15370b Mon Sep 17 00:00:00 2001 From: MadaraXor Date: Wed, 25 Nov 2026 12:53:02 +0100 Subject: [PATCH 015/258] Recompiler: v_readfirstlane in a pixel shader reads a live lane first In a pixel shader EXEC holds helper lanes (s_wqm), and on a primitive's edge the first lane of EXEC is often one. v_readfirstlane read that lane. An RDNA2 driver (RX 6700 XT, 32.0.21045) gives 0 for everything a helper lane holds once a WaveReadLaneAt ran inside a loop, quad reads included. A loop whose state the console's compiler carries in a vector register (v_mov v, s ... v_readfirstlane s, v) then read 0 back on each pass and ran to the loop budget: a retail title's volumetric light pass took seconds per draw at its world start and Windows reset the GPU (#675). v_readfirstlane now reads the first lane of EXEC that is live (ballot(true), per half in the wave32-in-64 form) when EXEC has one, and the first lane of EXEC as before when it has none. The value is the same: the console's compiler reads the first lane of a value equal in every lane, or of a lane it then removes from EXEC (a waterfall loop). The new GPU test draws that title's list-loop shape on two triangles sharing a diagonal. Without the change, on the RX 6700 XT, 69 of 1024 pixels run the loop 65 536 times (the budget) with wrong results; with it, none, and at most 16 passes. Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/emit.rs | 19 +++++- crates/xcl/src/gpu/recomp/tests.rs | 106 +++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 069c8b3f6f..839b89bfd0 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3994,7 +3994,8 @@ impl Em { let eh = if self.opt.wave64 { eh } else { "0u".into() }; let t = self.t(); let rla = self.rla_uniform_fn(); - self.line(&format!("uint {t} = {rla}({a}, first_lane({el}, {eh}));")); + // (a live lane of EXEC where there is one: `first_lane_live`) + self.line(&format!("uint {t} = {rla}({a}, first_lane_live({el}, {eh}));")); self.write32(&dst, &t); return Ok(()); } @@ -6226,6 +6227,22 @@ float3 cube_dir(float s, float t, float face) { // the cube of a cube array the face coordinate (face + 8 · slice) is in float cube_slice(float face) { return (float)(((uint)round(face)) / 8u); } uint first_lane(uint lo, uint hi) { return select(lo != 0u, firstbitlow(lo), select(hi != 0u, 32u + firstbitlow(hi), 0u)); } +// The lane a v_readfirstlane reads. In a pixel shader EXEC holds helper lanes (s_wqm) and its +// first lane is often one, on a primitive's edge. A helper lane's registers cannot be read once +// a loop has run a wave op: AMD's RDNA2 driver (RX 6700 XT) gives 0 for everything a helper +// lane holds after a WaveReadLaneAt inside a loop, quad reads included. A loop whose state the +// console's compiler carries in a vector (v_mov v, s … v_readfirstlane s, v) then read 0 back +// each time round and ran to the loop budget: a retail volumetric light pass took seconds a draw +// and the GPU was reset. So the first live lane of EXEC is read if EXEC has one. The value +// is the same there: the console's compiler reads the first lane of values that are equal in +// every lane, or of any lane it then removes from EXEC (a waterfall loop). +uint first_lane_live(uint lo, uint hi) { +#ifdef XCL_PIXEL + uint2 lv = ballot(true); + if (((lo & lv.x) | (hi & lv.y)) != 0u) { lo &= lv.x; hi &= lv.y; } +#endif + return first_lane(lo, hi); +} uint lanemask_lt_lo() { return lane_id >= 32u ? 0xFFFFFFFFu : (lane_id == 0u ? 0u : (0xFFFFFFFFu >> (32u - lane_id))); } uint lanemask_lt_hi() { return lane_id <= 32u ? 0u : (0xFFFFFFFFu >> (64u - lane_id)); } uint wqm(uint m) { uint q = m | (m >> 1); q = q | (q >> 2); q &= 0x11111111u; return q * 15u; } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 8aa9aa1c01..47b623f849 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -9325,3 +9325,109 @@ fn gpu_image_get_resinfo_past_last_level() { } assert!(bad.is_empty(), "resinfo past the last level:\n{}", bad.join("\n")); } + +/// The list loop of a retail volumetric light PS – a wave32 program under `s_wqm`: per-lane +/// mask words OR-reduced over the wave (`s_or_saveexec -1`, dpp8 x3, dpp, +/// permlanex16, `v_readlane 0`), then a bit loop whose state is written back per lane (`v_mov`) +/// and read with `v_readfirstlane`: `s_ff1`, `1 << (n & 31)`, xor, `s_cmp_eq` / `s_cbranch_scc0`. +/// Exports (iterations, the wave's OR, the pixel's own word, 1). +fn list_loop_ps() -> super::Translation { + use super::PsInterface; + let raw = |b: &[u8]| b.to_vec(); + let head = [ + ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 126)], None), + ins("S_WQM_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None), + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 5), ("SRC0", V + 2)], None), + ins("V_CVT_U32_F32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 3)], None), + ins("V_AND_B32", "ENC_VOP2", &[("VDST", 5), ("SRC0", 135), ("VSRC1", 5)], None), + ins("V_AND_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 135), ("VSRC1", 6)], None), + ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 6), ("SRC0", 136), ("VSRC1", 6)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", 129)], None), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 5), ("VSRC1", 11)], None), + ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 6), ("VSRC1", 11)], None), + ins("V_OR_B32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 7), ("VSRC1", 4)], None), + // the console's wave OR of v4 over the live lanes, into s3 + ins("S_OR_SAVEEXEC_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 193)], None), + ins("S_AND_B32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 20), ("SSRC1", 1)], None), + ins("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 0), ("SRC0", 128), ("SRC1", V + 4), ("SRC2", 3)], None), + raw(&[0xe9, 0x00, 0x00, 0x38, 0x00, 0xc1, 0x54, 0xde]), // v_or_b32_dpp8 v0, v0, v0 + raw(&[0xe9, 0x00, 0x00, 0x38, 0x00, 0x12, 0x60, 0x93]), + raw(&[0xe9, 0x00, 0x00, 0x38, 0x00, 0x24, 0x09, 0x00]), + raw(&[0xfa, 0x00, 0x00, 0x38, 0x00, 0x40, 0x09, 0xff]), // v_or_b32_dpp v0, v0, v0 + raw(&[0x01, 0x00, 0x78, 0xd7, 0x00, 0x01, 0x01, 0x02]), // v_permlanex16_b32 v1, v0, 0, 0 + raw(&[0x01, 0x01, 0x00, 0x38]), // v_or_b32 v0, v1, v0 + raw(&[0x03, 0x00, 0x60, 0xd7, 0x00, 0x01, 0x01, 0x00]), // v_readlane_b32 s3, v0, 0 + raw(&[0x01, 0x03, 0xfe, 0xbe]), // s_mov_b32 exec_lo, s1 + ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 8), ("SSRC0", 128)], None), + ins("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 3), ("SSRC1", 128)], None), + ] + .concat(); + let body = [ + ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", V + 8)], None), + ins("S_FF1_I32_B32", "ENC_SOP1", &[("SDST", 5), ("SSRC0", 4)], None), + ins("S_AND_B32", "ENC_SOP2", &[("SDST", 12), ("SSRC0", 5), ("SSRC1", 159)], None), + ins("S_LSHL_B32", "ENC_SOP2", &[("SDST", 5), ("SSRC0", 129), ("SSRC1", 12)], None), + ins("S_XOR_B32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 5), ("SSRC1", 4)], None), + ins("S_ADD_U32", "ENC_SOP2", &[("SDST", 8), ("SSRC0", 8), ("SSRC1", 129)], None), + ins("S_CMP_EQ_U32", "ENC_SOPC", &[("SSRC0", 4), ("SSRC1", 5)], None), + ] + .concat(); + let tail = [ + ins("S_MOV_B32", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 20)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 8)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 12), ("SRC0", 3)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 12), ("SRC0", V + 12)], None), + ins("V_CVT_F32_U32", "ENC_VOP1", &[("VDST", 13), ("SRC0", V + 4)], None), + ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", 242)], None), + ins("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 10), ("VSRC1", 12), ("VSRC2", 13), ("VSRC3", 11), ("DONE", 1), ("VM", 1)], None), + ] + .concat(); + // head; scc1 → tail; v8 = s3; branch over the write-back; L: v8 = s1; body; scc0 → L; tail + let mut code = head; + let skip_all = (4 + 4 + 4 + body.len() + 4) / 4; // v_mov, s_branch, v_mov, body, s_cbranch + code.extend(ins("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", skip_all as u64)], None)); + code.extend(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 3)], None)); + code.extend(ins("S_BRANCH", "ENC_SOPP", &[("SIMM16", 1)], None)); + code.extend(ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 1)], None)); + code.extend(&body); + let back = (-((4 + body.len() as i64 + 4) / 4)) as u16 as u64; + code.extend(ins("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", back)], None)); + code.extend(tail); + code.extend(ins("S_ENDPGM", "ENC_SOPP", &[], None)); + let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None }; + translate(&code, &Options { mode: Mode::Pixel(psi), wave64: false, ..Default::default() }).unwrap() +} + +/// `list_loop_ps` drawn on two triangles sharing a diagonal: every pixel's bit loop runs +/// popcount(wave OR) times (at most 16), never to the loop budget. The waves on the diagonal start +/// with helper lanes; `v_readfirstlane` read the first of them, whose registers an RDNA2 driver +/// gives as 0 once a wave op ran in the loop, and the loop never saw its state change. +#[test] +fn gpu_ps_readfirstlane_loop_on_a_primitive_edge_ends() { + if !gpu_ready() { + return; + } + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + let vs = super::dxc::compile("float4 main(float2 p : POSITION) : SV_Position { return float4(p, 0.5, 1.0); }\n", "main", "vs_6_6", &[]).unwrap(); + let pt = list_loop_ps(); + assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); + // the fourth channel: the hardware wave's lane count + let hlsl = pt.hlsl.replacen(" if (!xcl_live) discard;", " xo.t0[3] = (float)WaveGetLaneCount();\n if (!xcl_live) discard;", 1); + let ps = super::dxc::compile(&hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{hlsl}")); + let quad = [-1.0f32, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0]; + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let size = 32usize; + let px = runner::draw(&vs, &ps, &layout, &quad, 8, &[], &[], size as u32, [9.0; 4]).unwrap(); + let lanes: std::collections::BTreeSet = px.iter().map(|p| p[3] as u32).collect(); + let bad: Vec<(usize, usize, [f32; 4])> = (0..size * size) + .filter(|&i| { + let p = px[i]; + let (it, or, own) = (p[0] as u32, p[1] as u32, p[2] as u32); + own.count_ones() != 2 || or & own != own || it != or.count_ones() || it > 16 + }) + .map(|i| (i % size, i / size, px[i])) + .collect(); + let max_it = px.iter().map(|p| p[0] as u32).max().unwrap_or(0); + println!("{:?}: lane counts {lanes:?}; most iterations {max_it}; {} of {} pixels wrong, first {:?}", runner::adapter(), bad.len(), size * size, bad.iter().take(8).collect::>()); + assert!(bad.is_empty(), "{} pixels wrong (iterations, wave OR, own word, lane count), first {:?}", bad.len(), &bad[..bad.len().min(8)]); +} From 6e906b7da882a47f4e11924eac680c150dcad56e Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 15:39:31 +0100 Subject: [PATCH 016/258] local: loop budget experiment --- crates/xcl/src/gpu/recomp/dxc.rs | 10 + crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 273 +++++++++++++++++++ 2 files changed, 283 insertions(+) create mode 100644 crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index ec63906c58..243a289b68 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -918,6 +918,16 @@ pub fn in_cached_only() -> bool { } pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, bool), String> { + // LOCAL EXPERIMENT: XCL_LOOP_FOR= XCL_LOOP_N=: the loop budget of that program alone + let patched; + let src = match (std::env::var("XCL_LOOP_FOR"), std::env::var("XCL_LOOP_N")) { + (Ok(t), Ok(n)) if !t.is_empty() && src.contains(&t) => { + patched = src.replacen("static uint xcl_budget = 1u << 16;", &format!("static uint xcl_budget = {n}u;"), 1); + crate::xlog_info!("[SHADER] loop budget {n} for a program of {} B HLSL ({entry}, {profile})", src.len()); + &patched[..] + } + _ => src, + }; compile_cached_in(&cache_dir(), src, entry, profile) } diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs new file mode 100644 index 0000000000..012e002491 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -0,0 +1,273 @@ +//! Buffers in a GPU view of the title's memory, readable by shaders (`XCL_GPU_VIEW_BUFFERS=1`). +//! +//! A title reserves 64 KiB pages twice, once for the CPU and once with no CPU access (`kernelx:: +//! mirrors`), and gives the GPU addresses of the second. Those lie outside the memory windows, so +//! a shader reads zeros at them: a retail title's culling reads its object lists, and its mesh +//! shaders their geometry, from there (#697). +//! +//! The tiles a buffer view covers are mapped in free address space of a sparse window (video +//! memory only: nothing is committed for the CPU) and hold what the title's pages hold: their +//! bytes go up when the view is made and again when the title writes them. The view's address is +//! replaced by the window's. Only what is read is mirrored: a write through it is lost, so UAVs +//! keep their address. + +use std::collections::HashMap; + +use super::*; + +/// The window space a chunk of the title's view takes. Views inside one chunk share it; a view +/// across chunks gets a space of its own (its bytes have to be contiguous). +const EXTENT: usize = 1 << 20; +/// Views longer than this keep their address. +const MOST: usize = 64 << 20; + +pub fn on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GPU_VIEW_BUFFERS").is_ok_and(|v| v.trim() == "1")) +} + +/// `XCL_GPU_VIEW_MB` (512): the video memory the mirrors may take. +fn budget() -> usize { + static B: std::sync::OnceLock = std::sync::OnceLock::new(); + *B.get_or_init(|| std::env::var("XCL_GPU_VIEW_MB").ok().and_then(|v| v.trim().parse().ok()).filter(|&m| m > 0).unwrap_or(512usize) << 20) +} + +#[derive(Default)] +pub(super) struct Mirrors { + /// (first byte of the title's chunks, chunks) → the window space of them + extents: HashMap<(usize, usize), usize>, + /// window tile → title tile (an address in the GPU view) + title_of: FxHashMap, + /// where the bytes of a title tile are read from (its own address, or the CPU view's) + read: FxHashMap, + /// read tile → window tiles whose bytes are there + by_read: FxHashMap>, + /// window tiles none of whose bytes have gone up yet (or whose pages changed place) + fresh: Vec, + /// the next title tile the slow check looks at + turn: usize, + /// GPU-view mappings seen (`kernelx::gpu_view_map_gen`) + gen: u64, +} + +static MIRRORS: Mutex> = Mutex::new(None); + +impl Mirrors { + /// Title tile `title` is shown at window tile `win`, its bytes read from `read`. + pub(super) fn show(&mut self, win: usize, title: usize, read: usize) { + self.title_of.insert(win, title); + self.read.insert(title, read); + self.by_read.entry(read).or_default().push(win); + self.fresh.push(win); + } + + fn set_read(&mut self, title: usize, read: usize) { + let old = self.read.insert(title, read); + if old == Some(read) { + return; + } + let wins: Vec = self.title_of.iter().filter(|&(_, &t)| t == title).map(|(&w, _)| w).collect(); + if let Some(o) = old.and_then(|o| self.by_read.get_mut(&o)) { + o.retain(|w| !wins.contains(w)); + } + self.by_read.entry(read).or_default().extend(&wins); + self.fresh.extend(wins); + } + + /// The window tiles and pages a set of written pages (`dirty`, title or CPU addresses) is + /// shown at: (window page, the read address of its bytes). + pub(super) fn shown_at(&self, dirty: &[usize]) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + for &d in dirty { + let tile = d & !(TILE - 1); + for &w in self.by_read.get(&tile).map(Vec::as_slice).unwrap_or(&[]) { + out.push((w + (d - tile), d)); + } + } + out + } + + pub(super) fn tiles(&self) -> usize { + self.title_of.len() + } +} + +/// Copies `n` bytes from the title's memory at `at`; false when the page went away (nothing read). +unsafe fn read_title(at: usize, out: *mut u8, n: usize) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + let mut got = 0usize; + ReadProcessMemory(windows_sys::Win32::System::Threading::GetCurrentProcess(), at as *const c_void, out as *mut c_void, n, &mut got) != 0 && got == n +} + +impl State { + /// Brings the mirrored tiles in step with the title's memory: whole tiles that are new, and + /// the pages the title wrote (`dirty`). Before the title's lists; `m` is held by the caller. + pub(super) unsafe fn mirror_up(&mut self, m: &mut Mirrors, dirty: &[usize]) -> usize { + let mut pages: Vec<(usize, usize)> = m.shown_at(dirty); + for win in std::mem::take(&mut m.fresh) { + let Some(&title) = m.title_of.get(&win) else { continue }; + let read = m.read[&title]; + pages.extend((0..PAGES_PER_TILE).map(|i| (win + i * PAGE, read + i * PAGE))); + } + pages.sort_unstable(); + pages.dedup(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + let mut from: FxHashMap = FxHashMap::default(); + let mut bytes = [0u8; PAGE]; + for (win, read) in pages { + let tile = win & !(TILE - 1); + let Some(entry) = self.mapped.get_mut(&tile) else { continue }; + if !read_title(read, bytes.as_mut_ptr(), PAGE) { + continue; + } + let i = (win - tile) / PAGE; + entry.holes &= !(1u16 << i); + scan_page(&bytes, win, &mut entry.sent[i], &mut runs); + from.insert(win, read); + } + let n = runs.iter().map(|r| r.1).sum(); + // (the title tile a run lies in never changes within it: a run is at most a page here, but + // `push_run` joins neighbours, and two neighbouring pages may come from two places) + let split: Vec<(usize, usize)> = runs.iter().flat_map(|&(a, l)| { + let mut out = Vec::new(); + let (mut a, end) = (a, a + l); + while a < end { + let e = ((a & !(PAGE - 1)) + PAGE).min(end); + out.push((a, e - a)); + a = e; + } + out + }).collect(); + self.upload_runs(&split, &|dst, p, len| { + let page = dst & !(PAGE - 1); + from.get(&page).is_some_and(|r| read_title(r + (dst - page), p, len)) + }); + n + } +} + +/// The address a view of `len` bytes at `va` gets when it lies in a GPU view of the title's and +/// in no memory window: where the same bytes can be read by a shader. None: it keeps `va`. +pub fn base_for(va: usize, len: usize) -> Option { + if !on() || len == 0 || len > MOST { + return None; + } + let u = crate::gpu::uma::get()?; + if u.contains(va) || !u.has_sparse() { + return None; + } + let last = va.checked_add(len)?.checked_sub(1)?; + crate::hle::kernelx::mirrors::source(va)?; + crate::hle::kernelx::mirrors::source(last)?; + let (t0, t1) = (va & !(TILE - 1), (last & !(TILE - 1)) + TILE); + let first = t0 & !(EXTENT - 1); + let n = (t1 - first).div_ceil(EXTENT); + let known = MIRRORS.lock().unwrap().get_or_insert_with(Mirrors::default).extents.get(&(first, n)).copied(); + let win = match known { + Some(w) => w, + None => { + let (w, _) = u.sparse_alloc(n * EXTENT, EXTENT)?; + *MIRRORS.lock().unwrap().get_or_insert_with(Mirrors::default).extents.entry((first, n)).or_insert(w) + } + }; + // (held: STATE, then MIRRORS, as in `sync`) + let mut g = lock_state(); + let s = g.as_mut()?; + let mut mg = MIRRORS.lock().unwrap(); + let m = mg.get_or_insert_with(Mirrors::default); + let new: Vec = (t0..t1).step_by(TILE).filter(|t| !m.title_of.contains_key(&(win + (t - first)))).collect(); + if !new.is_empty() { + if m.tiles() + new.len() > budget() / TILE { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| crate::xlog_warn!("D3D12.X: the buffers of the GPU view take more than XCL_GPU_VIEW_MB: the rest keeps its address")); + return None; + } + // whole runs of new tiles at once (a mapping call and a signal for each run) + let mut i = 0; + while i < new.len() { + let mut j = i + 1; + while j < new.len() && new[j] == new[j - 1] + TILE { + j += 1; + } + let (a, b) = (new[i], win + (new[i] - first)); + s.ensure_mapped(b, (j - i) * TILE, |w| unsafe { query_tile_holes(super::super::title_textures::mirror_source(a + (w - b))) }); + for &t in &new[i..j] { + let w = win + (t - first); + if s.mapped.contains_key(&w) { + m.show(w, t, super::super::title_textures::mirror_source(t) & !(TILE - 1)); + } + } + i = j; + } + static N: AtomicU64 = AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() { + crate::xlog_info!("D3D12.X: buffers of the GPU view: {} tiles mirrored ({} MB), latest view {va:#x} ({len} B)", m.tiles(), (m.tiles() * TILE) >> 20); + } + } + if (t0..t1).step_by(TILE).any(|t| !m.title_of.contains_key(&(win + (t - first)))) { + return None; + } + Some(win + (va - first)) +} + +/// The pages of the CPU (and pool) side whose writes have to be seen: for the write watch. +pub fn sources() -> Vec<(usize, usize)> { + MIRRORS.lock().unwrap().as_ref().map_or(Vec::new(), |m| m.by_read.keys().map(|&r| (r, r + TILE)).collect()) +} + +/// `State::mirror_up` for a submit (`before_execute`; `s` is the locked state). A page the title +/// mapped elsewhere or now has no mapping at all is looked at again when the mappings of a GPU +/// view change, and a few tiles in turn otherwise. +pub(super) unsafe fn sync(s: &mut State, dirty: &[usize]) { + let mut g = MIRRORS.lock().unwrap(); + let Some(m) = g.as_mut().filter(|m| m.tiles() != 0) else { return }; + let gen = crate::hle::kernelx::gpu_view_map_gen(); + let titles: Vec = m.read.keys().copied().collect(); + let look: Vec = if std::mem::replace(&mut m.gen, gen) != gen { + titles + } else { + let n = titles.len().max(1); + (0..8.min(titles.len())).map(|i| titles[(m.turn + i) % n]).collect() + }; + m.turn = m.turn.wrapping_add(8); + for t in look { + let r = super::super::title_textures::mirror_source(t) & !(TILE - 1); + m.set_read(t, r); + } + let n = s.mirror_up(m, dirty); + static SENT: AtomicU64 = AtomicU64::new(0); + static CALLS: AtomicU64 = AtomicU64::new(0); + let total = SENT.fetch_add(n as u64, Ordering::Relaxed) + n as u64; + let k = CALLS.fetch_add(1, Ordering::Relaxed) + 1; + if k.is_power_of_two() && k >= 64 { + crate::xlog_info!("D3D12.X: buffers of the GPU view: {} tiles, {} MB sent in {k} submits", m.tiles(), total >> 20); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_written_page_is_shown_at_every_window_tile_it_is_read_for() { + let mut m = Mirrors::default(); + m.show(0x10_0000, 0xAA_0000, 0xAA_0000); + m.show(0x20_0000, 0xAA_0000, 0xAA_0000); + m.show(0x30_0000, 0xBB_0000, 0xCC_0000); + assert_eq!(m.tiles(), 3); + let mut a = m.shown_at(&[0xAA_3000]); + a.sort(); + assert_eq!(a, vec![(0x10_3000, 0xAA_3000), (0x20_3000, 0xAA_3000)]); + assert_eq!(m.shown_at(&[0xCC_1000]), vec![(0x30_1000, 0xCC_1000)], "by the read address, not the title's"); + assert!(m.shown_at(&[0xBB_1000]).is_empty()); + m.fresh.clear(); + // the page behind a title tile moved: its window tiles are sent whole again + m.set_read(0xBB_0000, 0xDD_0000); + assert_eq!(m.fresh, vec![0x30_0000]); + assert!(m.shown_at(&[0xCC_1000]).is_empty()); + assert_eq!(m.shown_at(&[0xDD_2000]), vec![(0x30_2000, 0xDD_2000)]); + m.set_read(0xBB_0000, 0xDD_0000); + assert_eq!(m.fresh, vec![0x30_0000], "the same place again is nothing new"); + } +} From 9c09d8efdd92f56c99cee4d72277c63f4f790864 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 15:40:54 +0100 Subject: [PATCH 017/258] local: buffers of the GPU view (XCL_GPU_VIEW_BUFFERS) --- crates/xcl/src/hle/d3d12x/bind.rs | 14 +++ crates/xcl/src/hle/d3d12x/real.rs | 25 +++-- crates/xcl/src/hle/d3d12x/sparse.rs | 19 +++- crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 102 ++++++++++++++++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 3 +- 5 files changed, 154 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8041ff06d5..10234d4145 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -269,9 +269,22 @@ pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_vo /// #40 / #42) pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_void, i: u32, va: u64) { note_address(va); + let va = readable_root(va); put_in(this, true, i, 0, &va.to_le_bytes()); } +/// The address a root descriptor at `va` gets (`sparse::gpu_view`): a root descriptor has no +/// size, so as much of the tile is taken as lies in the view. A read through it is in step with +/// the title's memory, a write is not (a root UAV in a GPU view stays what it was before). +fn readable_root(va: u64) -> u64 { + for len in [0x1_0000usize, 0x1000] { + if let Some(b) = super::sparse::gpu_view::base_for(va as usize, len) { + return b as u64; + } + } + va +} + /// `XCL_TRACE_ADDRESSES=1`: root descriptor addresses of console code – in unified memory /// (translated shaders see them) or not – counted and logged fn note_address(va: u64) { @@ -1362,6 +1375,7 @@ pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_voi /// #39 / #41): the 64-bit GPU address pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) { note_address(va); + let va = readable_root(va); put(this, i, 0, &va.to_le_bytes()); } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 267329acfe..94f942f1f0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1930,10 +1930,15 @@ unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12 }; let (va, size) = desc.as_ref().map_or((0, 0), |d| (d.BufferLocation, d.SizeInBytes)); let in_uma = crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); - if !in_uma { + let mirrored = if in_uma { None } else { super::sparse::gpu_view::base_for(va as usize, size as usize) }; + if !in_uma && mirrored.is_none() { note_buffer_view(); } - let (va, size) = if in_uma { (va, size) } else { (0, 0) }; + let (va, size) = match mirrored { + Some(b) => (b as u64, size), + None if in_uma => (va, size), + None => (0, 0), + }; super::console_heap::write(&slot, &crate::gpu::desc::cbv_words(va, size)); } @@ -2382,7 +2387,7 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let Some(slot) = super::console_heap::slot(cpu) else { return }; let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true); return super::console_heap::write(&slot, &words); } dev_create_srv_x(this, resource_at(this, rdesc, va), &v, cpu); @@ -2400,14 +2405,15 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let Some(slot) = super::console_heap::slot(cpu) else { return }; let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; - let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); + let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, false); return super::console_heap::write(&slot, &words); } dev_create_uav_x(this, resource_at(this, rdesc, va), std::ptr::null_mut(), &v, cpu); } /// V# of `n` elements from element `first` of the buffer at `va`. -fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> [u32; 4] { +/// (`read_only`: a view of a GPU view may get a readable address, `sparse::gpu_view`) +fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool, read_only: bool) -> [u32; 4] { let fmt = crate::gpu::desc::gfx10_format(format).unwrap_or(22); let (stride, elem) = match (raw, stride) { (true, _) => (0, 4), @@ -2418,7 +2424,14 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI (false, s) => (s, s), }; let records = if stride == 0 { n.saturating_mul(4) } else { n }; - crate::gpu::desc::buffer_words(va + first * elem as u64, stride, records, fmt) + let mut base = va + first * elem as u64; + if read_only { + let len = (n as u64).saturating_mul(elem as u64); + if let Some(b) = super::sparse::gpu_view::base_for(base as usize, len as usize) { + base = b as u64; + } + } + crate::gpu::desc::buffer_words(base, stride, records, fmt) } fn resolve_uav_array_size(array_size: u32, total_slices: u32, first_slice: u32) -> u32 { diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 91eb2ba351..6baf6b1d78 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -31,6 +31,8 @@ use windows_sys::Win32::System::Memory::{ PAGE_NOACCESS, PAGE_READWRITE, }; +pub mod gpu_view; + const TILE: usize = 0x1_0000; /// tiles of a video-memory pool heap (64 MiB) const POOL_TILES: u32 = 1024; @@ -1122,6 +1124,15 @@ impl State { /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via /// the 64 MiB ring staging buffer (zero CPU stall on the common path). unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) { + self.upload_runs(runs, &|at, p, n| { + std::ptr::copy_nonoverlapping(at as *const u8, p, n); + true + }); + } + + /// Copies `runs` (address in a window, bytes) into video memory; `read(address, to, bytes)` + /// gives their bytes (false: the run's piece is left as it is). + unsafe fn upload_runs(&mut self, runs: &[(usize, usize)], read: &dyn Fn(usize, *mut u8, usize) -> bool) { if runs.is_empty() { return; } @@ -1168,7 +1179,10 @@ impl State { } }; let dst_off = (aligned as usize) % STAGING; - std::ptr::copy_nonoverlapping(cur as *const u8, p.add(dst_off), chunk); + if !read(cur, p.add(dst_off), chunk) { + done += chunk; + continue; + } let staging_res = &self.staging.as_ref().unwrap().0; self.slots[slot_idx].list.CopyBufferRegion(&self.windows[wi].1, (cur - b) as u64, staging_res, dst_off as u64, chunk as u64); self.ring_write = aligned + chunk as u64; @@ -1511,6 +1525,9 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: if !dirty_runs.is_empty() { s.upload_dirty(&dirty_runs); } + if gpu_view::on() { + gpu_view::sync(s, dirty); + } PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); { static CALLS: AtomicU64 = AtomicU64::new(0); diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs index 012e002491..0f410f060e 100644 --- a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -190,7 +190,8 @@ pub fn base_for(va: usize, len: usize) -> Option { j += 1; } let (a, b) = (new[i], win + (new[i] - first)); - s.ensure_mapped(b, (j - i) * TILE, |w| unsafe { query_tile_holes(super::super::title_textures::mirror_source(a + (w - b))) }); + // SAFETY: the tiles are address space of a window, with no CPU memory behind them + unsafe { s.ensure_mapped(b, (j - i) * TILE, |w| query_tile_holes(super::super::title_textures::mirror_source(a + (w - b)))) }; for &t in &new[i..j] { let w = win + (t - first); if s.mapped.contains_key(&w) { @@ -270,4 +271,103 @@ mod tests { m.set_read(0xBB_0000, 0xDD_0000); assert_eq!(m.fresh, vec![0x30_0000], "the same place again is nothing new"); } + + /// The bytes of the title's pages reach the window tiles mapped for them, and again when the + /// title writes a page; a page that went away is left as it is. + #[test] + fn gpu_the_titles_bytes_reach_the_window_tiles_shown_for_them() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); + D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); + } + let dev = dev.expect("D3D12 device"); + let window = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + let source = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert!(window % TILE == 0 && source % TILE == 0); + for i in 0..TILE / 4 { + *((source + 4 * i) as *mut u32) = i as u32 * 7 + 1; + } + let mut reserved: Option = None; + dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved).expect("reserved buffer"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("list"); + rb_list.Close().expect("close"); + let mut slots = Vec::new(); + for _ in 0..UPLOAD_SLOTS { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list"); + list.Close().expect("close"); + slots.push(UploadSlot { alloc, list, fence_val: 0 }); + } + let mut s = State { + dev, + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + windows: vec![(window, reserved.expect("reserved buffer"))], + pools: Vec::new(), + free: Vec::new(), + retired: Vec::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: Vec::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + zero_buf: None, + slots, + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: None, + scratch_runs: Vec::new(), + }; + let mut m = Mirrors::default(); + s.ensure_mapped(window, TILE, |_| query_tile_holes(source)); + m.show(window, 0x7FFF_0000, source); + let at = |i: usize| *((window + 4 * i) as *const u32); + let shown = |s: &mut State, m: &mut Mirrors, dirty: &[usize]| { + s.mirror_up(m, dirty); + s.readback_ranges(&[(window, TILE)]); + }; + shown(&mut s, &mut m, &[]); + assert!((0..TILE / 4).all(|i| at(i) == i as u32 * 7 + 1), "the whole tile at first"); + // a page the title wrote (and one it did not) + *((source + 0x3010) as *mut u32) = 0xDEAD_BEEF; + shown(&mut s, &mut m, &[source + 0x3000]); + assert_eq!((at(0x3010 / 4), at(0x3014 / 4)), (0xDEAD_BEEF, (0x3014 / 4) as u32 * 7 + 1)); + // not reported as written: not sent + *((source + 0x4010) as *mut u32) = 0x1234_5678; + shown(&mut s, &mut m, &[]); + assert_eq!(at(0x4010 / 4), (0x4010 / 4) as u32 * 7 + 1); + // the page is gone: what the GPU has stays, and nothing faults + assert_ne!(VirtualFree(source as *mut c_void, 0, MEM_RELEASE), 0); + m.fresh.push(window); + shown(&mut s, &mut m, &[source + 0x5000]); + assert_eq!(at(0x3010 / 4), 0xDEAD_BEEF); + s.wait_for(s.value); + drop(s); + VirtualFree(window as *mut c_void, 0, MEM_RELEASE); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index f6f90acd3e..5a060173af 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -406,7 +406,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, /// Where a texture at `va` is read from: the CPU view behind a GPU view (`kernelx::mirrors`) /// when nothing is mapped at `va` itself, else `va`. A physical page mapped at `va` counts /// before its first use too, while it is still reserved memory (`kernelx::physical_page_at`). -fn mirror_source(va: usize) -> usize { +pub(super) fn mirror_source(va: usize) -> usize { let Some(src) = crate::hle::kernelx::mirrors::source(va) else { return va }; if crate::hle::kernelx::physical_page_at(va) { return va; @@ -666,6 +666,7 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { regions.extend(crate::hle::kernelx::graphics_reservations()); let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().by_res.values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); wanted.extend(super::sparse::mapped_ranges()); + wanted.extend(super::sparse::gpu_view::sources()); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); computed From 89d9f35605b2eb92b59ea62c7ed9a358e79944bf Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 15:46:37 +0100 Subject: [PATCH 018/258] local: title_bytes reads alias spaces safely --- crates/xcl/src/hle/d3d12x/title_textures.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 5a060173af..db13b7dab6 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1423,7 +1423,9 @@ unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> V /// The title's bytes at `at`: where they are when all of them are readable (a copy first cost /// as much as the detile of a video frame), else read page run by page run. unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> { - if crate::gpu::shader::readable(at, len) { + // (in a space of physical pages the title maps and unmaps them all the time, so a page can go + // away between the check and the read: `read_committed` copies without faulting) + if !crate::hle::kernelx::alias::in_space(at) && crate::gpu::shader::readable(at, len) { std::borrow::Cow::Borrowed(std::slice::from_raw_parts(at as *const u8, len)) } else { std::borrow::Cow::Owned(read_committed(at, len)) From d1fc32e66eb104e1a8073a1398b6c8147c0c5f9b Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 15:56:27 +0100 Subject: [PATCH 019/258] Recompiler: whole-wave reductions of wave32 VS / PS count every live lane --- crates/xcl/src/gpu/recomp/emit.rs | 52 +++++++++++++++++++++ crates/xcl/src/gpu/recomp/mod.rs | 77 +++++++++++++++++++++++++++++++ 2 files changed, 129 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 839b89bfd0..1bd2fa475a 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -17,6 +17,8 @@ pub(super) enum Flow { } pub(super) struct Em { + /// whole-wave reductions (`wave32_reductions`) + pub reductions: super::Reductions, opt: Options, out: String, pub indent: usize, @@ -592,6 +594,7 @@ impl Em { pub fn new(opt: Options) -> Self { Em { opt, + reductions: Default::default(), out: String::new(), indent: 1, sgprs: BTreeSet::new(), @@ -1266,6 +1269,7 @@ impl Em { *self.ignored.entry(name).or_default() += 1; return Flow::Next; } + let seed = self.reductions.seeds.get(&d.pc).copied(); let r = match d.enc.name { "ENC_SOPP" => return self.sopp(d, &name, next), "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPC" | "ENC_SOPK" => self.salu(d, &name), @@ -1282,6 +1286,10 @@ impl Em { if let Err(why) = r { self.unsupported(d, why); } + if let Some(v) = seed { + let v = self.vreg(v); + self.line(&format!("uint xcl_seed_{:x} = {v};", d.pc)); + } Flow::Next } @@ -4001,6 +4009,12 @@ impl Em { } "v_readlane_b32" => { let t = self.t(); + // the end of a whole-wave reduction (`wave32_reductions`) + if let Some((seed, op)) = self.reductions.reads.get(&d.pc) { + self.line(&format!("uint {t} = xcl_red_{op}(xcl_seed_{seed:x});")); + self.write32(&dst, &t); + return Ok(()); + } let rla = self.rla_uniform_fn(); let read = format!("{rla}({a}, {b} & {wmask}u)"); // wave64 VS / PS (`upper_lanes`): in a 32-lane wave, lanes 32..63 without a lane @@ -4754,6 +4768,9 @@ impl Em { if matches!(self.opt.mode, Mode::Pixel(_)) { h.push_str(PRELUDE_PIXEL); } + if !self.reductions.reads.is_empty() { + h.push_str(PRELUDE_REDUCE); + } if self.x64() { self.x64_prelude(&mut h); } @@ -6110,6 +6127,41 @@ void xcl_s_barrier() { } "#; +/// Whole-wave reductions of wave32 VS / PS programs (`wave32_reductions`). The console's combine +/// the lanes through DPP and permlane steps that pass partial results through lanes that were +/// never launched (`s_or_saveexec -1` runs them); here those lanes do not exist and the steps +/// read 0 from them, so a wave that is not full lost the words of live lanes. The lanes of each +/// half of a 64-lane wave are a console wave of their own. A helper lane is in no wave +/// operation and gets the result of a live lane of its quad (every quad has one). +const PRELUDE_REDUCE: &str = r#" +uint xcl_red_share(uint r) { +#ifdef XCL_PIXEL + uint hw = WaveGetLaneIndex(); + uint nib = (WaveActiveBallot(true)[hw >> 5] >> (hw & 28u)) & 15u; + uint q0 = QuadReadLaneAt(r, 0u), q1 = QuadReadLaneAt(r, 1u), q2 = QuadReadLaneAt(r, 2u), q3 = QuadReadLaneAt(r, 3u); + uint k = firstbitlow(nib); + r = (k & 2u) != 0u ? ((k & 1u) != 0u ? q3 : q2) : ((k & 1u) != 0u ? q1 : q0); +#endif + return r; +} +uint xcl_red_or(uint x) { + uint a = WaveActiveBitOr(select(xcl_half == 0u, x, 0u)), b = WaveActiveBitOr(select(xcl_half == 0u, 0u, x)); + return xcl_red_share(select(xcl_half == 0u, a, b)); +} +uint xcl_red_max(uint x) { + uint a = WaveActiveMax(select(xcl_half == 0u, x, 0u)), b = WaveActiveMax(select(xcl_half == 0u, 0u, x)); + return xcl_red_share(select(xcl_half == 0u, a, b)); +} +uint xcl_red_and(uint x) { + uint a = WaveActiveBitAnd(select(xcl_half == 0u, x, 0xFFFFFFFFu)), b = WaveActiveBitAnd(select(xcl_half == 0u, 0xFFFFFFFFu, x)); + return xcl_red_share(select(xcl_half == 0u, a, b)); +} +uint xcl_red_min(uint x) { + uint a = WaveActiveMin(select(xcl_half == 0u, x, 0xFFFFFFFFu)), b = WaveActiveMin(select(xcl_half == 0u, 0xFFFFFFFFu, x)); + return xcl_red_share(select(xcl_half == 0u, a, b)); +} +"#; + /// Pixel shaders: masks hold the helper lanes (#105). After `s_wqm` the helper pixels of a /// quad a primitive's edge splits are in EXEC and the console's `v_cmp*` / carries set their /// bits like any other lane's; wave ops leave helper lanes out before SM 6.7 (their ballot bits diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index d1e7d8bc4e..a4ce051df8 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -955,6 +955,80 @@ fn structurable_uncached(c: &Ctx, lo: u64, hi: u64, exit: Option, nest: usi Some(pending) } +/// The whole-wave reductions of a wave32 program (`wave32_reductions`). +#[derive(Default)] +pub struct Reductions { + /// pc of a `v_cndmask` that starts one → the VGPR it writes + pub seeds: std::collections::BTreeMap, + /// pc of the `v_readlane` that ends one → (its seed's pc, the operation: `xcl_red_`) + pub reads: std::collections::BTreeMap, +} + +/// The reductions the console's compiler makes over the lanes of a wave32 wave: +/// `s_or_saveexec_b32 s, -1` (every lane runs, launched or not), `v_cndmask v, identity, value, +/// mask`, three DPP8 steps (within 2, 4 and 8 lanes), a DPP row mirror, `v_permlanex16 w, v`, one more +/// step and `v_readlane s, v, 0` – nothing else in between, all in one basic block. +fn wave32_reductions(insts: &[Decoded], leaders: &std::collections::BTreeSet) -> Reductions { + let op_of = |d: &Decoded| match d.inst.name { + "V_OR_B32" => Some(("or", 128)), + "V_MAX_U32" => Some(("max", 128)), + "V_AND_B32" => Some(("and", 193)), + "V_MIN_U32" => Some(("min", 193)), + _ => None, + }; + let f = |d: &Decoded, n: &str| rdna2::field_value(d.enc, &d.words, n); + let ext = |d: &Decoded, n: &str| emit::ext_encoding(d).and_then(|e| rdna2::field_value(e, &d.words, n)); + // (the steps' waits and nops are not part of it) + let idle = |d: &Decoded| matches!(d.inst.name, "S_NOP" | "S_WAITCNT" | "V_NOP" | "S_WAITCNT_DEPCTR" | "S_INST_PREFETCH"); + // step k takes its value from the other half of the 2^(k+1) lanes a lane is in (all lanes of a + // half hold the same by then, so any of them will do) + let other_half = |k: usize, n: u64, sel: Option| sel.is_some_and(|s| s >> (k + 1) == n >> (k + 1) && (s ^ n) >> k & 1 == 1); + let mut out = Reductions::default(); + for (i, seed) in insts.iter().enumerate() { + if seed.inst.name != "V_CNDMASK_B32" || seed.variant != rdna2::Variant::Plain { + continue; + } + // the every-lane section it is in, with no other EXEC write before the end + let Some(open) = insts[..i].iter().rev().take(6).position(|d| d.inst.name == "S_OR_SAVEEXEC_B32" && f(d, "SSRC0") == Some(193)) else { continue }; + let open = i - 1 - open; + let steps: Vec<&Decoded> = insts[i + 1..].iter().filter(|d| !idle(d)).take(7).collect(); + let [a, b, c, mirror, cross, last, read] = steps[..] else { continue }; + let Some((op, identity)) = op_of(a) else { continue }; + let (_, w) = rdna2::vgpr_uses(seed); + let [v] = w[..] else { continue }; + if f(seed, "SRC0") != Some(identity) { + continue; + } + let same = |d: &Decoded, variant: rdna2::Variant| { + let (r, w) = rdna2::vgpr_uses(d); + op_of(d).map(|o| o.0) == Some(op) && d.variant == variant && w == vec![v] && r.contains(&v) + }; + let dpp8 = [a, b, c].iter().enumerate().all(|(k, d)| same(d, rdna2::Variant::Dpp8) && (0..8).all(|n| other_half(k, n, ext(d, &format!("LANE_SEL_{n}"))))); + let crossed = { + let (r, w) = rdna2::vgpr_uses(cross); + cross.inst.name == "V_PERMLANEX16_B32" && r.contains(&v) && w.len() == 1 + }; + if !dpp8 || !same(mirror, rdna2::Variant::Dpp16) || ext(mirror, "DPP_CTRL") != Some(0x140) || !crossed || !same(last, rdna2::Variant::Plain) { + continue; + } + let (r, _) = rdna2::vgpr_uses(read); + if read.inst.name != "V_READLANE_B32" || !r.contains(&v) || f(read, "SRC1") != Some(128) { + continue; + } + // one basic block, and EXEC kept all ones from the section's start + let end = insts.iter().position(|d| d.pc == read.pc).unwrap_or(i); + let inside = &insts[open + 1..=end]; + let straight = inside.iter().all(|d| !leaders.contains(&d.pc) && d.inst.flags & rdna2::F_TERMINATOR == 0 && rdna2::branch_target(d).is_none()); + let exec = inside.iter().any(|d| d.inst.name.contains("SAVEEXEC") || (d.enc.name.starts_with("ENC_SOP") && f(d, "SDST").is_some_and(|x| (126..=127).contains(&x)))); + if !straight || exec { + continue; + } + out.seeds.insert(seed.pc, v); + out.reads.insert(read.pc, (seed.pc, op)); + } + out +} + /// The instructions of block [start, end) at `depth`; the flow of the last one. fn emit_block(c: &Ctx, em: &mut emit::Em, body: &mut String, start: u64, end: u64, depth: usize, blocks: &mut usize) -> emit::Flow { em.indent = depth; @@ -1452,6 +1526,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { em.upper = Some(a); } } + if !opt.wave64 && matches!(opt.mode, Mode::Vertex(_) | Mode::Pixel(_)) { + em.reductions = wave32_reductions(&insts, &leaders); + } em.max_vgpr = insts .iter() .flat_map(|d| { From 7baeb8d7222b7a5259560313c76eb24df3ea5717 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 16:01:03 +0100 Subject: [PATCH 020/258] D3D12.X: an indirect dispatch runs no garbage group counts --- crates/xcl/src/hle/d3d12x/bind.rs | 134 +++++++++++++++++++++++++++++- 1 file changed, 130 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 10234d4145..0edcb731f2 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -551,13 +551,79 @@ void main(uint tid : SV_DispatchThreadID) { } "#; +/// The groups of an indirect dispatch (u2, `io` dword 0: their byte offset) as they go out (u3): +/// 0 x 0 x 0 when they are more than `io` dword 1 in all, or a count alone is (`MOST_GROUPS`). The +/// counts come from memory the GPU wrote; where that is not what the title meant they can be +/// anything, and billions of groups hold the GPU for seconds or until Windows resets the driver. +/// A count over D3D12's 65 535 that is not one of those is cut to it. +pub(super) const GUARD_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer src : register(u2); +RWByteAddressBuffer dst : register(u3); +[numthreads(1, 1, 1)] +void main() { + uint at = io.Load(0), most = io.Load(4), to = io.Load(8); + uint3 g = src.Load3(at); + bool none = g.x == 0u || g.y == 0u || g.z == 0u; + bool few = !none && all(g <= most) && g.x <= most / g.y && g.x * g.y <= most / g.z; + dst.Store3(to, few ? min(g, 65535u.xxx) : uint3(0u, 0u, 0u)); +} +"#; + +/// The groups of an indirect dispatch above which they are not the title's (`GUARD_ARGS_HLSL`): +/// a 4K target in groups of 2x2 pixels is 2.1 million. +const MOST_GROUPS: u32 = 1 << 22; + +unsafe fn guard_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: Mutex>> = Mutex::new(None); + args_pipeline(dev, GUARD_ARGS_HLSL, &CACHE) +} + +/// `XCL_INDIRECT_GUARD=0`: indirect dispatches run the groups memory holds, whatever they are. +fn indirect_guard() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INDIRECT_GUARD").map_or(true, |v| v.trim() != "0")) +} + +/// The arguments of one indirect dispatch at UMA address `src`, checked (`GUARD_ARGS_HLSL`): the +/// scratch block (INDIRECT_ARGUMENT until the caller puts it back to COMMON) and their offset. The +/// list's compute root signature and pipeline are the guard's after this. +unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize) -> Result<(ID3D12Resource, u64), String> { + let dev = super::real::list_device(this).ok_or("no device")?; + let (rs, pso) = guard_indirect_pipeline(&dev)?; + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + super::real::uma_window_buffer(src, 12).ok_or("the indirect arguments are not in one memory window")?; + let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + let (dst, dst_off) = scratch_args(this, &dev, 256)?; + let consts: Vec = [0u32, MOST_GROUPS, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); + let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + emit_uav_barrier(list, None); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, consts_va); + list.SetComputeRootUnorderedAccessView(2, src_va); + list.SetComputeRootUnorderedAccessView(3, dst.GetGPUVirtualAddress() + dst_off); + list.Dispatch(1, 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + Ok((dst, dst_off)) +} + unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { static CACHE: Mutex>> = Mutex::new(None); + args_pipeline(dev, SCALE_ARGS_HLSL, &CACHE) +} + +type ArgsPipelines = Mutex>>; + +unsafe fn args_pipeline(dev: &ID3D12Device, hlsl: &str, cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { let key = dev.as_raw() as usize; - if let Some(pair) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + if let Some(pair) = cache.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { return Ok(pair); } - let dxil = crate::gpu::recomp::dxc::compile_cached(SCALE_ARGS_HLSL, "main", "cs_6_6")?.0; + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; let rs = crate::gpu::recomp::pso::abi_root_signature(dev, false)?; let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), @@ -567,7 +633,7 @@ unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSigna let res_pso: Result = dev.CreateComputePipelineState(&cdesc); std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); let pso = res_pso.map_err(|e| format!("scale pso create: {e}"))?; - CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + cache.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); Ok((rs, pso)) } @@ -842,6 +908,30 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + // (before the dispatch's own root signature and pipeline are bound) + let mut guarded = None; + if compute && max == 1 && indirect_guard() && signature_dispatches(sig) { + if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { + match guard_dispatch_args(this, list, p) { + Ok(g) => guarded = Some(g), + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect's group counts are not checked: {e}"); + } + } + } + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + } + } + let (args, args_off) = guarded.as_ref().map_or((args, args_off), |(b, o)| (b.as_raw() as usize, *o)); + let unguard = || { + if let Some((b, _)) = &guarded { + emit_transition(list, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); + } + }; match bind_abi(this, list, pso, gfx) { Ok(()) => { if compute { @@ -851,14 +941,21 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us Err(e) => { crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); count(DISPATCHES_SKIPPED); + unguard(); return; } } } count(if gfx { DRAWS } else { DISPATCHES }); - fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) + if guarded.is_some() { + pc(this, sig, max, args, args_off, count_buf, count_off); + } else { + fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) + } + unguard(); } Err(e) => { + unguard(); count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -2329,6 +2426,35 @@ void main(uint t : SV_GroupIndex) { Some(((0..n).map(cmd).collect(), (n..2 * n).map(cmd).collect())) } + /// Indirect group counts that are not the title's run nothing, the others go out as they are. + #[test] + fn gpu_indirect_dispatch_runs_no_garbage_group_counts() { + use crate::gpu::recomp::runner; + if runner::adapter().is_err() { + runner::skip_test("no GPU"); + return; + } + let dxil = crate::gpu::recomp::dxc::compile(GUARD_ARGS_HLSL, "main", "cs_6_6", &[]).unwrap(); + let cases: [([u32; 3], [u32; 3]); 10] = [ + ([1, 1, 1], [1, 1, 1]), + ([2560 / 8, 1440 / 4, 1], [320, 360, 1]), + ([115_200, 1, 1], [65_535, 1, 1]), + ([0, 5, 5], [0, 0, 0]), + ([0xFF00_0000, 0xE3, 0xFF7F_0000], [0, 0, 0]), + ([65_535, 65_535, 65_535], [0, 0, 0]), + ([2048, 2048, 1], [2048, 2048, 1]), + ([2048, 2049, 1], [0, 0, 0]), + ([3, 1, 0xFFFF_FFFF], [0, 0, 0]), + ([1 << 16, 1 << 16, 1], [0, 0, 0]), + ]; + for (g, want) in cases { + let mut mem = vec![0xDEADu32; 64]; + mem[4..7].copy_from_slice(&g); + let out = runner::dispatch(&dxil, [1, 1, 1], &[16, MOST_GROUPS, 128], &mem).unwrap(); + assert_eq!(&out[32..35], &want, "{g:?}"); + } + } + #[test] fn gpu_indirect_two_pass_groups_stay_inside_the_record_buffer() { let Some((compute, mesh)) = scale_args(&[[7, 100, 1, 1], [8, 3, 1, 1], [9, 0, 1, 1]], 2, 10) else { return }; From edf78f09c1ab260672396a43517eea86022ebdb1 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 16:11:29 +0100 Subject: [PATCH 021/258] D3D12.X: the scratch of split dispatches is bounded over all recordings --- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 70 ++++++++++++++++--- 1 file changed, 60 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 865fb24463..0578506179 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -141,12 +141,36 @@ pub(in crate::hle::d3d12x) fn list_reset(list: usize) { SHARED.lock().unwrap().remove(&list); } -/// A scratch of `bytes` for a chain recorded on `list` with `allocator`, and whether a chain -/// before it on the list used it. -unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, bytes: u64) -> Option<(Arc, bool)> { +/// The scratch of all recordings alive together, `XCL_SPLIT_SCRATCH_TOTAL_MB` (384). A recording +/// keeps its scratch until its allocator is reset, and a title that records ahead of the GPU has +/// many: with a bound on one dispatch alone a retail title's world took 1.2 GB and went on growing. +fn scratch_total() -> u64 { + static B: OnceLock = OnceLock::new(); + *B.get_or_init(|| std::env::var("XCL_SPLIT_SCRATCH_TOTAL_MB").ok().and_then(|v| v.trim().parse().ok()).filter(|&m| m > 0).unwrap_or(384u64) << 20) +} + +/// A recording gets at least this much (or one group's worth) however much the others hold. +const LEAST: u64 = 2 << 20; + +/// How much scratch a dispatch of `needed` bytes (`group` for one group) runs with at once: the +/// list's own buffer (`had` bytes) when that is enough or no more may be made, else a new one of +/// the bytes given (second: make one). +fn scratch_bytes(needed: u64, group: u64, budget: u64, had: Option, live: u64, total: u64) -> (u64, bool) { + let want = needed.min(budget).max(group); + let room = total.saturating_sub(live); + match had { + Some(h) if h >= want || (room < want && h >= group) => (h, false), + _ => (want.min(room.max(LEAST)).max(group), true), + } +} + +/// A scratch for a chain of `needed` bytes recorded on `list` with `allocator`, and whether a +/// chain before it on the list used it. +unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, needed: u64, group: u64) -> Option<(Arc, bool)> { let had = SHARED.lock().unwrap().get(&list).filter(|s| s.0 == allocator).and_then(|s| s.1.upgrade()); - if let Some(s) = had.filter(|s| s.bytes >= bytes) { - return Some((s, true)); + let (bytes, make) = scratch_bytes(needed, group, scratch_budget(), had.as_ref().map(|s| s.bytes), LIVE.load(Ordering::Relaxed), scratch_total()); + if !make { + return had.map(|s| (s, true)); } let s = Arc::new(Scratch { buffer: scratch_buffer(dev, bytes)?, bytes }); let live = LIVE.fetch_add(bytes, Ordering::Relaxed) + bytes; @@ -186,12 +210,12 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) } else { allocator }; let group = u64::from(chain.words) * 4; - let most = (scratch_budget() / group).max(1); - let slabs = pso::dispatch_slabs(grid, most); - let first = slabs[0].1.into_iter().map(u64::from).product::(); - WANTED.fetch_max(grid.into_iter().fold(group, |s, n| s.saturating_mul(n as u64)), Ordering::Relaxed); + let needed = grid.into_iter().fold(group, |s, n| s.saturating_mul(n as u64)); + WANTED.fetch_max(needed, Ordering::Relaxed); let scratch = (allocator != 0 && list.GetType() != D3D12_COMMAND_LIST_TYPE_BUNDLE) - .then(|| scratch_for(&chain.builder.device, list.as_raw() as usize, allocator, first * group)).flatten(); + .then(|| scratch_for(&chain.builder.device, list.as_raw() as usize, allocator, needed, group)).flatten(); + let most = scratch.as_ref().map_or(1, |(s, _)| (s.bytes / group).max(1)); + let slabs = pso::dispatch_slabs(grid, most); let Some((scratch, used)) = scratch else { list.SetPipelineState(&chain.whole()?); list.Dispatch(x, y, z); @@ -205,3 +229,29 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, pso::record_dispatch_chain(list, grid, most, &held.scratch.buffer, used, std::iter::once(&held.first).chain(&held.chain.tail)); Ok(()) } + +#[cfg(test)] +mod tests { + use super::{scratch_bytes, LEAST}; + + const MB: u64 = 1 << 20; + + #[test] + fn a_chains_scratch_is_bounded_by_what_all_recordings_hold() { + let group = 187 << 10; + // the first of a recording: as much as it needs, up to the budget of one dispatch + assert_eq!(scratch_bytes(15 * MB, group, 64 * MB, None, 0, 384 * MB), (15 * MB, true)); + assert_eq!(scratch_bytes(900 * MB, group, 64 * MB, None, 0, 384 * MB), (64 * MB, true)); + // the others hold nearly all: what is left, and at least LEAST + assert_eq!(scratch_bytes(900 * MB, group, 64 * MB, None, 364 * MB, 384 * MB), (20 * MB, true)); + assert_eq!(scratch_bytes(900 * MB, group, 64 * MB, None, 1200 * MB, 384 * MB), (LEAST, true)); + // the list's own buffer: kept when big enough, or when no more may be made + assert_eq!(scratch_bytes(8 * MB, group, 64 * MB, Some(16 * MB), 100 * MB, 384 * MB), (16 * MB, false)); + assert_eq!(scratch_bytes(60 * MB, group, 64 * MB, Some(16 * MB), 380 * MB, 384 * MB), (16 * MB, false)); + // … but made again, larger, while there is room + assert_eq!(scratch_bytes(60 * MB, group, 64 * MB, Some(16 * MB), 100 * MB, 384 * MB), (60 * MB, true)); + // one group always fits, whatever the bounds say + assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, None, 400 * MB, 384 * MB), (9 * MB, true)); + assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true)); + } +} From 98be478531b7d57765bacd3fb375b7c209523b33 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 16:16:10 +0100 Subject: [PATCH 022/258] local: #1989's test keeps its vtable across Reset --- crates/xcl/src/hle/d3d12x/depth_uav.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 7eab5ca3f3..1e8062d3eb 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -2679,7 +2679,12 @@ mod tests { // --- Phase 2: Global UAV barrier (#146 GLOBAL) + before_bind_dsv --- alloc.Reset().unwrap(); let reset_orig: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> i32 = std::mem::transmute(real::orig_fn(list.as_raw(), 10)); - assert_eq!(reset_orig(list.as_raw(), alloc.as_raw(), std::ptr::null_mut()), 0); + { + // the runtime's Reset puts its own vtable back (as `list_x::reset_pc` knows) + let ext = *(list.as_raw() as *const usize); + assert_eq!(reset_orig(list.as_raw(), alloc.as_raw(), std::ptr::null_mut()), 0); + real::preserve_vtable(list.as_raw(), ext); + } set_heaps_orig(list.as_raw(), 1, &uav_heap_raw); set_cs_rs(list.as_raw(), cs_rs.as_raw()); @@ -2733,7 +2738,12 @@ mod tests { forget(depth_res.as_raw() as usize); alloc.Reset().unwrap(); - assert_eq!(reset_orig(list.as_raw(), alloc.as_raw(), std::ptr::null_mut()), 0); + { + // the runtime's Reset puts its own vtable back (as `list_x::reset_pc` knows) + let ext = *(list.as_raw() as *const usize); + assert_eq!(reset_orig(list.as_raw(), alloc.as_raw(), std::ptr::null_mut()), 0); + real::preserve_vtable(list.as_raw(), ext); + } } if let Some(m) = PIPELINES.lock().unwrap().as_mut() { m.remove(&(dev.as_raw() as usize)); From 0e06c5eac50b76e5a4eb8d4b0c6937c10ed0649e Mon Sep 17 00:00:00 2001 From: notdxbi <69725883+notdxbi@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:59:32 +0000 Subject: [PATCH 023/258] kernelx: XMemMapPhysicalPagesScatter with no page array unmaps A retail game unmaps addresses while it streams its world with XMemMapPhysicalPagesScatter(addresses, n, NULL); it checks the result and runs into its own int3 when the call fails (+0xb18de7, then its crash reporter). XCL refused a NULL page array with ERROR_INVALID_PARAMETER. Page 0 already means "unmap this address" in a scatter, so no array is taken as page 0 for every address. Test scatter_without_pages_unmaps: two pages mapped and written, unmapped with no array (the call succeeds, the addresses are no longer committed), mapped again they read what was written. It fails without the change ("refused"). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/kernelx.rs | 44 ++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 45eec18ec9..5731877be4 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1723,9 +1723,11 @@ pub unsafe extern "system" fn XMemMapPhysicalPages(va: *mut c_void, n: usize, ar } /// `BOOL XMemMapPhysicalPagesScatter(void** addresses, SIZE_T count, ULONG64* pages)`: one 64 KiB -/// page at each address (page 0: the address is unmapped) +/// page at each address (page 0: the address is unmapped). No page array unmaps every address: +/// a retail game unmaps that way while it streams its world and stops on its own `int3` when the +/// call fails. pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut c_void, n: usize, pages: *mut u64) -> BOOL { - if addresses.is_null() || pages.is_null() { + if addresses.is_null() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } @@ -1738,7 +1740,12 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut } let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); - let ok = (0..n).all(|i| !map_pages(away, *addresses.add(i), 1, pages.add(i) as *mut usize).is_null()); + // no page array: page 0 (unmap) for every address + let ok = (0..n).all(|i| { + let mut none = 0usize; + let page = if pages.is_null() { &mut none as *mut usize } else { pages.add(i) as *mut usize }; + !map_pages(away, *addresses.add(i), 1, page).is_null() + }); give_back_homes(away); ok as BOOL } @@ -2775,6 +2782,37 @@ mod tests { } } + /// `XMemMapPhysicalPagesScatter` with no page array unmaps each address, as page 0 does (a + /// retail game unmaps so while it streams; refused, it stopped on its own `int3`). + #[test] + fn scatter_without_pages_unmaps() { + unsafe { + let Some(_) = crate::gpu::uma::get() else { return }; + let mut n = 2; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let r = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert!(r != 0); + let addrs = [r as *mut c_void, (r + PHYS_PAGE) as *mut c_void]; + let mut ids = [pages[0] as u64, pages[1] as u64]; + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), 2, ids.as_mut_ptr()), 1); + (r as *mut u32).write_volatile(7); + ((r + PHYS_PAGE) as *mut u32).write_volatile(9); + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), 2, std::ptr::null_mut()), 1, "no page array: unmapped, not refused"); + for a in addrs { + assert!(!crate::gpu::shader::readable(a as usize, 4), "{a:p} still mapped"); + } + // the pages kept what was written: mapped again, they read it + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), 2, ids.as_mut_ptr()), 1); + assert_eq!(((r as *const u32).read_volatile(), ((r + PHYS_PAGE) as *const u32).read_volatile()), (7, 9)); + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), 2, std::ptr::null_mut()), 1); + // no addresses: the same answer with and without a page array + let mut none = [0u64; 1]; + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), 0, std::ptr::null_mut()), XMemMapPhysicalPagesScatter(addrs.as_ptr(), 0, none.as_mut_ptr())); + mem::VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE); + } + } + /// `n` pages with a sparse home (None, with nothing allocated: not on this adapter). unsafe fn sparse_pages(n: usize) -> Option> { let u = crate::gpu::uma::get()?; From 03e90ae148a32dc57536e35ec24e375f38658d8b Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 16:31:19 +0100 Subject: [PATCH 024/258] local: the merged presenter builds --- crates/xcl/src/hle/d3d12x/present.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 62656c877d..05d359c08e 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1080,7 +1080,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, return; // swap chain is bound to the first queue we presented from } // rotate to the oldest in-flight allocator slot and wait only for its fence (frame N-2) - if let Err(e) = prepare_pipelined_slot(p, frame.is_some()) { + if let Err(e) = prepare_pipelined_slot(p, is_frame) { p.disabled = matches!(&e, FenceError::Removed(_)); if !matches!(&e, FenceError::Timeout(_)) { crate::xlog_error!("present: previous copy: {e}"); From 294539c7426592308e2c9d2bb08940fec9f7d973 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 16:35:30 +0100 Subject: [PATCH 025/258] local: an unmap with no page array also with XCL_PAGE_ALIAS=1 --- crates/xcl/src/hle/kernelx.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 5731877be4..8a9feb6c91 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1731,8 +1731,11 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } + // no page array: page 0 (unmap) for every address + let mut none = 0u64; + let mut page = |i: usize| if pages.is_null() { &mut none as *mut u64 as *mut usize } else { pages.add(i) as *mut usize }; if alias::enabled() { - return (0..n).all(|i| !map_aliased(*addresses.add(i), 1, pages.add(i) as *mut usize).is_null()) as BOOL; + return (0..n).all(|i| !map_aliased(*addresses.add(i), 1, page(i)).is_null()) as BOOL; } if crate::gpu::uma::get().is_none() { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); @@ -1740,12 +1743,7 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut } let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); - // no page array: page 0 (unmap) for every address - let ok = (0..n).all(|i| { - let mut none = 0usize; - let page = if pages.is_null() { &mut none as *mut usize } else { pages.add(i) as *mut usize }; - !map_pages(away, *addresses.add(i), 1, page).is_null() - }); + let ok = (0..n).all(|i| !map_pages(away, *addresses.add(i), 1, page(i)).is_null()); give_back_homes(away); ok as BOOL } From a0442743dbe47e85e189bbf2abea3aab4d05215e Mon Sep 17 00:00:00 2001 From: Grein Date: Tue, 24 Nov 2026 12:25:34 -0300 Subject: [PATCH 026/258] DirectStorage: read a physical-page list again when its request runs A retail title keeps its destination page lists in slots of its own table and writes a slot's pages after EnqueueRequest. At enqueue such a slot can still name the pages of the slot's previous request, and the snapshot taken then is what execute() wrote to (#289 rereads only the entries that are 0). Over 16 000 requests a run were written into pages the title had since reused: its objects got garbage pointers and it crashed about 20 s into world loading; when the old pages were freed, the request failed with E_ACCESS_VIOLATION. The console reads the list when it runs the request. execute() now reads it again (through read_own, as the snapshot) and takes it when it differs and every page in it is allocated (kernelx::physical_pages_live). A list that was on the enqueuing thread's stack keeps the snapshot: that memory is reused once the call returns, and a page ID written there since can belong to another live allocation. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/dstorage.rs | 133 +++++++++++++++++++++++++++++++-- crates/xcl/src/hle/kernelx.rs | 5 ++ 2 files changed, 132 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 97755841df..01be8299b4 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -778,6 +778,13 @@ impl Request { } /// Snapshot a `PULONG_PTR` physical page array at enqueue time (callers often stack-allocate it). +/// `[p, p + len)` overlaps the calling thread's stack. +fn on_callers_stack(p: usize, len: usize) -> bool { + let (mut lo, mut hi) = (0usize, 0usize); + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadStackLimits(&mut lo, &mut hi) }; + p < hi && p.saturating_add(len.max(1)) > lo +} + unsafe fn snapshot_page_array(ptr: u64, offset: u16, byte_len: u32) -> Result, HRESULT> { if byte_len == 0 { return Ok(Vec::new()); @@ -872,7 +879,7 @@ fn note_request(r: &Request) { } /// Run a request; the destination gets the bytes or nothing. -unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[usize]>, src_pages: Option<&[usize]>) -> Result<(), HRESULT> { +unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[usize]>, dest_on_stack: bool, src_pages: Option<&[usize]>) -> Result<(), HRESULT> { let n = r.destination_size as usize; note_request(r); if !r.dest_physical_pages() && !writable(r.destination as usize, n) { @@ -929,6 +936,28 @@ unsafe fn execute(r: &Request, file: Option<&FileInner>, dest_pages: Option<&[us if r.dest_physical_pages() { let pages = dest_pages.ok_or(E_ACCESS_VIOLATION)?; + // The console reads the page list when it runs the request. A retail title keeps its + // lists in slots of its own table and writes a slot's pages after EnqueueRequest, so at + // enqueue a slot can still name the pages of its previous request: written there, the + // data lands in memory the title has since used for something else, or in freed pages. + // The list as it is now is taken when all its pages are allocated. A list that was on the + // enqueuing thread's stack keeps the snapshot: that memory is reused once the call + // returns, and a page ID written there since can belong to another allocation. + let mut current = vec![0usize; pages.len()]; + let pages = if !dest_on_stack + && read_own(r.destination as usize, current.as_mut_ptr() as *mut u8, std::mem::size_of_val(pages)) + && current[..] != pages[..] + && crate::hle::kernelx::physical_pages_live(¤t) + { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = N.fetch_add(1, Ordering::Relaxed) + 1; + if k == 1 || k.is_power_of_two() { + crate::xlog_info!("DirectStorage: {k} page lists written after their request was enqueued: the pages named at execution are used"); + } + ¤t[..] + } else { + pages + }; // A page number of 0 in the snapshot taken at enqueue (no page has it): the entry is // read again now. A retail title keeps its page arrays in its own tables and fills an // entry after EnqueueRequest – its streaming requests were refused by the thousand @@ -990,6 +1019,8 @@ enum Entry { req: Request, file: Option>, dest_pages: Option>, + /// the destination page list was on the enqueuing thread's stack (`on_callers_stack`) + dest_on_stack: bool, src_pages: Option>, }, /// refused at enqueue: reported in queue order by the worker (unless cancelled, as a request) @@ -1138,12 +1169,12 @@ impl QueueInner { return; } match e { - Entry::Request { seq, req, file, dest_pages, src_pages } => { + Entry::Request { seq, req, file, dest_pages, dest_on_stack, src_pages } => { if self.is_cancelled(seq, req.tag) { // Cancelled requests are skipped without affecting status or error record. return; } - if let Err(hr) = unsafe { execute(&req, file.as_deref(), dest_pages.as_deref(), src_pages.as_deref()) } { + if let Err(hr) = unsafe { execute(&req, file.as_deref(), dest_pages.as_deref(), dest_on_stack, src_pages.as_deref()) } { self.update_error(hr, req, file.as_deref(), since_status); } } @@ -1194,8 +1225,8 @@ impl QueueInner { } } - fn enqueue_request(self: &Arc, req: Request, file: Option>, dest_pages: Option>, src_pages: Option>) { - self.enqueue_numbered(|seq| Entry::Request { seq, req, file, dest_pages, src_pages }); + fn enqueue_request(self: &Arc, req: Request, file: Option>, dest_pages: Option>, dest_on_stack: bool, src_pages: Option>) { + self.enqueue_numbered(|seq| Entry::Request { seq, req, file, dest_pages, dest_on_stack, src_pages }); } /// A request refused at enqueue, numbered as a request so `CancelRequestsWithTag` covers it. @@ -1378,7 +1409,8 @@ unsafe extern "system" fn queue_enqueue_request(p: *mut c_void, req: *const u8) } else { None }; - q.enqueue_request(r, file, dest_pages, src_pages); + let dest_on_stack = dest_pages.as_ref().is_some_and(|p| on_callers_stack(r.destination as usize, std::mem::size_of_val(&p[..]))); + q.enqueue_request(r, file, dest_pages, dest_on_stack, src_pages); } unsafe extern "system" fn queue_enqueue_status(p: *mut c_void, array: *mut c_void, index: u32) { @@ -2316,6 +2348,95 @@ mod tests { } } + /// A title's table slot still names its previous request's page at enqueue and gets this + /// request's page before Submit: the data goes to the page named at execution, and the old + /// page (in use for something else by then) is left alone. A list on the enqueuing thread's + /// stack keeps its snapshot: a page written there since, though allocated, is not taken. + #[test] + fn a_destination_page_rewritten_after_enqueue() { + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; + if crate::gpu::uma::get().is_none() { + return; + } + unsafe { + let mut count = 2usize; + let mut pages = [0usize; 2]; + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut count, pages.as_mut_ptr()), 1); + + let mut f = std::ptr::null_mut(); + assert_eq!(DStorageGetFactory(&IID_FACTORY, &mut f), S_OK); + let vt = *(f as *const *const usize); + let create_queue: unsafe extern "system" fn(*mut c_void, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(3)); + let create_status: unsafe extern "system" fn(*mut c_void, u32, *const u8, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(*vt.add(5)); + let mut desc = [0u8; 0x18]; + desc[0..4].copy_from_slice(&1u32.to_le_bytes()); + desc[8..10].copy_from_slice(&16u16.to_le_bytes()); + desc[10] = 2; + let mut q = std::ptr::null_mut(); + assert_eq!(create_queue(f, desc.as_ptr(), &IID_QUEUE, &mut q), S_OK); + let mut s = std::ptr::null_mut(); + assert_eq!(create_status(f, 2, std::ptr::null(), &IID_STATUS_ARRAY, &mut s), S_OK); + let qv = *(q as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, *const u8) = std::mem::transmute(*qv.add(3)); + let status: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) = std::mem::transmute(*qv.add(4)); + let submit: unsafe extern "system" fn(*mut c_void) = std::mem::transmute(*qv.add(6)); + let sv = *(s as *const *const usize); + let complete: unsafe extern "system" fn(*mut c_void, u32) -> bool = std::mem::transmute(*sv.add(3)); + let hresult: unsafe extern "system" fn(*mut c_void, u32) -> HRESULT = std::mem::transmute(*sv.add(4)); + + let reserved = windows_sys::Win32::System::Memory::VirtualAlloc( + std::ptr::null(), + 2 * PHYS_PAGE_SIZE, + windows_sys::Win32::System::Memory::MEM_RESERVE, + windows_sys::Win32::System::Memory::PAGE_READWRITE, + ); + assert!(!reserved.is_null()); + assert_eq!(MapTitlePhysicalPages(reserved, 2, 0, 4, pages.as_mut_ptr()), reserved); + let old_page = std::slice::from_raw_parts_mut(reserved as *mut u8, 0x100); + old_page.fill(0xAB); + + let data: Vec = (0..0x100u32).map(|i| (i * 7 + 1) as u8).collect(); + let mut slot = Box::new([pages[0]]); + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, slot.as_ptr() as u64, 0, data.len() as u32, data.as_ptr() as u64, 0, data.len() as u32, 0, 0).as_ptr()); + std::ptr::write_volatile(&mut slot[0], pages[1]); + status(q, s, 0); + submit(q); + let t = std::time::Instant::now(); + while !complete(s, 0) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!(hresult(s, 0), S_OK); + let new_page = std::slice::from_raw_parts((reserved as *const u8).add(PHYS_PAGE_SIZE), data.len()); + assert_eq!(new_page, &data[..], "the data goes to the page the slot names at execution"); + assert!(old_page.iter().all(|&b| b == 0xAB), "the slot's previous page is left alone"); + + // the same on the enqueuing thread's stack: rewritten after enqueue with another live + // page, the list keeps its snapshot + let other = std::slice::from_raw_parts_mut((reserved as *mut u8).add(PHYS_PAGE_SIZE), data.len()); + other.fill(0xCD); + let data2: Vec = (0..0x100u32).map(|i| (i * 3 + 5) as u8).collect(); + let mut on_stack = [pages[0]]; + enqueue(q, request_ex(SOURCE_MEMORY_BIT | DEST_PHYS_PAGES_BIT, on_stack.as_ptr() as u64, 0, data2.len() as u32, data2.as_ptr() as u64, 0, data2.len() as u32, 0, 0).as_ptr()); + std::ptr::write_volatile(&mut on_stack[0], pages[1]); + status(q, s, 1); + submit(q); + let t = std::time::Instant::now(); + while !complete(s, 1) && t.elapsed().as_secs() < 5 { + std::thread::yield_now(); + } + assert_eq!(hresult(s, 1), S_OK); + assert_eq!(&old_page[..], &data2[..], "a list on the stack: the page of its snapshot"); + assert!(other.iter().all(|&b| b == 0xCD), "the page written on the stack since is left alone"); + + MapTitlePhysicalPages(reserved, 2, 0, 4, std::ptr::null_mut()); + windows_sys::Win32::System::Memory::VirtualFree(reserved, 0, windows_sys::Win32::System::Memory::MEM_RELEASE); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 2, pages.as_mut_ptr()), 1); + queue_close(q); + queue_release(q); + status_release(s); + } + } + #[test] fn physical_page_destinations_and_sources() { use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, PHYS_PAGE_SIZE}; diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 8a9feb6c91..ae0eba0ca5 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1177,6 +1177,11 @@ fn page_home(page: usize) -> Option { (live > 0 && index < first.checked_add(count)?).then(|| home.checked_add((index - first).checked_mul(PHYS_PAGE)?)).flatten() } +/// Whether every page of `pages` (at least one) is a physical page allocated now. +pub fn physical_pages_live(pages: &[usize]) -> bool { + !pages.is_empty() && pages.iter().all(|&p| page_home(p).is_some()) +} + /// Whether a home is only reserved until it is used (a sparse window's, or plain memory's – /// the coherent window is committed as a whole). fn lazy_home(home: usize) -> bool { From e8623e979bb863f9c90877bfccf769d933974ebe Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 17:00:59 +0100 Subject: [PATCH 027/258] local: #1405 also with XCL_PAGE_ALIAS=1 --- crates/xcl/src/hle/kernelx.rs | 2 +- crates/xcl/src/hle/kernelx/alias.rs | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index ae0eba0ca5..2f0a243892 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1179,7 +1179,7 @@ fn page_home(page: usize) -> Option { /// Whether every page of `pages` (at least one) is a physical page allocated now. pub fn physical_pages_live(pages: &[usize]) -> bool { - !pages.is_empty() && pages.iter().all(|&p| page_home(p).is_some()) + !pages.is_empty() && pages.iter().all(|&p| if alias::enabled() { alias::page_live(p) } else { page_home(p).is_some() }) } /// Whether a home is only reserved until it is used (a sparse window's, or plain memory's – diff --git a/crates/xcl/src/hle/kernelx/alias.rs b/crates/xcl/src/hle/kernelx/alias.rs index 5cf51b7603..351ab21a05 100644 --- a/crates/xcl/src/hle/kernelx/alias.rs +++ b/crates/xcl/src/hle/kernelx/alias.rs @@ -300,6 +300,11 @@ pub fn physical_page_at(va: usize) -> bool { with(|s| s.views.contains_key(&at) || s.away_at.contains_key(&at)) } +/// Whether `page` is a physical page allocated now. +pub fn page_live(page: usize) -> bool { + with(|s| s.page(page).is_some()) +} + /// The physical page mapped at the page holding `va` (a view, or a page moved there), or None. pub fn page_at(va: usize) -> Option { let at = va & !(PAGE - 1); From 2af4c65b2d24aaf9c4dd8bb964ab58008659eaaf Mon Sep 17 00:00:00 2001 From: imnicho Date: Wed, 25 Nov 2026 14:06:52 +0100 Subject: [PATCH 028/258] D3D12.X: XCL_TEXTURE_LEVEL_PAGES=1 gives a sampled texture's levels their pages with their texels A retail title places its streamed textures at full size and has memory behind their levels only as it loads them, the small ones first. vram::place_pages gives a sampled texture a 64 KiB page of video memory for every tile at once: when that title's world is set up about 92 % of those pages have nothing behind them (80 690 pages, 6 809 committed, on one card). With the switch (off by default) a sampled 2D texture of one slice is placed with no tile mapped. Its tiling is kept as groups of tiles, one for each level with tiles of its own and one for the packed levels, and a group gets its pages before the first upload that has texels for it - the same pages by address as before, so textures placed at one address still share them. A texture the GPU writes gets all its pages. Part of #1773. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 176 ++++++++++++++ crates/xcl/src/hle/d3d12x/vram.rs | 241 +++++++++++++++++++- 2 files changed, 405 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index db13b7dab6..be9a745777 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -464,6 +464,15 @@ fn recheck_source(e: &mut Entry) -> bool { /// by the GPU). The first upload, if still pending, stays: it runs before the title's submit /// that copies. pub fn note_gpu_write(res: usize) { + if super::vram::level_pages() { + // (a texture whose levels get their pages one by one: all of them before the GPU's write) + let p = res as *mut c_void; + unsafe { + if let Some(r) = ID3D12Resource::from_raw_borrowed(&p) { + super::vram::map_levels(r, None); + } + } + } let mut marked = false; { let mut t = TEXTURES.lock().unwrap(); @@ -540,6 +549,10 @@ pub fn forget(res: usize) { for r in &to_remap { unsafe { super::vram::remap_if_unmapped(r); + // (lazy levels: one the GPU wrote is not uploaded again, so all of it has pages) + if super::vram::level_pages() && TEXTURES.lock().unwrap().by_res.get(&(r.as_raw() as usize)).is_some_and(|e| e.gpu_written) { + super::vram::map_levels(r, None); + } } } if removed { @@ -1123,6 +1136,10 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { if super::present::trace_frame() { note_content(va, &r, &subs); } + if super::vram::level_pages() { + // (the queue waits for these mappings before the copies: `vram::before_execute` below) + map_levels_with_texels(&r, &subs); + } batch.push((r, subs, states)); } let d = device as *mut c_void; @@ -1149,6 +1166,27 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } } +/// (`vram::level_pages`) Before an upload of title texture `r`: its levels with texels in `subs` +/// (its subresources as they go up) get their video memory pages if they have none - a texture +/// placed with lazy levels; any other: nothing to do. A level of zeros has no texels: a streamed +/// texture's larger levels before the title has memory behind them (read as zeros, +/// `read_committed`). It keeps no pages, reads as zeros as it would with them, and its copy goes +/// to tiles that are not mapped, which drops it (tiled resources tier 2). +unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) { + if !super::vram::has_lazy_levels(r.as_raw() as usize) { + return; + } + // (one slice: its subresources are its levels) + let present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + super::vram::map_levels(r, Some(&present)); +} + +/// Whether every byte of `b` is zero (eight at a time: gigabytes a second where it is). +fn all_zero(b: &[u8]) -> bool { + let mut words = b.chunks_exact(8); + words.all(|w| u64::from_ne_bytes(w.try_into().unwrap()) == 0) && words.remainder().iter().all(|&x| x == 0) +} + /// `XCL_TRACE_FRAME`: how much of a title texture's top level is not zero, each time it is /// uploaded (the first 48 uploads of textures of 64x64 and more). fn note_content(va: usize, r: &ID3D12Resource, subs: &[texture::Subresource]) { @@ -2340,6 +2378,144 @@ mod tests { forget(gpu_res_id); } + /// Real GPU, `vram::level_pages` (`XCL_TEXTURE_LEVEL_PAGES=1`): a sampled texture placed on the + /// shared pages gets the pages of a level when an upload has texels for it. Its memory has + /// every level but the largest at first, as a title streams a texture: no page before the + /// first upload, then pages for those levels only and their texels right, zeros where there + /// are none. With memory under the largest level too, a texture placed there again (as a + /// title does) takes that level's pages - the others are shared - and holds all of it. A + /// texture the GPU writes gets the pages of all its levels. + #[test] + fn a_placed_texture_gets_the_pages_of_a_level_with_its_texels() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const NAME: &str = "a_placed_texture_gets_the_pages_of_a_level_with_its_texels"; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { return println!("SKIPPED {NAME}: no adapter") }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + return println!("SKIPPED {NAME}: software adapter"); + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { return println!("SKIPPED {NAME}: no D3D12 device") }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.ResourceHeapTier.0 < 2 + || opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 + { + return println!("SKIPPED {NAME}: tiled tier < 2"); + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + // 1024x1024 RGBA8, 11 levels, 64 KiB blocks: 5.4 MiB on the console + let d = console_desc(3, 1024, 1024, 1, 11, 28, 0x109); + let place_tex = |va: usize| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), va as u64, d.as_ptr(), D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "CreatePlacedResourceX failed: {hr:#x}"); + ID3D12Resource::from_raw(p) + }; + let read_sub = |r: &ID3D12Resource, sub: u32| -> Vec { + let rd = r.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&rd, sub, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + let buffer = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + own_work(|| { + super::super::vram::before_execute(&queue); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + texture::wait(&dev, &queue).unwrap(); + }); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + rb.Unmap(0, None); + out + }; + let tex = xg::Texture::new(&d).unwrap(); + let surface = tex.texels().unwrap(); + let (size, chain) = (tex.size() as usize, &surface.chain); + // the whole texture as the title will have it (no byte of a level zero), and what its + // levels then hold + let mut whole = vec![0u8; size]; + for (m, l) in chain.levels.iter().enumerate() { + let pat: Vec = (0..l.width * l.height * surface.bpe as usize).map(|k| 1 + ((m * 7 + k * 13) % 251) as u8).collect(); + chain.tile_level(&mut whole[..chain.slice_bytes], m, 0, &pat); + } + let want = subresources(whole.as_ptr() as usize, &tex); + assert_eq!(want.len(), 11); + // its place in the title's memory: everything below mip 0 is there (the levels follow + // each other from the smallest to mip 0, `tiling::Chain`) + let at = VirtualAlloc(std::ptr::null(), size.next_multiple_of(0x1_0000), MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(at, 0); + let top = chain.levels[0].offset; + assert!(top > 0 && top % 0x1000 == 0 && top < size, "mip 0 is the last part of the slice: from {top:#x} of {size:#x}"); + assert!(!VirtualAlloc(at as *const c_void, top, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::copy_nonoverlapping(whole.as_ptr(), at as *mut u8, top); + + super::super::vram::LEVEL_PAGES_FOR_TEST.store(true, Ordering::Relaxed); + let dev_key = dev.as_raw() as usize; + let dev_pages = || super::super::vram::page_bytes_for(dev_key).0; + let p0 = dev_pages(); + let small = place_tex(at); + super::super::vram::LEVEL_PAGES_FOR_TEST.store(false, Ordering::Relaxed); + if !super::super::vram::has_lazy_levels(small.as_raw() as usize) { + // (not reserved, or a tiling that does not add up: it has its pages as before) + drop(small); + VirtualFree(at as *mut c_void, 0, MEM_RELEASE); + return println!("SKIPPED {NAME}: this adapter's texture was not placed with lazy levels"); + } + super::super::vram::LEVEL_PAGES_FOR_TEST.store(true, Ordering::Relaxed); + assert_eq!(dev_pages(), p0, "no pages before the first upload"); + // the tiles of mip 0 and of all of it, as this driver lays them out + let (mut all, mut n, mut mip0) = (0u32, 1u32, D3D12_SUBRESOURCE_TILING::default()); + dev.GetResourceTiling(&small, Some(&mut all), None, None, Some(&mut n), 0, &mut mip0); + let top_tiles = mip0.WidthInTiles * mip0.HeightInTiles as u32 * mip0.DepthInTiles as u32; + assert!(n == 1 && top_tiles > 0 && top_tiles < all, "mip 0 has tiles of its own: {top_tiles} of {all}"); + refresh(queue.as_raw()); + assert_eq!(dev_pages() - p0, ((all - top_tiles) as usize) << 16, "pages for the levels with texels, none for mip 0"); + for sub in 1..11u32 { + assert!(read_sub(&small, sub) == want[sub as usize].data, "level {sub} after the first upload"); + } + assert!(read_sub(&small, 0).iter().all(|&b| b == 0), "a level without pages reads as zeros"); + // the title maps memory under mip 0 and fills it + assert!(!VirtualAlloc((at + top) as *const c_void, size - top, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::copy_nonoverlapping(whole.as_ptr().add(top), (at + top) as *mut u8, size - top); + let full = place_tex(at); + refresh(queue.as_raw()); + assert_eq!(dev_pages() - p0, (all as usize) << 16, "mip 0's pages come with its texels; the other levels' are shared"); + for sub in 0..11u32 { + assert!(read_sub(&full, sub) == want[sub as usize].data, "level {sub} once all of it is there"); + } + // what the GPU writes needs pages under all of the texture: the first one's mip 0 gets + // the pages of its address, which hold what the second one's upload put there + note_gpu_write(small.as_raw() as usize); + assert_eq!(dev_pages() - p0, (all as usize) << 16, "the same pages"); + assert!(read_sub(&small, 0) == want[0].data, "a GPU-written texture has pages under all its levels"); + super::super::vram::LEVEL_PAGES_FOR_TEST.store(false, Ordering::Relaxed); + drop((small, full)); + VirtualFree(at as *mut c_void, 0, MEM_RELEASE); + } + } + /// `read_committed` copies committed pages and leaves uncommitted gaps zeroed, including /// unaligned start/end offsets. #[test] diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 6ed4304ad5..c2b433d0bc 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -239,6 +239,110 @@ struct Target { mapped: bool, used: Vec, used_extra: Vec<(usize, usize)>, + /// its levels get their pages one by one (`map_levels`); None: all of it has pages + levels: Option, +} + +/// The tiles of a texture whose levels get video memory when an upload first has texels for +/// them (`level_pages`): a group for each level with tiles of its own, in order, then one for +/// the packed levels. +#[derive(Clone, Debug, PartialEq)] +struct Levels { + /// (the group's first subresource, its first tile in the resource, its tiles, mapped) + groups: Vec<(u32, u32, u32, bool)>, + /// the texture's levels (the last group's go up to here) + mips: u32, +} + +impl Levels { + /// From the resource's tiling: `standard` (first tile, tiles) of each level with tiles of + /// its own, `packed` the same of the packed levels, `total` tiles in all. None: they do not + /// add up to the resource (it then gets all its pages at once). + fn new(standard: &[(u32, u32)], packed: Option<(u32, u32)>, total: u32, mips: u32) -> Option { + let mut groups: Vec<(u32, u32, u32, bool)> = standard.iter().enumerate().map(|(i, &(first, n))| (i as u32, first, n, false)).collect(); + if let Some((first, n)) = packed { + groups.push((standard.len() as u32, first, n, false)); + } + let mut next = 0u32; + let mut by_tile = groups.clone(); + by_tile.sort_by_key(|g| g.1); + for g in &by_tile { + if g.2 == 0 || g.1 != next { + return None; + } + next = g.1.checked_add(g.2)?; + } + (next == total && !groups.is_empty()).then_some(Levels { groups, mips }) + } + + /// The levels of group `k`. + fn levels_of(&self, k: usize) -> std::ops::Range { + self.groups[k].0..self.groups.get(k + 1).map_or(self.mips, |g| g.0) + } + + /// The group level `level` is in (the packed levels share the last one). + fn group_of(&self, level: u32) -> usize { + self.groups.partition_point(|g| g.0 <= level).saturating_sub(1) + } +} + +/// `XCL_TEXTURE_LEVEL_PAGES=1` (off by default): a sampled 2D texture of one slice on the +/// shared pages gets the pages of a level when an upload first has texels for it. A retail game +/// places its streamed textures at full size and maps memory under their levels as it loads +/// them, the small ones first; with a page for every 64 KiB a texture covers most of the pages +/// are for levels that are not loaded. +pub(super) fn level_pages() -> bool { + #[cfg(test)] + if LEVEL_PAGES_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { + return true; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_TEXTURE_LEVEL_PAGES").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("D3D12.X: XCL_TEXTURE_LEVEL_PAGES=1 - a sampled texture's levels get their video memory pages when an upload first has texels for them"); + } + on + }) +} + +/// `level_pages` for a test (under `VRAM_TEST_LOCK`) +#[cfg(test)] +pub(super) static LEVEL_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Of the textures with lazy levels there are now: how many, the tiles they stand for, and the +/// tiles of them that have pages; and the level groups given pages so far. +static LEVEL_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; + +/// (textures with lazy levels, the tiles they stand for, the tiles of them with pages, level +/// groups given pages so far) +fn level_stats() -> (u64, u64, u64, u64) { + let l = |k: usize| LEVEL_STATS[k].load(std::sync::atomic::Ordering::Relaxed); + (l(0), l(1), l(2), l(3)) +} + +impl Levels { + /// Its tiles that have pages. + fn mapped_tiles(&self) -> u64 { + self.groups.iter().filter(|g| g.3).map(|g| g.2 as u64).sum() + } +} + +/// The tiling of reserved texture `res` of `mips` levels as `Levels`, and its tiles in all. +unsafe fn level_tiling(dev: &ID3D12Device, res: &ID3D12Resource, mips: u32) -> (Option, u32) { + let mut total = 0u32; + let mut packed = D3D12_PACKED_MIP_INFO::default(); + let mut n = mips; + let mut tilings = vec![D3D12_SUBRESOURCE_TILING::default(); mips as usize]; + dev.GetResourceTiling(res, Some(&mut total), Some(&mut packed), None, Some(&mut n), 0, tilings.as_mut_ptr()); + let standard: Vec<(u32, u32)> = tilings + .iter() + .take((packed.NumStandardMips as usize).min(n as usize)) + .map(|t| (t.StartTileIndexInOverallResource, t.WidthInTiles * t.HeightInTiles as u32 * t.DepthInTiles as u32)) + .collect(); + let tail = (packed.NumPackedMips > 0).then_some((packed.StartTileIndexInOverallResource, packed.NumTilesForPackedMips)); + let whole = standard.len() == packed.NumStandardMips as usize && packed.NumStandardMips as u32 + packed.NumPackedMips as u32 == mips; + (if whole { Levels::new(&standard, tail, total, mips) } else { None }, total) } /// Per-heap free-tile allocator for `Pages`. @@ -592,7 +696,8 @@ impl Pages { } /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. - unsafe fn map(&mut self, res: &ID3D12Resource, tiles: &[Tile]) { + /// `tiles` for the tiles of `res` from the first one of subresource `sub` on. + unsafe fn map(&mut self, res: &ID3D12Resource, sub: u32, tiles: &[Tile]) { if tiles.is_empty() { return; } @@ -616,7 +721,7 @@ impl Pages { self.scratch_counts.push(count); num_tiles += count; } - let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let coord = D3D12_TILED_RESOURCE_COORDINATE { Subresource: sub, ..Default::default() }; let region = D3D12_TILE_REGION_SIZE { NumTiles: num_tiles, UseBox: false.into(), ..Default::default() }; let _timer = step(Step::Map); self.queue.UpdateTileMappings( @@ -697,6 +802,12 @@ impl Pages { /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { + self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize) + } + + /// `bind` for the tiles `range` of the resource's `total`, which start at subresource `sub`. + #[allow(clippy::too_many_arguments)] + unsafe fn bind_range(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32, sub: u32, range: std::ops::Range) -> Option<(Vec, Vec<(usize, usize)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); let timer = step(Step::Sweep); @@ -705,7 +816,7 @@ impl Pages { let mut missing = 0usize; let mut preferred: Option = None; - for i in 0..total as usize { + for i in range.clone() { let existing = if i < own { self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) } else { @@ -727,10 +838,10 @@ impl Pages { })?; let mut fresh_iter = fresh.into_iter(); - let mut tiles = Vec::with_capacity(total as usize); - let mut used = Vec::with_capacity(own); + let mut tiles = Vec::with_capacity(range.len()); + let mut used = Vec::with_capacity(own.min(range.len())); let mut used_extra = Vec::new(); - for i in 0..total as usize { + for i in range { let tile = if i < own { let a = first + i * PAGE; let t = match self.pages.get_mut(&a) { @@ -766,7 +877,7 @@ impl Pages { }; tiles.push(tile); } - self.map(res, &tiles); + self.map(res, sub, &tiles); Some((used, used_extra)) } } @@ -868,6 +979,7 @@ unsafe fn place_on_pages( clear: *const c_void, console_bytes: Option, require_aligned: bool, + lazy: bool, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void, ) -> Option { @@ -913,15 +1025,28 @@ unsafe fn place_on_pages( let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; let timer = step(Step::Tiling); - dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + let levels = if lazy { + let (levels, n) = level_tiling(dev, res, desc.MipLevels as u32); + total = n; + levels.filter(|_| total > 0 && owned_pages(va, console_bytes, total as usize).is_some()) + } else { + dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + None + }; drop(timer); let bound = { let timer = step(Step::Lock); let mut g = PAGES.lock().unwrap(); drop(timer); if let Some(Some(pages)) = g.get_mut(&dev_key) { - if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra }); + if levels.is_some() { + // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) + LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels }); + true + } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None }); true } else { false @@ -954,6 +1079,10 @@ pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { let used = std::mem::take(&mut t.used); let used_extra = std::mem::take(&mut t.used_extra); t.mapped = false; + if let Some(l) = t.levels.as_mut() { + LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); + l.groups.iter_mut().for_each(|g| g.3 = false); + } pages.unmap(res, total); pages.release_tiles(used, used_extra, now, true); return; @@ -976,6 +1105,11 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { if mapped { return true; } + // (lazy levels: they get their pages again with their next texels) + if let Some(t) = pages.targets.get_mut(&key).filter(|t| t.levels.is_some()) { + t.mapped = true; + return true; + } let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { return false; }; @@ -993,6 +1127,11 @@ fn forget_pages(resource: usize) { let now = std::time::Instant::now(); for pages in g.values_mut().flatten() { let Some(t) = pages.targets.remove(&resource) else { continue }; + if let Some(l) = &t.levels { + LEVEL_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + LEVEL_STATS[1].fetch_sub(t.total as u64, std::sync::atomic::Ordering::Relaxed); + LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); + } if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); } @@ -1129,7 +1268,61 @@ pub unsafe fn place_pages( if console_has_packed_3d_mips(desc) { return None; } - place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, riid, ppv) + // (one slice: the tiles of an array's packed levels are not asked about here) + let lazy = level_pages() && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.DepthOrArraySize == 1 && desc.SampleDesc.Count == 1 && desc.Flags == D3D12_RESOURCE_FLAG_NONE; + place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, lazy, riid, ppv) +} + +/// The levels `levels` of `res` (None: all of them) get their pages if they have none yet: a +/// texture placed with lazy levels (any other: nothing to do). Returns the levels that got pages +/// by this call - the queue the texture is used on next has to wait for that (`before_execute`), +/// and what the pages held before is another texture's. +pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> Vec { + let key = res.as_raw() as usize; + let mut g = PAGES.lock().unwrap(); + for (&dev_key, pages) in g.iter_mut() { + let Some(pages) = pages.as_mut() else { continue }; + let Some(t) = pages.targets.get(&key) else { continue }; + let Some(lv) = t.levels.as_ref().filter(|_| t.mapped) else { return Vec::new() }; + let mut wanted: Vec = match levels { + Some(l) => l.iter().map(|&x| lv.group_of(x)).collect(), + None => (0..lv.groups.len()).collect(), + }; + wanted.sort_unstable(); + wanted.dedup(); + let todo: Vec<(usize, u32, u32, u32, std::ops::Range)> = + wanted.into_iter().filter(|&k| !lv.groups[k].3).map(|k| (k, lv.groups[k].0, lv.groups[k].1, lv.groups[k].2, lv.levels_of(k))).collect(); + if todo.is_empty() { + return Vec::new(); + } + let (va, console_bytes, total) = (t.va, t.console_bytes, t.total); + let d = dev_key as *mut c_void; + let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return Vec::new() }; + let mut fresh = Vec::new(); + for (k, sub, first, n, levels) in todo { + let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize) else { continue }; + let Some(t) = pages.targets.get_mut(&key) else { return fresh }; + t.used.extend(used); + t.used_extra.extend(used_extra); + if let Some(l) = t.levels.as_mut() { + l.groups[k].3 = true; + } + LEVEL_STATS[2].fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); + let groups = LEVEL_STATS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if groups >= 1024 && groups.is_power_of_two() { + let (textures, stand, mapped, _) = level_stats(); + crate::xlog_info!("D3D12.X: level pages: {textures} textures standing for {} MB have pages for {} MB ({groups} levels given pages so far)", stand >> 4, mapped >> 4); + } + fresh.extend(levels); + } + return fresh; + } + Vec::new() +} + +/// Whether `resource` is a texture whose levels get their pages one by one (`map_levels`). +pub(super) fn has_lazy_levels(resource: usize) -> bool { + PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).is_some_and(|t| t.levels.is_some())) } /// XG and the PC driver pack volume mip tails differently. Keep these textures on the @@ -1163,7 +1356,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st return None; } if std::env::var_os("XCL_VRAM_ARENAS").is_none() { - if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, true, riid, ppv) { + if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, true, false, riid, ppv) { return Some(hr); } } @@ -1191,6 +1384,30 @@ mod tests { const MIB: usize = 1 << 20; + /// The levels of a texture with lazy levels: a group of tiles for each level with tiles of its + /// own and one for the packed levels; a level past the last standard one is in the packed + /// group; a tiling that does not add up to the resource's tiles gives none. + #[test] + fn the_tiles_of_a_texture_are_grouped_by_its_levels() { + // 2048x2048 BC7, 12 levels: 64, 16, 4, 1 tiles and 1 for the 8 packed levels + let l = Levels::new(&[(0, 64), (64, 16), (80, 4), (84, 1)], Some((85, 1)), 86, 12).unwrap(); + assert_eq!(l.groups, vec![(0, 0, 64, false), (1, 64, 16, false), (2, 80, 4, false), (3, 84, 1, false), (4, 85, 1, false)]); + assert_eq!((0..12).map(|i| l.group_of(i)).collect::>(), [0, 1, 2, 3, 4, 4, 4, 4, 4, 4, 4, 4]); + assert_eq!((l.levels_of(0), l.levels_of(3), l.levels_of(4)), (0..1, 3..4, 4..12)); + // all of it packed: one group + let small = Levels::new(&[], Some((0, 1)), 1, 5).unwrap(); + assert_eq!((small.group_of(0), small.group_of(4), small.levels_of(0)), (0, 0, 0..5)); + // no packed levels: the last level's group ends at the texture's levels + let plain = Levels::new(&[(0, 4), (4, 1)], None, 5, 2).unwrap(); + assert_eq!((plain.group_of(1), plain.levels_of(1)), (1, 1..2)); + // a gap, an overlap, a tile count that is not the resource's, nothing at all + assert_eq!(Levels::new(&[(0, 4), (5, 1)], None, 6, 2), None); + assert_eq!(Levels::new(&[(0, 4), (3, 2)], None, 5, 2), None); + assert_eq!(Levels::new(&[(0, 4), (4, 1)], None, 6, 2), None); + assert_eq!(Levels::new(&[(0, 4), (4, 0)], None, 4, 2), None); + assert_eq!(Levels::new(&[], None, 0, 1), None); + } + #[test] fn packed_console_3d_mip_tails_use_the_detile_upload_path() { fn desc( From 31b4c5c73bdb864e710d199974be2289a047d4e6 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 17:18:49 +0100 Subject: [PATCH 029/258] local: XCL_PSO_MAX_CACHED=1 --- crates/xcl/src/hle/d3d12x/real.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index b3fa46b724..5bb6fa30a5 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4400,6 +4400,13 @@ fn build_cap_bytes() -> usize { *V.get_or_init(|| std::env::var("XCL_PSO_MAX_KB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0usize).saturating_mul(1024)) } +/// `XCL_PSO_MAX_CACHED=1`: `XCL_PSO_MAX_KB` also holds for a program with a saved driver blob (one +/// of ~1 MB of DXIL takes ~50 MB of commit once made, however quickly). +fn cap_holds_for_cached() -> bool { + static V: OnceLock = OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_PSO_MAX_CACHED").is_ok_and(|v| v.trim() == "1")) +} + fn over_build_cap(dxil: usize, cap: usize) -> bool { cap != 0 && dxil > cap } @@ -4432,8 +4439,8 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL if let Some(b) = &cached { copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } - if cached.is_none() && over_build_cap(dxil.len(), build_cap_bytes()) { - crate::xlog_warn!("D3D12.X: compute PSO of record {record:016x} ({} B DXIL) not built: over XCL_PSO_MAX_KB and without a saved blob", dxil.len()); + if (cached.is_none() || cap_holds_for_cached()) && over_build_cap(dxil.len(), build_cap_bytes()) { + crate::xlog_warn!("D3D12.X: compute PSO of record {record:016x} ({} B DXIL) not built: over XCL_PSO_MAX_KB{}", dxil.len(), if cached.is_none() { " and without a saved blob" } else { " (it has a saved blob)" }); return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); } // in the background, a few at a time and within the commit headroom the program asks for From 77b416f8e0f088f7d9cf668a9aff14c89b0e2bc4 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 17:31:00 +0100 Subject: [PATCH 030/258] D3D12.X: the two-pass record buffer is shared by the recordings --- crates/xcl/src/hle/d3d12x/bind.rs | 71 +++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8f9ee70fe5..4bcd56a247 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -40,6 +40,8 @@ struct State { arena: crate::gpu::uma::Arena, res_buf: Option<(ID3D12Resource, u64, usize)>, res_retired: Vec<(ID3D12Resource, u64, usize)>, + /// the recording used the shared record buffer (`shared_record_buffer`) + shared_records: bool, /// rewritten indirect arguments (`scratch_args`): the block, its bytes in use, and the /// bytes of blocks this recording took scratch: Option<(ID3D12Resource, u64, usize)>, @@ -127,6 +129,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.args_gfx.clear(); s.rs_gfx = 0; s.heaps = [0; 2]; + s.shared_records = false; // (the scratch blocks are in `res_retired` already) (s.scratch, s.scratch_used, s.scratch_taken) = (None, 0, 0); let mut res_bufs = std::mem::take(&mut s.res_retired); @@ -423,9 +426,55 @@ fn two_pass_steps(max: u32) -> impl Iterator { (0..max).flat_map(|k| [(k, true), (k, false)]) } +/// The record buffers all recordings of a device share (`XCL_TWO_PASS_SHARED=0`: one of each list, +/// kept until its allocator is reset). A retail title's world frame has more than a hundred lists +/// with two-pass draws: at 32 MiB a list the first frame took 4 GB of video memory. A direct +/// queue runs its lists in order and every pass over the records ends with a UAV barrier +/// (`emit_uav_barrier`), so the next list's passes see none of it as long as there is one direct +/// queue (`one_direct_queue`). +static SHARED_RECORDS: Mutex> = Mutex::new(Vec::new()); +const SHARED_LEAST: u64 = 32 << 20; + +fn shared_records_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TWO_PASS_SHARED").map_or(true, |v| v.trim() != "0")) +} + +/// The title submitted work to at most one direct queue so far. +unsafe fn one_direct_queue() -> bool { + let direct = |q: usize| { + let raw = q as *mut c_void; + ID3D12CommandQueue::from_raw_borrowed(&raw).is_some_and(|q| q.GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT) + }; + super::present::known_queues().into_iter().filter(|&q| direct(q)).count() <= 1 +} + +/// A shared record buffer of at least `need` bytes: buffer, address, bytes. +unsafe fn shared_record_buffer(dev: &ID3D12Device, need: u64) -> Result<(ID3D12Resource, u64), String> { + let key = dev.as_raw() as usize; + let mut all = SHARED_RECORDS.lock().unwrap(); + if let Some((buf, cap, _)) = all.iter().find(|(_, cap, d)| *d == key && *cap >= need) { + return Ok((buf.clone(), *cap)); + } + let bytes = need.max(SHARED_LEAST); + let buf = default_uav_buffer(dev, bytes, "shared two-pass record buffer")?; + all.push((buf.clone(), bytes, key)); + Ok((buf, bytes)) +} + /// The record buffer of this list for `need_bytes` (at most 128 MiB): buffer, address, bytes. unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64, u64), String> { let need = need_bytes.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); + if shared_records_on() && one_direct_queue() { + let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; + let (buf, cap) = shared_record_buffer(&dev, need)?; + let first = with(this, |s| !std::mem::replace(&mut s.shared_records, true)); + if let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this).filter(|_| first) { + emit_uav_barrier(list, None); // what an earlier list left in the records + } + let va = buf.GetGPUVirtualAddress(); + return Ok((buf, va, cap)); + } if let Some((buf, cap, _dev)) = with(this, |s| s.res_buf.as_ref().filter(|(_, cap, _)| *cap >= need).cloned()) { let va = buf.GetGPUVirtualAddress(); return Ok((buf, va, cap)); @@ -2495,6 +2544,28 @@ void main(uint t : SV_GroupIndex) { assert!(!pool_keeps(16, 0, 1 << 20)); } + /// Recordings share one record buffer, a bigger one is made only when that one is too small. + #[test] + fn gpu_two_pass_record_buffer_is_shared_by_the_recordings() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + let mut dev: Option = None; + if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + unsafe { + let (a, cap) = shared_record_buffer(&dev, 4 << 20).unwrap(); + assert_eq!(cap, SHARED_LEAST); + let (b, _) = shared_record_buffer(&dev, SHARED_LEAST).unwrap(); + assert_eq!(a.as_raw(), b.as_raw(), "a second recording's records are the first one's"); + let (c, big) = shared_record_buffer(&dev, SHARED_LEAST + 1).unwrap(); + assert!(c.as_raw() != a.as_raw() && big > SHARED_LEAST); + let (d, _) = shared_record_buffer(&dev, 4 << 20).unwrap(); + assert_eq!(d.as_raw(), a.as_raw()); + } + } + #[test] fn gpu_two_pass_argument_scratch_is_shared_and_capped() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; From 03a30949705fe8dce888f1f9f4da436048334cd8 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 17:39:10 +0100 Subject: [PATCH 031/258] local: census of committed resources --- crates/xcl/src/hle/d3d12x/bind.rs | 7 ++++++ crates/xcl/src/hle/d3d12x/real.rs | 37 +++++++++++++++++++++++++++++++ crates/xcl/src/host.rs | 3 +++ 3 files changed, 47 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 4bcd56a247..e8cba5fb67 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -465,6 +465,13 @@ unsafe fn shared_record_buffer(dev: &ID3D12Device, need: u64) -> Result<(ID3D12R /// The record buffer of this list for `need_bytes` (at most 128 MiB): buffer, address, bytes. unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D12Resource, u64, u64), String> { let need = need_bytes.max(4 << 20).next_multiple_of(1 << 20).min(128 << 20); + { + // local: which way the records go, once each + static SAID: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()]; + let one = one_direct_queue(); + let on = shared_records_on(); + SAID[(on && one) as usize].call_once(|| crate::xlog_info!("D3D12.X: two-pass records: {} (switch {on}, one direct queue {one})", if on && one { "shared" } else { "a buffer of each list" })); + } if shared_records_on() && one_direct_queue() { let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; let (buf, cap) = shared_record_buffer(&dev, need)?; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5bb6fa30a5..5a707bf1d7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3141,12 +3141,49 @@ macro_rules! creator { } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { adopt(*ppv, $kind); + if $method.starts_with("CreateCommittedResource") { + note_committed(this, *ppv); + } } hr } }; } +/// local: what was committed (resources of their own heap), by shape: (heap type, dimension, +/// width, height, format) -> (made, bytes) +static COMMITTED: Mutex>> = Mutex::new(None); + +unsafe fn note_committed(dev: *mut c_void, res: *mut c_void) { + let (Some(dev), Some(r)) = (ID3D12Device::from_raw_borrowed(&dev), ID3D12Resource::from_raw_borrowed(&res)) else { return }; + let d = r.GetDesc(); + let (mut props, mut flags) = (D3D12_HEAP_PROPERTIES::default(), D3D12_HEAP_FLAGS::default()); + let _ = r.GetHeapProperties(Some(&mut props), Some(&mut flags)); + let bytes = dev.GetResourceAllocationInfo(0, &[d]).SizeInBytes; + let mut g = COMMITTED.lock().unwrap(); + let e = g.get_or_insert_with(HashMap::new).entry((props.Type.0, d.Dimension.0, d.Width, d.Height, d.Format.0)).or_default(); + e.0 += 1; + if bytes != u64::MAX { + e.1 += bytes; + } +} + +/// local: the committed shapes that were made since the last report, biggest first +pub fn committed_report() -> Option { + static LAST: Mutex>> = Mutex::new(None); + let now = COMMITTED.lock().unwrap().clone()?; + let mut last = LAST.lock().unwrap(); + let before = last.replace(now.clone()).unwrap_or_default(); + let mut d: Vec<_> = now.iter().map(|(k, v)| (k, v.0 - before.get(k).map_or(0, |b| b.0), v.1 - before.get(k).map_or(0, |b| b.1))).filter(|x| x.1 > 0).collect(); + d.sort_by_key(|x| std::cmp::Reverse(x.2)); + let total: u64 = d.iter().map(|x| x.2).sum(); + if total < 64 << 20 { + return None; + } + let top: Vec = d.iter().take(6).map(|(k, n, b)| format!("{n}x heap {} dim {} {}x{} fmt {}: {} MB", k.0, k.1, k.2, k.3, k.4, b >> 20)).collect(); + Some(format!("{} MB in {} resources: {}", total >> 20, d.iter().map(|x| x.1).sum::(), top.join("; "))) +} + creator!(dev_create_command_queue, "CreateCommandQueue", Kind::CommandQueue, [a1]); creator!(dev_create_command_queue1, "CreateCommandQueue1", Kind::CommandQueue, [a1, a2]); creator!(dev_create_command_allocator, "CreateCommandAllocator", Kind::CommandAllocator, [a1]); diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 71a25c7c14..5cffd7a752 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -70,6 +70,9 @@ pub fn host_main(boot_path: &Path) -> i32 { let (arenas, arenas_made) = crate::hle::d3d12x::vram::arena_bytes(); let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); + if let Some(t) = crate::hle::d3d12x::real::committed_report() { + crate::xlog_info!("committed since the last line: {t}"); + } let mb = |b: u64| b >> 20; crate::xlog_info!( "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped)", From 9211159c21fae7288d3b539d9e06c9e010de72fc Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 17:42:42 +0100 Subject: [PATCH 032/258] D3D12.X: the two-pass record buffer is shared while one queue gets the lists --- crates/xcl/src/hle/d3d12x/bind.rs | 54 ++++++++++++++++++++-------- crates/xcl/src/hle/d3d12x/present.rs | 1 + 2 files changed, 41 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e8cba5fb67..af9727b82d 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -428,10 +428,10 @@ fn two_pass_steps(max: u32) -> impl Iterator { /// The record buffers all recordings of a device share (`XCL_TWO_PASS_SHARED=0`: one of each list, /// kept until its allocator is reset). A retail title's world frame has more than a hundred lists -/// with two-pass draws: at 32 MiB a list the first frame took 4 GB of video memory. A direct -/// queue runs its lists in order and every pass over the records ends with a UAV barrier -/// (`emit_uav_barrier`), so the next list's passes see none of it as long as there is one direct -/// queue (`one_direct_queue`). +/// with two-pass draws: at 32 MiB a list the first frames made 68 of them in 4 s. A queue runs +/// its lists in order and every pass over the records ends with a UAV barrier +/// (`emit_uav_barrier`), so the next list's passes see none of it as long as all of them go to +/// one queue (`note_records_queue`). static SHARED_RECORDS: Mutex> = Mutex::new(Vec::new()); const SHARED_LEAST: u64 = 32 << 20; @@ -440,13 +440,30 @@ fn shared_records_on() -> bool { *ON.get_or_init(|| std::env::var("XCL_TWO_PASS_SHARED").map_or(true, |v| v.trim() != "0")) } -/// The title submitted work to at most one direct queue so far. -unsafe fn one_direct_queue() -> bool { - let direct = |q: usize| { - let raw = q as *mut c_void; - ID3D12CommandQueue::from_raw_borrowed(&raw).is_some_and(|q| q.GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT) - }; - super::present::known_queues().into_iter().filter(|&q| direct(q)).count() <= 1 +/// The queue the recordings with two-pass draws go to (0: none yet), and whether a second one +/// was seen: the shared buffer is for one queue's lists, which run in order. +static RECORDS_QUEUE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static RECORDS_QUEUES_DIFFER: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// `lists` go to `queue` now (`present::note_execute`): the ones that used the shared record +/// buffer must all go to one queue. +pub(super) fn note_records_queue(queue: usize, lists: &[*mut c_void]) { + if RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed) { + return; + } + let used = STATES.lock().unwrap().as_ref().is_some_and(|m| lists.iter().any(|&l| m.get(&(l as usize)).is_some_and(|s| s.shared_records))); + if used && !same_records_queue(&RECORDS_QUEUE, queue) { + RECORDS_QUEUES_DIFFER.store(true, Ordering::Relaxed); + crate::xlog_warn!("D3D12.X: two-pass draws go to a second queue ({queue:#x}): the record buffers are the lists' own from here"); + } +} + +/// `queue` is the first one seen, or the same as it (`seen`: 0 before the first). +fn same_records_queue(seen: &std::sync::atomic::AtomicUsize, queue: usize) -> bool { + match seen.compare_exchange(0, queue, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => true, + Err(first) => first == queue, + } } /// A shared record buffer of at least `need` bytes: buffer, address, bytes. @@ -468,11 +485,11 @@ unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D1 { // local: which way the records go, once each static SAID: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()]; - let one = one_direct_queue(); + let one = !RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed); let on = shared_records_on(); - SAID[(on && one) as usize].call_once(|| crate::xlog_info!("D3D12.X: two-pass records: {} (switch {on}, one direct queue {one})", if on && one { "shared" } else { "a buffer of each list" })); + SAID[(on && one) as usize].call_once(|| crate::xlog_info!("D3D12.X: two-pass records: {} (switch {on}, one queue so far {one})", if on && one { "shared" } else { "a buffer of each list" })); } - if shared_records_on() && one_direct_queue() { + if shared_records_on() && !RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed) { let dev = super::real::list_device(this).ok_or("no device for two-pass buffer")?; let (buf, cap) = shared_record_buffer(&dev, need)?; let first = with(this, |s| !std::mem::replace(&mut s.shared_records, true)); @@ -2551,6 +2568,15 @@ void main(uint t : SV_GroupIndex) { assert!(!pool_keeps(16, 0, 1 << 20)); } + /// A second queue for two-pass draws is told from the first one. + #[test] + fn two_pass_records_are_shared_on_one_queue_only() { + let seen = std::sync::atomic::AtomicUsize::new(0); + assert!(same_records_queue(&seen, 0x10) && same_records_queue(&seen, 0x10)); + assert!(!same_records_queue(&seen, 0x20)); + assert!(same_records_queue(&seen, 0x10)); + } + /// Recordings share one record buffer, a bigger one is made only when that one is too small. #[test] fn gpu_two_pass_record_buffer_is_shared_by_the_recordings() { diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 05d359c08e..b582501543 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -306,6 +306,7 @@ pub fn activity() -> (u64, u64) { pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { EXECUTES.fetch_add(1, Ordering::Relaxed); + super::bind::note_records_queue(queue as usize, lists); { let mut q = QUEUES.lock().unwrap(); if !q.contains(&(queue as usize)) { From 045db31c47084d1ee060081b6fc74694b9b5761f Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 17:48:02 +0100 Subject: [PATCH 033/258] local: the activity thread asks for a removed device --- crates/xcl/src/host.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 5cffd7a752..a8f336458a 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -52,6 +52,8 @@ pub fn host_main(boot_path: &Path) -> i32 { let mut last = snap(); loop { std::thread::sleep(std::time::Duration::from_secs(2)); + // a device removed while every title thread waits: nothing else would ask + crate::hle::d3d12x::real::stop_if_device_removed(); let now = snap(); let d: Vec = now.iter().zip(last).map(|(a, b)| a - b).collect(); crate::xlog_info!( From 6acf8dd59bd66d38d7d8f4f8257a86cf320563c9 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 17:58:00 +0100 Subject: [PATCH 034/258] local: XCL_PSO_SKIP_FILE --- crates/xcl/src/hle/d3d12x/real.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5a707bf1d7..c5af5295ae 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4444,6 +4444,16 @@ fn cap_holds_for_cached() -> bool { *V.get_or_init(|| std::env::var("XCL_PSO_MAX_CACHED").is_ok_and(|v| v.trim() == "1")) } +/// local: records (16 hex digits a line) in the file `XCL_PSO_SKIP_FILE` names +fn skip_listed(record: u64) -> bool { + static L: OnceLock> = OnceLock::new(); + L.get_or_init(|| { + let Some(p) = std::env::var_os("XCL_PSO_SKIP_FILE") else { return Default::default() }; + std::fs::read_to_string(p).unwrap_or_default().lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).collect() + }) + .contains(&record) +} + fn over_build_cap(dxil: usize, cap: usize) -> bool { cap != 0 && dxil > cap } @@ -4476,6 +4486,14 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL if let Some(b) = &cached { copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } + if skip_listed(record) { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 3 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: compute PSO of record {record:016x} not built: in the skip list ({} so far)", n + 1); + } + return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); + } if (cached.is_none() || cap_holds_for_cached()) && over_build_cap(dxil.len(), build_cap_bytes()) { crate::xlog_warn!("D3D12.X: compute PSO of record {record:016x} ({} B DXIL) not built: over XCL_PSO_MAX_KB{}", dxil.len(), if cached.is_none() { " and without a saved blob" } else { " (it has a saved blob)" }); return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); From e6aca81b18ef24114242d7ece63b0d1ceedb5a13 Mon Sep 17 00:00:00 2001 From: IvyNotFound <86932032+IvyNotFound@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:39:12 +0100 Subject: [PATCH 035/258] D3D12.X: XCL_GPU_CULPRIT names the dispatches a stalled queue has not done When the GPU-wait watchdog releases a wait (#505), its lines say which queues wait on which, but not what the GPU is running. With XCL_GPU_CULPRIT=1 every dispatch XCL records (title lists, console-recorded lists, ExecuteIndirect of a translated compute pipeline) is wrapped in WriteBufferImmediate markers, in before and out after, one pair of words per PC list in a readback buffer. At a release the lists whose marker in is above their marker out are logged with the dispatches between the two: console CS (fnv64 of the title's bytecode), PC pipeline and groups. On the retail title of #505 (RTX 5080) this named, at each stall, one list with a run of 1-D dispatches of one CS whose first never finished; not the same CS from run to run. DRED breadcrumbs were tried first: they change the driver's pipeline cache keys, so every pipeline was built again and the title never got past its start. Off by default; without the variable nothing is recorded. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/bind.rs | 8 +- crates/xcl/src/hle/d3d12x/console_list.rs | 5 +- crates/xcl/src/hle/d3d12x/culprit.rs | 279 ++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/list_x.rs | 1 + crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 8 + crates/xcl/src/host.rs | 10 + 7 files changed, 310 insertions(+), 2 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/culprit.rs diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index af9727b82d..7765a23645 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1025,11 +1025,14 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } count(if gfx { DRAWS } else { DISPATCHES }); + // an indirect dispatch: its groups are in the argument buffer (`max` of them) + let mark = if gfx { 0 } else { super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [0, 0, max]) }; if guarded.is_some() { pc(this, sig, max, args, args_off, count_buf, count_off); } else { fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) } + super::culprit::after_dispatch(list, mark); unguard(); } Err(e) => { @@ -1697,7 +1700,10 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis trace_fullscreen(this, pso, [x, y, z]); } bind_abi(this, list, pso, false)?; - super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]) + let mark = super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [x, y, z]); + let r = super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]); + super::culprit::after_dispatch(list, mark); + r } /// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index e75f8d02ac..730866e2e9 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -897,7 +897,10 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let raw = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; list.SetPipelineState(pc); - super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z])?; + let mark = super::culprit::before_dispatch(&list, (*p).pc, real, [x, y, z]); + let r = super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z]); + super::culprit::after_dispatch(&list, mark); + r?; out.dispatches += 1; } _ => out.skipped_dispatches += 1, diff --git a/crates/xcl/src/hle/d3d12x/culprit.rs b/crates/xcl/src/hle/d3d12x/culprit.rs new file mode 100644 index 0000000000..41317a268d --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/culprit.rs @@ -0,0 +1,279 @@ +//! `XCL_GPU_CULPRIT=1` (diagnostics, off by default): which dispatches a stalled queue has not +//! finished. Around every dispatch XCL records (title lists, console-recorded lists, +//! ExecuteIndirect of a translated compute pipeline) the list writes a running number into a +//! readback buffer with `WriteBufferImmediate`: `MARKER_IN` before (the work before it has +//! started), `MARKER_OUT` after (the work before it is done), one pair of words per PC list. +//! When the GPU-wait watchdog releases a wait, a list whose last number in is above its last +//! number out has work that started and is not done: those dispatches are logged with their +//! console compute shader (`fnv64` of the title's CS bytecode, the name of its file in the +//! translated-shader cache) and their groups. +//! +//! DRED breadcrumbs would say the same on a device removal, but they change the driver's +//! pipeline cache keys: every pipeline is built again, and a retail title's start then takes +//! minutes. + +use std::collections::{HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, OnceLock}; +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +pub fn enabled() -> bool { + static E: OnceLock = OnceLock::new(); + *E.get_or_init(|| std::env::var("XCL_GPU_CULPRIT").is_ok_and(|v| v.trim() == "1")) +} + +/// Lists with a slot in the readback buffer (two words each). +const SLOTS: usize = 1 << 14; +/// Dispatches remembered by number (the oldest are forgotten). +const REMEMBERED: usize = 1 << 20; + +/// The console CS of the compute pipelines the title made, by the pointer it holds. +static CS: Mutex>> = Mutex::new(None); + +/// A compute pipeline the title made: its console CS, for the log. +pub unsafe fn note_compute(pso: usize, desc: *const c_void) { + if !enabled() || pso == 0 || !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return; + } + let d = std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + let (p, n) = (d.CS.pShaderBytecode as usize, d.CS.BytecodeLength); + if p == 0 || n == 0 || !crate::gpu::shader::readable(p, n) { + return; + } + let h = crate::gpu::shader::fnv64(std::slice::from_raw_parts(p as *const u8, n)); + CS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, h); +} + +/// The title's pipeline, or the one it stands for (a background build). +fn cs_of(title_pso: usize, pso: usize) -> u64 { + let g = CS.lock().unwrap(); + let Some(m) = g.as_ref() else { return 0 }; + [title_pso, pso, super::pso_async::resolve(title_pso)].iter().find_map(|p| m.get(p)).copied().unwrap_or(0) +} + +struct Markers { + _buf: ID3D12Resource, + gpu: u64, + cpu: *const u32, + /// PC list → its slot + slots: HashMap, + /// dispatch number → (list, what it was) + what: HashMap, + order: VecDeque, +} +// SAFETY: `cpu` is the persistent map of `_buf`, read only under the mutex +unsafe impl Send for Markers {} + +static MARKERS: Mutex> = Mutex::new(None); +static NEXT: AtomicU32 = AtomicU32::new(1); + +unsafe fn make_markers(dev: &ID3D12Device) -> Option { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (SLOTS * 8) as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let mut buf: Option = None; + if let Err(e) = dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut buf) { + crate::xlog_warn!("GPU culprit: no readback buffer for the dispatch markers: {e}"); + return None; + } + let buf = buf?; + let mut p: *mut c_void = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + crate::xlog_info!("GPU culprit: dispatch markers on ({SLOTS} list slots)"); + Some(Markers { gpu: buf.GetGPUVirtualAddress(), _buf: buf, cpu: p as *const u32, slots: HashMap::new(), what: HashMap::new(), order: VecDeque::new() }) +} + +/// Before a dispatch on `list`: a marker in with a new number, which the caller hands to +/// `after_dispatch` once the dispatch is recorded (0: no marker). `groups` `[0, 0, n]`: an +/// indirect one of at most `n` dispatches. +pub unsafe fn before_dispatch(list: &ID3D12GraphicsCommandList, title_pso: usize, pso: usize, groups: [u32; 3]) -> u32 { + if !enabled() { + return 0; + } + let Ok(l2) = list.cast::() else { return 0 }; + let mut g = MARKERS.lock().unwrap(); + if g.is_none() { + let mut dev: Option = None; + if list.GetDevice(&mut dev).is_err() { + return 0; + } + *g = make_markers(&dev.unwrap()); + } + let Some(m) = g.as_mut() else { return 0 }; + let key = list.as_raw() as usize; + let Some(slot) = slot_for(&mut m.slots, key, SLOTS) else { return 0 }; + let id = NEXT.fetch_add(1, Ordering::Relaxed); + let size = match groups { + [0, 0, n] => format!("indirect, up to {n} dispatches"), + [x, y, z] => format!("groups {x}x{y}x{z}"), + }; + m.what.insert(id, (key, format!("cs {:016x}, pipeline {pso:#x}, {size}", cs_of(title_pso, pso)))); + m.order.push_back(id); + if m.order.len() > REMEMBERED { + let old = m.order.pop_front().unwrap(); + m.what.remove(&old); + } + let p = D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: m.gpu + slot as u64 * 8, Value: id }; + l2.WriteBufferImmediate(1, &p, Some(&D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN)); + id +} + +/// After the dispatch: a marker out with its number. +pub unsafe fn after_dispatch(list: &ID3D12GraphicsCommandList, id: u32) { + if id == 0 { + return; + } + let Ok(l2) = list.cast::() else { return }; + let g = MARKERS.lock().unwrap(); + let Some(m) = g.as_ref() else { return }; + let Some(&slot) = m.slots.get(&(list.as_raw() as usize)) else { return }; + let p = D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: m.gpu + slot as u64 * 8 + 4, Value: id }; + l2.WriteBufferImmediate(1, &p, Some(&D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT)); +} + +/// The slot of `list`: its own, or the next free one; none once `cap` lists have one (the list is +/// then not recorded, so every recorded slot stays inside the readback buffer). +fn slot_for(slots: &mut HashMap, list: usize, cap: usize) -> Option { + if let Some(&s) = slots.get(&list) { + return Some(s); + } + let n = slots.len(); + (n < cap).then(|| { + slots.insert(list, n as u32); + n as u32 + }) +} + +/// The lists with work started and not done: (list, last number in, last number out), from +/// each slot's pair of words. A marker in only says that the work before it has started, so a +/// list counts when its number in is above its number out (in and out written out of order +/// otherwise look open). +fn open_lists(slots: &HashMap, words: impl Fn(u32) -> (u32, u32)) -> Vec<(usize, u32, u32)> { + let mut open: Vec<(usize, u32, u32)> = slots + .iter() + .filter_map(|(&list, &slot)| { + let (i, o) = words(slot); + (i > o).then_some((list, i, o)) + }) + .collect(); + open.sort_by_key(|&(_, i, _)| i); + open +} + +/// The dispatches of `list` numbered after `out` up to `in_` that are still remembered. +fn not_done(what: &HashMap, list: usize, in_: u32, out: u32) -> Vec<(u32, &str)> { + ((out + 1)..=in_).filter_map(|id| what.get(&id).filter(|(l, _)| *l == list).map(|(_, s)| (id, s.as_str()))).collect() +} + +/// The watchdog released GPU waits: log the dispatches started and not done (once per burst, +/// 4 s apart, at most 8 times). +pub fn on_watchdog_release() { + static BURSTS: AtomicU32 = AtomicU32::new(0); + static LAST: Mutex> = Mutex::new(None); + if !enabled() { + return; + } + { + let mut l = LAST.lock().unwrap(); + if l.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(4)) { + return; + } + *l = Some(std::time::Instant::now()); + } + if BURSTS.fetch_add(1, Ordering::Relaxed) >= 8 { + return; + } + let g = MARKERS.lock().unwrap(); + let Some(m) = g.as_ref() else { return }; + // SAFETY: slots index the mapped buffer of SLOTS pairs + let open = open_lists(&m.slots, |s| unsafe { (std::ptr::read_volatile(m.cpu.add(s as usize * 2)), std::ptr::read_volatile(m.cpu.add(s as usize * 2 + 1))) }); + crate::xlog_warn!("GPU culprit: {} of {} lists have dispatches started and not done", open.len(), m.slots.len()); + for (list, i, o) in open.iter().take(16) { + let left = not_done(&m.what, *list, *i, *o); + crate::xlog_warn!("GPU culprit: list {list:#x}: marker in #{i}, last marker out #{o}; {} of its dispatches not known done:", left.len()); + for (id, s) in left.iter().take(24) { + crate::xlog_warn!("GPU culprit: #{id}: {s}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Only a list whose number in is above its number out has work in flight, and the + /// dispatches logged for it are its own, after the out. + #[test] + fn a_list_with_a_marker_in_above_its_marker_out_is_open() { + let slots: HashMap = [(0xA, 0), (0xB, 1), (0xC, 2), (0xD, 3)].into_iter().collect(); + // A: done; B: 12 started, 10 done; C: in and out written out of order; D: never ran + let words = |s: u32| [(9, 9), (12, 10), (20, 21), (0, 0)][s as usize]; + assert_eq!(open_lists(&slots, words), vec![(0xB, 12, 10)]); + + let what: HashMap = + [(10, (0xB, "b10".to_string())), (11, (0xA, "a11".to_string())), (12, (0xB, "b12".to_string()))].into_iter().collect(); + assert_eq!(not_done(&what, 0xB, 12, 10), vec![(12, "b12")], "11 belongs to another list"); + } + + /// Once every slot is taken, a new list gets none and is not recorded, and the lists that + /// have one keep it: no slot past the readback buffer is ever read. + #[test] + fn a_list_past_the_last_slot_gets_none() { + let mut slots = HashMap::new(); + assert_eq!(slot_for(&mut slots, 0xA, 2), Some(0)); + assert_eq!(slot_for(&mut slots, 0xB, 2), Some(1)); + assert_eq!(slot_for(&mut slots, 0xC, 2), None); + assert_eq!(slots.len(), 2, "the list without a slot is not recorded"); + assert_eq!(slot_for(&mut slots, 0xA, 2), Some(0)); + assert!(slots.values().all(|&s| (s as usize) < 2)); + } + + /// The markers reach the readback buffer: a list run to its end leaves its numbers in and + /// out equal, so nothing is reported for it. + #[test] + fn gpu_markers_of_a_finished_list_match() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let Some(m) = make_markers(&dev) else { panic!("readback buffer") }; + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let l2: ID3D12GraphicsCommandList2 = list.cast().unwrap(); + for (i, mode) in [(0u64, D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_IN), (4, D3D12_WRITEBUFFERIMMEDIATE_MODE_MARKER_OUT)] { + let p = D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: m.gpu + 8 + i, Value: 77 }; + l2.WriteBufferImmediate(1, &p, Some(&mode)); + } + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + let t = std::time::Instant::now(); + while fence.GetCompletedValue() < 1 { + assert!(t.elapsed().as_secs() < 10, "the list did not finish"); + std::thread::yield_now(); + } + let words = |s: u32| (std::ptr::read_volatile(m.cpu.add(s as usize * 2)), std::ptr::read_volatile(m.cpu.add(s as usize * 2 + 1))); + assert_eq!(words(1), (77, 77)); + let slots: HashMap = [(list.as_raw() as usize, 1)].into_iter().collect(); + assert!(open_lists(&slots, words).is_empty()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 19d0bfdfb6..25cbf74016 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1672,6 +1672,7 @@ fn wake_sync_watchdog() { if had_expired { crate::xlog_warn!("D3D12.X: pending title ID3D12Fences during GPU wait timeout: {}", super::fence_x::pending_summary()); crate::xlog_warn!("D3D12.X: XCL's own queue waits unmet during GPU wait timeout: {}", internal_waits_summary()); + super::culprit::on_watchdog_release(); } }); }); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 1b4dafa888..17fd7c471a 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -14,6 +14,7 @@ pub mod bind; pub mod console_heap; pub mod console_list; mod depth_uav; +pub mod culprit; pub mod device_x; pub mod dxgi_device; mod cpu_writes; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c5af5295ae..4ace843e82 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5718,6 +5718,14 @@ unsafe fn note_translated_compute(hr: HRESULT, ppv: *mut *mut c_void) { } unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let hr = create_compute_pso(this, desc, riid, ppv); + if hr >= 0 && !ppv.is_null() { + super::culprit::note_compute(*ppv as usize, desc); + } + hr +} + +unsafe fn create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_compute_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index a8f336458a..b2cb4cd8bb 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -54,6 +54,16 @@ pub fn host_main(boot_path: &Path) -> i32 { std::thread::sleep(std::time::Duration::from_secs(2)); // a device removed while every title thread waits: nothing else would ask crate::hle::d3d12x::real::stop_if_device_removed(); + // the GPU's work in flight when no frame came for 6 s (`XCL_GPU_CULPRIT=1`) + static IDLE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let frames = crate::hle::d3d12x::present::counters().1; + let o = std::sync::atomic::Ordering::Relaxed; + if SEEN.swap(frames, o) != frames || frames < 100 { + IDLE.store(0, o); + } else if IDLE.fetch_add(1, o) == 2 { + crate::hle::d3d12x::culprit::on_watchdog_release(); + } let now = snap(); let d: Vec = now.iter().zip(last).map(|(a, b)| a - b).collect(); crate::xlog_info!( From 82fe7f49b59cdf476b4d8fa0f99fd9d6b709c097 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 18:00:00 +0100 Subject: [PATCH 036/258] local: indirect group limit from the environment --- crates/xcl/src/hle/d3d12x/bind.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 7765a23645..8f9da9f162 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -651,6 +651,12 @@ void main() { /// a 4K target in groups of 2x2 pixels is 2.1 million. const MOST_GROUPS: u32 = 1 << 22; +/// local: `XCL_INDIRECT_MOST_GROUPS` instead of `MOST_GROUPS` +fn most_groups() -> u32 { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_INDIRECT_MOST_GROUPS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(MOST_GROUPS)) +} + unsafe fn guard_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { static CACHE: Mutex>> = Mutex::new(None); args_pipeline(dev, GUARD_ARGS_HLSL, &CACHE) @@ -672,7 +678,7 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis super::real::uma_window_buffer(src, 12).ok_or("the indirect arguments are not in one memory window")?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; let (dst, dst_off) = scratch_args(this, &dev, 256)?; - let consts: Vec = [0u32, MOST_GROUPS, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let consts: Vec = [0u32, most_groups(), 0].iter().flat_map(|w| w.to_le_bytes()).collect(); let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; From 27002f488350609c968a3796e61e04cf7a82c95d Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 18:06:31 +0100 Subject: [PATCH 037/258] local: XCL_SKIP_MESH --- crates/xcl/src/hle/d3d12x/bind.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8f9da9f162..41cff8ab93 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -801,12 +801,22 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman Ok((dst, dst_off)) } +/// local: `XCL_SKIP_MESH=1` leaves out the draws of the two-pass mesh path (a bisection of GPU hangs) +fn skip_mesh() -> bool { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_SKIP_MESH").is_ok_and(|v| v.trim() == "1")) +} + pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: u32, z: u32) { type PcDm = unsafe extern "system" fn(*mut c_void, u32, u32, u32); let pc_dm: PcDm = std::mem::transmute(super::real::orig_fn(this, 79)); let raw_pso = with(this, |s| s.pso); let pso = pso_for_draw(raw_pso); if let Some(tp) = super::real::two_pass_of(pso) { + if skip_mesh() { + count(DRAWS_SKIPPED); + return; + } let groups = x.saturating_mul(y).saturating_mul(z); if groups == 0 { return; @@ -878,6 +888,10 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let count_at = super::real::console_buffer(count_buf).filter(|&(_, n)| count_off as usize + 4 <= n).map(|(p, _)| p + count_off as usize); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if let Some(tp) = super::real::two_pass_of(pso) { + if skip_mesh() { + count(DRAWS_SKIPPED); + return; + } if let Some(msig) = dispatch_mesh_sig_of(sig) { let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; let run = (|| -> Result<(), String> { From 559c4d39c77a66e56156081bc5c535f3312c2d6c Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 18:11:48 +0100 Subject: [PATCH 038/258] local: culprit markers for mesh draws --- crates/xcl/src/hle/d3d12x/bind.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 41cff8ab93..93c6d102a3 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -837,10 +837,15 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: } } bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; + let m1 = super::culprit::before_dispatch(list, raw_pso, pso, [n, 1, 1]); list.Dispatch(n, 1, 1); + super::culprit::after_dispatch(list, m1); emit_uav_barrier(list, Some(&res_buf)); bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; + // (the mesh pass: what the marker says is its groups; 0x3e2 marks a mesh draw in the log) + let m2 = super::culprit::before_dispatch(list, raw_pso, pso, [n * tp.mesh_groups_per_record, 0x3e2, 1]); pc_dm(this, n * tp.mesh_groups_per_record, 1, 1); + super::culprit::after_dispatch(list, m2); emit_uav_barrier(list, Some(&res_buf)); Ok(()) })(); @@ -921,7 +926,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us for (k, compute) in two_pass_steps(max) { bind_two_pass_stage(this, list, pso, &tp, res_va, compute)?; let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; + let mark = super::culprit::before_dispatch(list, raw_pso, pso, [0, 0, if compute { 1 } else { 0x3e2 }]); pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); + super::culprit::after_dispatch(list, mark); emit_uav_barrier(list, Some(&res_buf)); } Ok(()) From ea9401cf3b4acd2b4d4d72501122059c46353fd5 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 18:15:05 +0100 Subject: [PATCH 039/258] D3D12.X: a vertex or index buffer view at address 0 is a null view --- crates/xcl/src/hle/d3d12x/list_x.rs | 47 ++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 25cbf74016..2fe15eae04 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3595,6 +3595,26 @@ fn pc_va(va: u64) -> u64 { /// it reads there first (`sync_title_buffers`), as the title wrote it by then. (A copy of the /// whole buffer at every bind filled unified memory within two minutes of a retail title's /// menus, and missed what the title wrote after the bind.) +/// A vertex buffer view at address 0 is a null view whatever its size: the console reads zeros +/// from it, and the PC's input assembler would fetch from GPU address 0 (a page fault there is +/// what a removed device reports, `0x887a0006` with "GPU VA 0x0"). +fn null_if_at_zero(mut v: D3D12_VERTEX_BUFFER_VIEW) -> D3D12_VERTEX_BUFFER_VIEW { + if v.BufferLocation == 0 && v.SizeInBytes != 0 { + note_null_buffer("vertex buffer"); + v.SizeInBytes = 0; + } + v +} + +/// A view at address 0 with a size was bound (`null_if_at_zero`). +fn note_null_buffer(what: &str) { + 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: a {what} at address 0 with a size is bound: a null view ({n} so far)"); + } +} + unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: bool) -> u64 { let t = pc_va(va); if t != va || va == 0 || bytes == 0 { @@ -3910,6 +3930,7 @@ pub(super) unsafe extern "system" fn ia_set_vertex_buffers_x(this: *mut c_void, let mut v = views.add(k).read_unaligned(); let title = v.BufferLocation; v.BufferLocation = gpu_va(this, v.BufferLocation, v.SizeInBytes as usize, "vertex buffer", true); + v = null_if_at_zero(v); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); let i = N.fetch_add(1, Ordering::Relaxed); @@ -3957,6 +3978,13 @@ pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, vi s.bindings.index_title = Some((v.BufferLocation, v.SizeInBytes, v.Format.0)); drop(g); v.BufferLocation = gpu_va(this, v.BufferLocation, v.SizeInBytes as usize, "index buffer", true); + if v.BufferLocation == 0 { + note_null_buffer("index buffer"); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { + s.index_buffer = None; + } + return set_index_buffer(this, None); + } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))) { s.index_buffer = Some(v); } @@ -3980,7 +4008,11 @@ pub(super) unsafe extern "system" fn draw_indexed_x(this: *mut c_void, va: u64, }; let bound = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).and_then(|s| s.index_buffer)); sync_title_buffers(this, None, 0, 0, 2); - let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: gpu_va(this, va, count.saturating_mul(stride) as usize, "DrawIndexedX indices", false), SizeInBytes: count.saturating_mul(stride), Format: format }; + let at = gpu_va(this, va, count.saturating_mul(stride) as usize, "DrawIndexedX indices", false); + if at == 0 { + return note_null_buffer("DrawIndexedX index buffer"); + } + let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: count.saturating_mul(stride), Format: format }; set_index_buffer(this, Some(&view)); super::bind::emit_prepared_indexed_draw(&list, count, 1, 0, 0, 0); set_index_buffer(this, bound.as_ref()); @@ -4558,6 +4590,19 @@ pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, hea #[cfg(test)] mod tests { use super::*; + + /// A vertex buffer view at address 0 with a size is a null view; any other is as it was. + #[test] + fn a_vertex_buffer_view_at_address_0_is_null() { + let view = |at: u64, size: u32| D3D12_VERTEX_BUFFER_VIEW { BufferLocation: at, SizeInBytes: size, StrideInBytes: 16 }; + let v = null_if_at_zero(view(0, 4096)); + assert_eq!((v.BufferLocation, v.SizeInBytes, v.StrideInBytes), (0, 0, 16)); + for (at, size) in [(0, 0), (0x1000, 4096), (0x1000, 0)] { + let v = null_if_at_zero(view(at, size)); + assert_eq!((v.BufferLocation, v.SizeInBytes), (at, size)); + } + } + use std::sync::Arc; /// An internal wait shows in the watchdog's summary while its fence is short of the value, From 36ba1764c2600b7656088d6990e3942c0348f7f9 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 18:23:39 +0100 Subject: [PATCH 040/258] local: what the GPU view mirror refuses --- crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 27 +++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs index 0f410f060e..2ce62ec0ae 100644 --- a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -149,7 +149,13 @@ impl State { /// The address a view of `len` bytes at `va` gets when it lies in a GPU view of the title's and /// in no memory window: where the same bytes can be read by a shader. None: it keeps `va`. pub fn base_for(va: usize, len: usize) -> Option { - if !on() || len == 0 || len > MOST { + if !on() || len == 0 { + return None; + } + if len > MOST { + if crate::hle::kernelx::mirrors::source(va).is_some() { + refused(1, va, len); + } return None; } let u = crate::gpu::uma::get()?; @@ -180,6 +186,9 @@ pub fn base_for(va: usize, len: usize) -> Option { if m.tiles() + new.len() > budget() / TILE { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| crate::xlog_warn!("D3D12.X: the buffers of the GPU view take more than XCL_GPU_VIEW_MB: the rest keeps its address")); + drop(mg); + drop(g); + refused(0, t0, t1 - t0); return None; } // whole runs of new tiles at once (a mapping call and a signal for each run) @@ -212,6 +221,22 @@ pub fn base_for(va: usize, len: usize) -> Option { Some(win + (va - first)) } +/// local: what views kept their address (they read zeros): `kind` 0 the budget, 1 longer than +/// `MOST`; the distinct title tiles of each, logged as they grow +fn refused(kind: usize, at: usize, len: usize) { + static SEEN: Mutex; 2]>> = Mutex::new(None); + static VIEWS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + let k = VIEWS[kind].fetch_add(1, Ordering::Relaxed) + 1; + let mut g = SEEN.lock().unwrap(); + let set = &mut g.get_or_insert_with(Default::default)[kind]; + for t in (at & !(TILE - 1)..at + len).step_by(TILE).take(4096) { + set.insert(t); + } + if k.is_power_of_two() { + crate::xlog_info!("D3D12.X: GPU view buffers refused ({}): {k} views, {} distinct tiles ({} MB), latest {at:#x} ({len} B)", ["budget", "longer than MOST"][kind], set.len(), (set.len() * TILE) >> 20); + } +} + /// The pages of the CPU (and pool) side whose writes have to be seen: for the write watch. pub fn sources() -> Vec<(usize, usize)> { MIRRORS.lock().unwrap().as_ref().map_or(Vec::new(), |m| m.by_read.keys().map(|&r| (r, r + TILE)).collect()) From bd4584de9d79402c3a0fe90f6eb7d8dcd4ab2e00 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 18:39:23 +0100 Subject: [PATCH 041/258] local: XCL_LOOP_FILE, past the caches --- crates/xcl/src/gpu/recomp/dxc.rs | 34 ++++++++++++++++++++++++++++++++ crates/xcl/src/gpu/recomp/pso.rs | 5 +++++ 2 files changed, 39 insertions(+) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 243a289b68..9e89b16682 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -917,15 +917,49 @@ pub fn in_cached_only() -> bool { CACHED_ONLY.with(|c| c.get()) } +thread_local! { + /// local: this thread translates a program of `XCL_LOOP_FILE` + static LOOP_LISTED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// local: the record is in `XCL_LOOP_FILE` (and `XCL_LOOP_N` is set) +pub fn loop_record(record: u64) -> bool { + static L: std::sync::OnceLock> = std::sync::OnceLock::new(); + !L.get_or_init(|| { + let Some(p) = std::env::var_os("XCL_LOOP_FILE") else { return Default::default() }; + std::fs::read_to_string(p).unwrap_or_default().lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).collect() + }) + .is_empty() + && L.get().is_some_and(|l| l.contains(&record)) + && std::env::var("XCL_LOOP_N").is_ok() +} + +pub fn with_loop_budget(f: impl FnOnce() -> R) -> R { + let before = LOOP_LISTED.with(|l| l.replace(true)); + let r = f(); + LOOP_LISTED.with(|l| l.set(before)); + r +} + pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, bool), String> { // LOCAL EXPERIMENT: XCL_LOOP_FOR= XCL_LOOP_N=: the loop budget of that program alone let patched; + let listed = LOOP_LISTED.with(|l| l.get()); let src = match (std::env::var("XCL_LOOP_FOR"), std::env::var("XCL_LOOP_N")) { (Ok(t), Ok(n)) if !t.is_empty() && src.contains(&t) => { patched = src.replacen("static uint xcl_budget = 1u << 16;", &format!("static uint xcl_budget = {n}u;"), 1); crate::xlog_info!("[SHADER] loop budget {n} for a program of {} B HLSL ({entry}, {profile})", src.len()); &patched[..] } + (_, Ok(n)) if listed => { + patched = src.replacen("static uint xcl_budget = 1u << 16;", &format!("static uint xcl_budget = {n}u;"), 1); + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let k = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if k <= 3 || k.is_power_of_two() { + crate::xlog_info!("[SHADER] loop budget {n} for a listed program of {} B HLSL ({entry}, {profile}; {k} so far, {} changed)", src.len(), patched.len() != src.len() || patched != src); + } + &patched[..] + } _ => src, }; compile_cached_in(&cache_dir(), src, entry, profile) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 4dd688c9de..082abc519d 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -151,6 +151,11 @@ fn shader_cache() -> &'static Mutex { /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); + // local: `XCL_LOOP_FILE` (records, 16 hex digits a line) translate past the caches with + // `XCL_LOOP_N` iterations a lane + if dxc::loop_record(crate::gpu::shader::fnv64(blob)) { + return dxc::with_loop_budget(|| compile_one()).map(|(c, _)| c); + } if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { return compile_one().map(|(c, _)| c); } From c7a18d8383dc386afc8c1667332837f47ad430b0 Mon Sep 17 00:00:00 2001 From: ivall Date: Wed, 25 Nov 2026 18:48:12 +0100 Subject: [PATCH 042/258] Revert "local: XCL_LOOP_FILE, past the caches" This reverts commit bd4584de9d79402c3a0fe90f6eb7d8dcd4ab2e00. --- crates/xcl/src/gpu/recomp/dxc.rs | 34 -------------------------------- crates/xcl/src/gpu/recomp/pso.rs | 5 ----- 2 files changed, 39 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 9e89b16682..243a289b68 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -917,49 +917,15 @@ pub fn in_cached_only() -> bool { CACHED_ONLY.with(|c| c.get()) } -thread_local! { - /// local: this thread translates a program of `XCL_LOOP_FILE` - static LOOP_LISTED: std::cell::Cell = const { std::cell::Cell::new(false) }; -} - -/// local: the record is in `XCL_LOOP_FILE` (and `XCL_LOOP_N` is set) -pub fn loop_record(record: u64) -> bool { - static L: std::sync::OnceLock> = std::sync::OnceLock::new(); - !L.get_or_init(|| { - let Some(p) = std::env::var_os("XCL_LOOP_FILE") else { return Default::default() }; - std::fs::read_to_string(p).unwrap_or_default().lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).collect() - }) - .is_empty() - && L.get().is_some_and(|l| l.contains(&record)) - && std::env::var("XCL_LOOP_N").is_ok() -} - -pub fn with_loop_budget(f: impl FnOnce() -> R) -> R { - let before = LOOP_LISTED.with(|l| l.replace(true)); - let r = f(); - LOOP_LISTED.with(|l| l.set(before)); - r -} - pub fn compile_cached(src: &str, entry: &str, profile: &str) -> Result<(Vec, bool), String> { // LOCAL EXPERIMENT: XCL_LOOP_FOR= XCL_LOOP_N=: the loop budget of that program alone let patched; - let listed = LOOP_LISTED.with(|l| l.get()); let src = match (std::env::var("XCL_LOOP_FOR"), std::env::var("XCL_LOOP_N")) { (Ok(t), Ok(n)) if !t.is_empty() && src.contains(&t) => { patched = src.replacen("static uint xcl_budget = 1u << 16;", &format!("static uint xcl_budget = {n}u;"), 1); crate::xlog_info!("[SHADER] loop budget {n} for a program of {} B HLSL ({entry}, {profile})", src.len()); &patched[..] } - (_, Ok(n)) if listed => { - patched = src.replacen("static uint xcl_budget = 1u << 16;", &format!("static uint xcl_budget = {n}u;"), 1); - static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let k = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; - if k <= 3 || k.is_power_of_two() { - crate::xlog_info!("[SHADER] loop budget {n} for a listed program of {} B HLSL ({entry}, {profile}; {k} so far, {} changed)", src.len(), patched.len() != src.len() || patched != src); - } - &patched[..] - } _ => src, }; compile_cached_in(&cache_dir(), src, entry, profile) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 082abc519d..4dd688c9de 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -151,11 +151,6 @@ fn shader_cache() -> &'static Mutex { /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); - // local: `XCL_LOOP_FILE` (records, 16 hex digits a line) translate past the caches with - // `XCL_LOOP_N` iterations a lane - if dxc::loop_record(crate::gpu::shader::fnv64(blob)) { - return dxc::with_loop_budget(|| compile_one()).map(|(c, _)| c); - } if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { return compile_one().map(|(c, _)| c); } From 7294c83dbba008968849f86c6827c85d87ab3a2a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:27:50 +0100 Subject: [PATCH 043/258] D3D12.X: label indirect argument passes and fix root UAV bindings Both internal indirect-argument rewrite passes in bind.rs (guard_dispatch_args and make_scaled_args_buffer) emitted the exact DRED breadcrumb pattern (barrier, barrier, marker, Dispatch, barrier, marker) with an unlabeled pipeline and had root-binding and alignment hazards on AMD RDNA4: 1. Neither guard_indirect_pipeline nor scale_indirect_pipeline called dred::label_text (or SetName), so DRED printed the fallback stand-in label. 2. Both reused abi_root_signature (6 root UAVs + directly-indexed heap flags) while leaving slots unbound; SCALE_ARGS_HLSL statically references cnt (u4) via a ternary even when no count buffer is bound. 3. src_va and count_va were passed directly to SetComputeRootUnorderedAccessView even when args_off or count_off was not 16-byte aligned (e.g. 12-byte Dispatch argument strides or 4-byte count offsets). Fix all three: label both pipelines for DRED, give args_pipeline a minimal root signature with every parameter unconditionally bound (binding u4 to consts_va when count is None and guarding cnt.Load with an if), align root UAV bases down to 256 bytes and pass the byte offset via io, guard GUARD_ARGS_HLSL divisions, and validate bundle/stride/offset bounds. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 285 +++++++++++++++++++++++++++--- 1 file changed, 258 insertions(+), 27 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 93c6d102a3..7f727bfd48 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -610,7 +610,10 @@ RWByteAddressBuffer cnt : register(u4); void main(uint tid : SV_DispatchThreadID) { uint count = io.Load(0), stride = io.Load(4), offset = io.Load(8), split = io.Load(12), cap = io.Load(16); if (tid >= count) return; - uint live = io.Load(28) != 0u ? min(count, cnt.Load(io.Load(32))) : count; + uint live = count; + if (io.Load(28) != 0u) { + live = min(count, cnt.Load(io.Load(32))); + } uint s = io.Load(20) + tid * stride, d = io.Load(24) + tid * stride, m = d + count * stride; for (uint i = 0u; i < stride; i += 4u) { uint w = src.Load(s + i); @@ -641,12 +644,21 @@ RWByteAddressBuffer dst : register(u3); void main() { uint at = io.Load(0), most = io.Load(4), to = io.Load(8); uint3 g = src.Load3(at); - bool none = g.x == 0u || g.y == 0u || g.z == 0u; - bool few = !none && all(g <= most) && g.x <= most / g.y && g.x * g.y <= most / g.z; - dst.Store3(to, few ? min(g, 65535u.xxx) : uint3(0u, 0u, 0u)); + uint3 out_g = uint3(0u, 0u, 0u); + if (g.x != 0u && g.y != 0u && g.z != 0u && all(g <= most)) { + if (g.x <= most / g.y) { + if (g.x * g.y <= most / g.z) { + out_g = min(g, 65535u.xxx); + } + } + } + dst.Store3(to, out_g); } "#; +const GUARD_ARGS_DRED_LABEL: &str = "xcl guard_dispatch_args"; +const SCALE_ARGS_DRED_LABEL: &str = "xcl make_scaled_args_buffer"; + /// The groups of an indirect dispatch above which they are not the title's (`GUARD_ARGS_HLSL`): /// a 4K target in groups of 2x2 pixels is 2.1 million. const MOST_GROUPS: u32 = 1 << 22; @@ -657,9 +669,39 @@ fn most_groups() -> u32 { *V.get_or_init(|| std::env::var("XCL_INDIRECT_MOST_GROUPS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(MOST_GROUPS)) } +/// Align a GPU virtual address down to a 256-byte root UAV base and its 4-byte-aligned shader +/// byte offset (`RWByteAddressBuffer::Load` requires 4-byte alignment, and D3D12 root raw UAVs +/// require >= 16-byte alignment; UMA window buffers are 64 KiB-aligned so `va & !255` stays in +/// the same buffer and sparse tile). +fn align_root_uav(va: u64) -> Result<(u64, u32), String> { + if va % 4 != 0 { + return Err(format!("indirect buffer address {va:#x} is not 4-byte aligned")); + } + Ok((va & !255, (va & 255) as u32)) +} + +/// Validate `SCALE_ARGS_HLSL`'s command-buffer layout and return the source byte span (`max * stride`). +fn validate_scale_args_layout(max: u32, stride: u32, mesh_offset: u32) -> Result { + if max == 0 { + return Err("zero indirect commands".into()); + } + if stride == 0 || stride % 4 != 0 { + return Err(format!("invalid indirect command stride {stride}")); + } + if mesh_offset % 4 != 0 || mesh_offset.checked_add(12).is_none_or(|end| end > stride) { + return Err(format!("invalid DispatchMesh argument offset {mesh_offset} for stride {stride}")); + } + let commands = (max as u64).checked_mul(stride as u64).ok_or("indirect command span overflow")?; + let total_dst = commands.checked_mul(2).ok_or("scaled indirect buffer size overflow")?; + if total_dst > u32::MAX as u64 { + return Err(format!("scaled indirect buffer ({total_dst:#x} B) exceeds 32-bit shader offsets")); + } + Ok(commands) +} + unsafe fn guard_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { static CACHE: Mutex>> = Mutex::new(None); - args_pipeline(dev, GUARD_ARGS_HLSL, &CACHE) + args_pipeline(dev, GUARD_ARGS_HLSL, GUARD_ARGS_DRED_LABEL, false, &CACHE) } /// `XCL_INDIRECT_GUARD=0`: indirect dispatches run the groups memory holds, whatever they are. @@ -672,13 +714,17 @@ fn indirect_guard() -> bool { /// scratch block (INDIRECT_ARGUMENT until the caller puts it back to COMMON) and their offset. The /// list's compute root signature and pipeline are the guard's after this. unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize) -> Result<(ID3D12Resource, u64), String> { + if super::list_x::tracked_list_type(this) == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) { + return Err("command bundles cannot record indirect argument barriers".into()); + } let dev = super::real::list_device(this).ok_or("no device")?; let (rs, pso) = guard_indirect_pipeline(&dev)?; let u = crate::gpu::uma::get().ok_or("no unified memory")?; super::real::uma_window_buffer(src, 12).ok_or("the indirect arguments are not in one memory window")?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + let (src_base, src_off) = align_root_uav(src_va)?; let (dst, dst_off) = scratch_args(this, &dev, 256)?; - let consts: Vec = [0u32, most_groups(), 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let consts: Vec = [src_off, most_groups(), 0].iter().flat_map(|w| w.to_le_bytes()).collect(); let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; @@ -688,8 +734,8 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); list.SetComputeRootUnorderedAccessView(0, consts_va); - list.SetComputeRootUnorderedAccessView(2, src_va); - list.SetComputeRootUnorderedAccessView(3, dst.GetGPUVirtualAddress() + dst_off); + list.SetComputeRootUnorderedAccessView(1, src_base); + list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress() + dst_off); list.Dispatch(1, 1, 1); emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); Ok((dst, dst_off)) @@ -697,18 +743,56 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { static CACHE: Mutex>> = Mutex::new(None); - args_pipeline(dev, SCALE_ARGS_HLSL, &CACHE) + args_pipeline(dev, SCALE_ARGS_HLSL, SCALE_ARGS_DRED_LABEL, true, &CACHE) } type ArgsPipelines = Mutex>>; -unsafe fn args_pipeline(dev: &ID3D12Device, hlsl: &str, cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { +/// Minimal compute root signature for XCL's internal argument-rewrite passes: only the root UAVs +/// the shader declares (`u0, u2, u3`, plus `u4` when `with_count` is set) and no heap flags, so +/// every root parameter is unconditionally bound before Dispatch. +unsafe fn args_root_signature(dev: &ID3D12Device, with_count: bool) -> Result { + let regs: &[u32] = if with_count { &[0, 2, 3, 4] } else { &[0, 2, 3] }; + let params: Vec = regs + .iter() + .map(|®| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: reg, + RegisterSpace: 0, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }) + .collect(); + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: 0, + pStaticSamplers: std::ptr::null(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }, + }, + }; + let mut blob: Option = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None).map_err(|e| format!("args root signature serialize: {e}"))?; + let blob = blob.ok_or("args root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("args root signature create: {e}")) +} + +unsafe fn args_pipeline(dev: &ID3D12Device, hlsl: &str, label: &str, with_count: bool, cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { let key = dev.as_raw() as usize; if let Some(pair) = cache.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { return Ok(pair); } let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; - let rs = crate::gpu::recomp::pso::abi_root_signature(dev, false)?; + let rs = args_root_signature(dev, with_count)?; let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, @@ -716,7 +800,9 @@ unsafe fn args_pipeline(dev: &ID3D12Device, hlsl: &str, cache: &'static ArgsPipe }; let res_pso: Result = dev.CreateComputePipelineState(&cdesc); std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); - let pso = res_pso.map_err(|e| format!("scale pso create: {e}"))?; + let pso = res_pso.map_err(|e| format!("{label} pso create: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from(label)); + super::dred::label_text(pso.as_raw() as usize, || label.to_string()); cache.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); Ok((rs, pso)) } @@ -767,35 +853,47 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res /// count (`count`: its UMA address, when the title gave a count buffer). #[allow(clippy::too_many_arguments)] unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, count: Option, max: u32, stride: u32, mesh_offset: u32, split: u32, cap: u32) -> Result<(ID3D12Resource, u64), String> { + if super::list_x::tracked_list_type(this) == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) { + return Err("command bundles cannot record indirect argument barriers".into()); + } + let commands = validate_scale_args_layout(max, stride, mesh_offset)?; let dev = super::real::list_device(this).ok_or("no device")?; let (rs, pso) = scale_indirect_pipeline(&dev)?; let u = crate::gpu::uma::get().ok_or("no unified memory")?; - let commands = (max as u64).saturating_mul(stride as u64); super::real::uma_window_buffer(src, commands as usize).ok_or("the indirect arguments are not in one memory window")?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; - let count_va = match count { + let (src_base, src_off) = align_root_uav(src_va)?; + if (src_off as u64).checked_add(commands).is_none_or(|end| end > u32::MAX as u64) { + return Err("indirect command range exceeds 32-bit shader offsets".into()); + } + let count_bound = match count { Some(p) => { super::real::uma_window_buffer(p, 4).ok_or("the indirect count is not in a memory window")?; - Some(super::real::uma_va_of(p).ok_or("unified memory is not open on the GPU")?) + let va = super::real::uma_va_of(p).ok_or("unified memory is not open on the GPU")?; + Some(align_root_uav(va)?) } None => None, }; let (dst, dst_off) = scratch_args(this, &dev, commands.saturating_mul(2))?; - let consts: Vec = [max, stride, mesh_offset, split, cap, 0, 0, count_va.is_some() as u32, 0].iter().flat_map(|w| w.to_le_bytes()).collect(); + let consts: Vec = [max, stride, mesh_offset, split, cap, src_off, 0, count_bound.is_some() as u32, count_bound.map_or(0, |(_, off)| off)] + .iter() + .flat_map(|w| w.to_le_bytes()) + .collect(); let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + // Bind u4 unconditionally (to `consts_va` when no count buffer is supplied) because + // `SCALE_ARGS_HLSL` statically references `cnt : register(u4)`. + let cnt_base = count_bound.map_or(consts_va, |(base, _)| base); // the title's writes of the arguments before this (`fresh_indirect_arguments`) emit_uav_barrier(list, None); emit_transition(list, &dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); list.SetComputeRootUnorderedAccessView(0, consts_va); - list.SetComputeRootUnorderedAccessView(2, src_va); - list.SetComputeRootUnorderedAccessView(3, dst.GetGPUVirtualAddress() + dst_off); - if let Some(va) = count_va { - list.SetComputeRootUnorderedAccessView(4, va); - } + list.SetComputeRootUnorderedAccessView(1, src_base); + list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress() + dst_off); + list.SetComputeRootUnorderedAccessView(3, cnt_base); list.Dispatch(max.div_ceil(64), 1, 1); emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); Ok((dst, dst_off)) @@ -889,8 +987,14 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let raw_pso = with(this, |s| s.pso); let pso = pso_for_draw(raw_pso); // where the commands are in unified memory (a console buffer's offsets are the title's) - let commands_at = super::real::console_buffer(args).map(|(p, n)| (p + args_off as usize, n.saturating_sub(args_off as usize))); - let count_at = super::real::console_buffer(count_buf).filter(|&(_, n)| count_off as usize + 4 <= n).map(|(p, _)| p + count_off as usize); + let commands_at = super::real::console_buffer(args).and_then(|(p, n)| { + let off = usize::try_from(args_off).ok()?; + (off <= n).then(|| p.checked_add(off).map(|addr| (addr, n - off))).flatten() + }); + let count_at = super::real::console_buffer(count_buf).and_then(|(p, n)| { + let off = usize::try_from(count_off).ok()?; + (off.checked_add(4)? <= n).then(|| p.checked_add(off)).flatten() + }); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if let Some(tp) = super::real::two_pass_of(pso) { if skip_mesh() { @@ -1018,7 +1122,12 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if compute && max == 1 && indirect_guard() && signature_dispatches(sig) { if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { match guard_dispatch_args(this, list, p) { - Ok(g) => guarded = Some(g), + Ok(g) => { + guarded = Some(g); + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + } Err(e) => { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1026,9 +1135,6 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } } - if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { - list.SetPipelineState(real); - } } } let (args, args_off) = guarded.as_ref().map_or((args, args_off), |(b, o)| (b.as_raw() as usize, *o)); @@ -2906,4 +3012,129 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) assert!(taken <= SCRATCH_CAP, "pooled block exceeds recording budget: {taken} > {SCRATCH_CAP}"); } } + + #[test] + fn root_uav_alignment_splits_unaligned_offsets_and_rejects_sub_dword() { + assert_eq!(align_root_uav(0x1_0000_0000).unwrap(), (0x1_0000_0000, 0)); + // 12-byte D3D12_DISPATCH_ARGUMENTS stride: not 16-byte aligned, split into 256-byte base + byte offset + assert_eq!(align_root_uav(0x1_0000_000c).unwrap(), (0x1_0000_0000, 12)); + assert_eq!(align_root_uav(0x1_0000_0018).unwrap(), (0x1_0000_0000, 24)); + assert_eq!(align_root_uav(0x1_0000_01fc).unwrap(), (0x1_0000_0100, 252)); + assert!(align_root_uav(0x1_0000_0001).is_err()); + assert!(align_root_uav(0x1_0000_0002).is_err()); + assert!(align_root_uav(0x1_0000_0003).is_err()); + } + + #[test] + fn scale_args_layout_validation_rejects_malformed_strides_and_offsets() { + assert_eq!(validate_scale_args_layout(4, 16, 4).unwrap(), 64); + assert_eq!(validate_scale_args_layout(1, 12, 0).unwrap(), 12); + assert_eq!(validate_scale_args_layout(8, 28, 16).unwrap(), 224); + assert!(validate_scale_args_layout(0, 16, 4).is_err()); + assert!(validate_scale_args_layout(1, 0, 0).is_err()); + assert!(validate_scale_args_layout(1, 14, 0).is_err()); + assert!(validate_scale_args_layout(1, 16, 2).is_err()); + assert!(validate_scale_args_layout(1, 16, 8).is_err()); + assert!(validate_scale_args_layout(1, 16, u32::MAX).is_err()); + } + + /// Both internal argument-rewrite pipelines build cleanly with their minimal root signatures + /// (no unbound ABI slots) and run with non-16-byte-aligned source/count byte offsets. + #[test] + fn gpu_args_pipelines_build_and_handle_non_16_aligned_offsets() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let (guard_rs, guard_pso) = guard_indirect_pipeline(&dev).expect("guard_indirect_pipeline"); + let (scale_rs, scale_pso) = scale_indirect_pipeline(&dev).expect("scale_indirect_pipeline"); + + let make_cpu_buf = |bytes: u64| -> ID3D12Resource { + let 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: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + }; + + let io_buf = make_cpu_buf(512); + let src_buf = make_cpu_buf(512); + let dst_buf = make_cpu_buf(512); + let map = |b: &ID3D12Resource| -> *mut u32 { + let mut p = std::ptr::null_mut(); + b.Map(0, None, Some(&mut p)).unwrap(); + p as *mut u32 + }; + let (io_p, src_p, dst_p) = (map(&io_buf), map(&src_buf), map(&dst_buf)); + std::ptr::write_bytes(io_p, 0, 128); + std::ptr::write_bytes(src_p, 0, 128); + std::ptr::write_bytes(dst_p, 0xCC, 128); + + // Guard pass reading from 12-byte offset (dword 3, not 16-byte aligned). + let (guard_src_base, guard_src_off) = align_root_uav(src_buf.GetGPUVirtualAddress() + 12).unwrap(); + assert_eq!(guard_src_off, 12); + std::ptr::copy_nonoverlapping([70_000u32, 2, 1].as_ptr(), src_p.add(3), 3); + std::ptr::copy_nonoverlapping([guard_src_off, MOST_GROUPS, 0].as_ptr(), io_p, 3); + + // Scale pass reading 2 commands at 12-byte offset (stride 16, mesh_offset 4) with no count buffer (u4 bound to io). + let (scale_src_base, scale_src_off) = align_root_uav(src_buf.GetGPUVirtualAddress() + 64 + 12).unwrap(); + assert_eq!(scale_src_off, 76); + std::ptr::copy_nonoverlapping([11u32, 20, 1, 1, 22, 3, 2, 1].as_ptr(), src_p.add(19), 8); + std::ptr::copy_nonoverlapping([2u32, 16, 4, 2, 10, scale_src_off, 0, 0, 0].as_ptr(), io_p.add(64), 9); + + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + + list.SetComputeRootSignature(&guard_rs); + list.SetPipelineState(&guard_pso); + list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(1, guard_src_base); + list.SetComputeRootUnorderedAccessView(2, dst_buf.GetGPUVirtualAddress()); + list.Dispatch(1, 1, 1); + + list.SetComputeRootSignature(&scale_rs); + list.SetPipelineState(&scale_pso); + list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress() + 256); + list.SetComputeRootUnorderedAccessView(1, scale_src_base); + list.SetComputeRootUnorderedAccessView(2, dst_buf.GetGPUVirtualAddress() + 256); + list.SetComputeRootUnorderedAccessView(3, io_buf.GetGPUVirtualAddress() + 256); + list.Dispatch(1, 1, 1); + + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 10_000).unwrap(); + + assert_eq!(std::slice::from_raw_parts(dst_p, 3), &[65_535, 2, 1]); + assert_eq!(std::slice::from_raw_parts(dst_p.add(64), 8), &[11, 10, 1, 1, 22, 6, 1, 1]); + assert_eq!(std::slice::from_raw_parts(dst_p.add(72), 8), &[11, 20, 1, 1, 22, 12, 1, 1]); + + io_buf.Unmap(0, None); + src_buf.Unmap(0, None); + dst_buf.Unmap(0, None); + } + } } From 3cda5beadadc51902ac180b83358f03262c01c27 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:29:36 +0100 Subject: [PATCH 044/258] D3D12.X: match 16-bit depth twin steps bit-for-bit in R24G8 sync Console D16_UNORM_S8_UINT (118..=120) depth+UAV twins used R16_UNORM SRVs and a float fullscreen pass. Because 2^24-1 is not a multiple of 65535, hardware R16_UNORM conversion can differ by 1 ULP from float(k) * asfloat(0x37800080) computed by tiled-lighting DepthFunc = EQUAL vertex shaders, rejecting lighting draws on AMD RDNA4. Read the R16_TYPELESS twin as R16_UINT in a dedicated fullscreen PSO returning float(val) * asfloat(0x37800080) for console formats 118..=120, and update the twin-plan unit test. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/depth_uav.rs | 51 +++++++++++++++++++------- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 1e8062d3eb..5ff66d5fe5 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -58,7 +58,10 @@ pub(super) enum DepthSyncKind { /// Two-plane `R32G8X24_TYPELESS` plane 0 (`R32_TYPELESS`): buffer-through `CopyTextureRegion`. BufferThrough, /// Two-plane `R24G8_TYPELESS` plane 0: fullscreen depth-write pass (twin -> depth) and CS copy (depth -> twin). - FullscreenPass { twin_srv_fmt: i32, twin_uav_fmt: i32 }, + /// When `steps` is true (console `D16_UNORM_S8_UINT` family `118..=120`), the `R16_TYPELESS` twin stores + /// 16-bit integer steps of `1/65535` read as `R16_UINT` and multiplied by `asfloat(0x37800080)` so the + /// 24-bit depth matches tiled-lighting `DepthFunc = EQUAL` vertex shaders bit-for-bit. + FullscreenPass { steps: bool, twin_srv_fmt: i32, twin_uav_fmt: i32 }, } /// Twin allocation & sync plan derived from a console resource format. @@ -99,7 +102,8 @@ pub(super) fn plan_for_console_format(console_fmt: u32) -> Option { depth_twin_fmt: DXGI_FORMAT_R16_TYPELESS.0, stencil_twin_fmt: Some(DXGI_FORMAT_R8_TYPELESS.0), depth_sync: DepthSyncKind::FullscreenPass { - twin_srv_fmt: DXGI_FORMAT_R16_UNORM.0, + steps: true, + twin_srv_fmt: DXGI_FORMAT_R16_UINT.0, twin_uav_fmt: DXGI_FORMAT_R16_UNORM.0, }, two_plane: true, @@ -109,6 +113,7 @@ pub(super) fn plan_for_console_format(console_fmt: u32) -> Option { depth_twin_fmt: DXGI_FORMAT_R32_TYPELESS.0, stencil_twin_fmt: Some(DXGI_FORMAT_R8_TYPELESS.0), depth_sync: DepthSyncKind::FullscreenPass { + steps: false, twin_srv_fmt: DXGI_FORMAT_R32_FLOAT.0, twin_uav_fmt: DXGI_FORMAT_R32_FLOAT.0, }, @@ -1417,6 +1422,7 @@ unsafe fn copy_plane_through_buffer( struct SyncPipelines { gfx_rs: ID3D12RootSignature, gfx_pso: ID3D12PipelineState, + gfx_pso_steps: ID3D12PipelineState, cs_rs: ID3D12RootSignature, cs_pso: ID3D12PipelineState, } @@ -1465,6 +1471,14 @@ unsafe fn build_sync_pipelines(dev: &ID3D12Device) -> Option { }\n", "ps_5_0", )?; + let ps_steps = compile_sm5( + "Texture2DArray src : register(t0);\n\ + cbuffer C : register(b0) { uint slice; uint mip; };\n\ + float main(float4 pos : SV_Position) : SV_Depth {\n\ + return float(src.Load(int4(int2(pos.xy), int(slice), int(mip)))) * asfloat(0x37800080);\n\ + }\n", + "ps_5_0", + )?; let cs = compile_sm5( "Texture2DArray src : register(t0);\n\ RWTexture2DArray dst : register(u0);\n\ @@ -1593,12 +1607,21 @@ unsafe fn build_sync_pipelines(dev: &ID3D12Device) -> Option { let create_gfx: CreateGfxPsoFn = std::mem::transmute(real::orig_fn(dev_raw, 10)); let mut gfx_pso_raw = std::ptr::null_mut(); let hr_gfx = create_gfx(dev_raw, &gfx_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut gfx_pso_raw); - ManuallyDrop::drop(&mut gfx_desc.pRootSignature); if hr_gfx < 0 || gfx_pso_raw.is_null() { + ManuallyDrop::drop(&mut gfx_desc.pRootSignature); return None; } let gfx_pso = ID3D12PipelineState::from_raw(gfx_pso_raw); + gfx_desc.PS = D3D12_SHADER_BYTECODE { pShaderBytecode: ps_steps.as_ptr() as *const c_void, BytecodeLength: ps_steps.len() }; + let mut gfx_pso_steps_raw = std::ptr::null_mut(); + let hr_gfx_steps = create_gfx(dev_raw, &gfx_desc, &ID3D12PipelineState::IID as *const _ as *const _, &mut gfx_pso_steps_raw); + ManuallyDrop::drop(&mut gfx_desc.pRootSignature); + if hr_gfx_steps < 0 || gfx_pso_steps_raw.is_null() { + return None; + } + let gfx_pso_steps = ID3D12PipelineState::from_raw(gfx_pso_steps_raw); + let mut cs_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: ManuallyDrop::new(Some(cs_rs.clone())), CS: D3D12_SHADER_BYTECODE { pShaderBytecode: cs.as_ptr() as *const c_void, BytecodeLength: cs.len() }, @@ -1614,7 +1637,7 @@ unsafe fn build_sync_pipelines(dev: &ID3D12Device) -> Option { } let cs_pso = ID3D12PipelineState::from_raw(cs_pso_raw); - Some(SyncPipelines { gfx_rs, gfx_pso, cs_rs, cs_pso }) + Some(SyncPipelines { gfx_rs, gfx_pso, gfx_pso_steps, cs_rs, cs_pso }) } /// Ensure per-resource internal unadopted PC DSV + SRV/UAV descriptor heaps exist for `R24G8_TYPELESS` sync. @@ -1719,13 +1742,15 @@ unsafe fn ensure_pass_heaps( Some((e.pass_dsv_heap.clone()?, e.pass_srv_uav_heap.clone()?)) } -unsafe fn get_pipelines(dev: &ID3D12Device) -> Option<(ID3D12RootSignature, ID3D12PipelineState, ID3D12RootSignature, ID3D12PipelineState)> { +unsafe fn get_pipelines( + dev: &ID3D12Device, +) -> Option<(ID3D12RootSignature, ID3D12PipelineState, ID3D12PipelineState, ID3D12RootSignature, ID3D12PipelineState)> { let key = dev.as_raw() as usize; let mut g = PIPELINES.lock().unwrap(); let map = g.get_or_insert_with(HashMap::new); let entry = map.entry(key).or_insert_with(|| build_sync_pipelines(dev)); let p = entry.as_ref()?; - Some((p.gfx_rs.clone(), p.gfx_pso.clone(), p.cs_rs.clone(), p.cs_pso.clone())) + Some((p.gfx_rs.clone(), p.gfx_pso.clone(), p.gfx_pso_steps.clone(), p.cs_rs.clone(), p.cs_pso.clone())) } /// Execute queued depth+UAV synchronization ops on a `DIRECT` command list. @@ -1803,12 +1828,12 @@ pub(super) unsafe fn execute_syncs(list: *mut c_void, ops: &[SyncOp]) { list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); transition_plane_from(list, res, true, per_plane, 0, STATE_COPY_DEST, depth); } - DepthSyncKind::FullscreenPass { twin_srv_fmt, twin_uav_fmt } => { + DepthSyncKind::FullscreenPass { steps, twin_srv_fmt, twin_uav_fmt } => { let heaps = { let mut g = ENTRIES.lock().unwrap(); g.as_mut().and_then(|m| m.get_mut(&res)).and_then(|e| ensure_pass_heaps(&dev, depth_res, &twin, e, twin_srv_fmt, twin_uav_fmt)) }; - if let (Some((gfx_rs, gfx_pso, _, _)), Some((dsv_heap, srv_heap))) = (get_pipelines(&dev), heaps) { + if let (Some((gfx_rs, gfx_pso, gfx_pso_steps, _, _)), Some((dsv_heap, srv_heap))) = (get_pipelines(&dev), heaps) { let twin_raw = twin.as_raw() as usize; list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATES(STATE_SRV_ALL as i32)); transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_DEPTH_WRITE)); @@ -1826,7 +1851,7 @@ pub(super) unsafe fn execute_syncs(list: *mut c_void, ops: &[SyncOp]) { set_heaps(list, 1, &srv_raw); set_gfx_rs(list, gfx_rs.as_raw()); - set_pso(list, gfx_pso.as_raw()); + set_pso(list, if steps { gfx_pso_steps.as_raw() } else { gfx_pso.as_raw() }); set_topo(list, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST.0 as u32); set_gfx_table(list, 1, srv_heap.GetGPUDescriptorHandleForHeapStart().ptr); let dsv_base = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; @@ -1917,12 +1942,12 @@ pub(super) unsafe fn execute_syncs(list: *mut c_void, ops: &[SyncOp]) { list_x::transition(list, twin_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); transition_plane_from(list, res, true, per_plane, 0, STATE_COPY_SOURCE, depth); } - DepthSyncKind::FullscreenPass { twin_srv_fmt, twin_uav_fmt } => { + DepthSyncKind::FullscreenPass { twin_srv_fmt, twin_uav_fmt, .. } => { let heaps = { let mut g = ENTRIES.lock().unwrap(); g.as_mut().and_then(|m| m.get_mut(&res)).and_then(|e| ensure_pass_heaps(&dev, depth_res, &twin, e, twin_srv_fmt, twin_uav_fmt)) }; - if let (Some((_, _, cs_rs, cs_pso)), Some((_, srv_heap))) = (get_pipelines(&dev), heaps) { + if let (Some((_, _, _, cs_rs, cs_pso)), Some((_, srv_heap))) = (get_pipelines(&dev), heaps) { transition_plane_subs(list, res, true, per_plane, 0, depth, Some(STATE_SRV_ALL)); let srv_raw = srv_heap.as_raw() as usize; let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); @@ -2017,12 +2042,12 @@ mod tests { assert_eq!(d16s8.depth_twin_fmt, 53); assert_eq!(d16s8.stencil_twin_fmt, Some(60)); assert!(d16s8.two_plane); - assert_eq!(d16s8.depth_sync, DepthSyncKind::FullscreenPass { twin_srv_fmt: 56, twin_uav_fmt: 56 }); + assert_eq!(d16s8.depth_sync, DepthSyncKind::FullscreenPass { steps: true, twin_srv_fmt: 57, twin_uav_fmt: 56 }); let d24s8 = plan_for_console_format(45).expect("D24_UNORM_S8_UINT"); assert_eq!(d24s8.depth_twin_fmt, 39); assert_eq!(d24s8.stencil_twin_fmt, Some(60)); - assert_eq!(d24s8.depth_sync, DepthSyncKind::FullscreenPass { twin_srv_fmt: 41, twin_uav_fmt: 41 }); + assert_eq!(d24s8.depth_sync, DepthSyncKind::FullscreenPass { steps: false, twin_srv_fmt: 41, twin_uav_fmt: 41 }); assert!(plan_for_console_format(28).is_none(), "color format has no depth twin plan"); } From b2a2fec99bc9e7500118510dae6050fe21cf0db3 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:29:36 +0100 Subject: [PATCH 045/258] D3D12.X: sync format-aliased writers on enhanced barriers and map resolves Command list #146 (uav_barrier_x) synced depth+UAV enhanced barriers and PlacedUav format-alias pairs, but never checked D3D12_BARRIER_TYPE_TEXTURE transitions on TitlePlaced format-alias writers (such as R9G9B9E5 lighting targets), leaving aliased SRVs stale under enhanced barriers. Add format_alias::filter_enhanced_barriers and call sync_title_writers in uav_barrier_x. Also translate console target formats in resolve_subresource_x and resolve_subresource_region_x via device_x::pc_target_format. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/format_alias.rs | 103 ++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/list_x.rs | 7 ++ 2 files changed, 110 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/format_alias.rs b/crates/xcl/src/hle/d3d12x/format_alias.rs index 81b5aabc1e..874fe0a750 100644 --- a/crates/xcl/src/hle/d3d12x/format_alias.rs +++ b/crates/xcl/src/hle/d3d12x/format_alias.rs @@ -754,6 +754,109 @@ pub(super) fn note_title_transition(res: usize, subresource: u32, before: u32, a } } +/// Inspect enhanced `D3D12_BARRIER_GROUP` texture barriers (`#146`) and collect any tracked +/// `TitlePlaced` writers leaving write access so their format-aliased readers receive a copy. +pub(super) unsafe fn filter_enhanced_barriers(n: u32, groups: *const c_void, writers_to_sync: &mut Vec<(usize, u32)>) { + if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 + || ACTIVE_PAIRS.load(Ordering::Relaxed) == 0 + || n == 0 + || groups.is_null() + { + return; + } + let group_count = (n as usize).min(256); + let group_bytes = group_count.saturating_mul(std::mem::size_of::()); + if !crate::gpu::shader::readable(groups as usize, group_bytes) { + return; + } + let write_access = (D3D12_BARRIER_ACCESS_RENDER_TARGET.0 as u32) + | (D3D12_BARRIER_ACCESS_UNORDERED_ACCESS.0 as u32) + | (D3D12_BARRIER_ACCESS_COPY_DEST.0 as u32); + let read_access = (D3D12_BARRIER_ACCESS_SHADER_RESOURCE.0 as u32) + | (D3D12_BARRIER_ACCESS_COPY_SOURCE.0 as u32); + let is_write_layout = |l: D3D12_BARRIER_LAYOUT| { + matches!( + l, + D3D12_BARRIER_LAYOUT_RENDER_TARGET + | D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_UNORDERED_ACCESS + | D3D12_BARRIER_LAYOUT_COPY_DEST + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_DEST + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_DEST + ) + }; + let is_common_layout = |l: D3D12_BARRIER_LAYOUT| { + matches!( + l, + D3D12_BARRIER_LAYOUT_COMMON + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COMMON + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COMMON + ) + }; + let is_read_layout = |l: D3D12_BARRIER_LAYOUT| { + matches!( + l, + D3D12_BARRIER_LAYOUT_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_SHADER_RESOURCE + | D3D12_BARRIER_LAYOUT_GENERIC_READ + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_GENERIC_READ + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_GENERIC_READ + | D3D12_BARRIER_LAYOUT_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_DIRECT_QUEUE_COPY_SOURCE + | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_SOURCE + ) + }; + let slice = std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, group_count); + for grp in slice { + if grp.Type != D3D12_BARRIER_TYPE_TEXTURE { + continue; + } + let count = (grp.NumBarriers as usize).min(4096); + if count == 0 { + continue; + } + let ptr = grp.Anonymous.pTextureBarriers; + let bytes = count.saturating_mul(std::mem::size_of::()); + if ptr.is_null() || !crate::gpu::shader::readable(ptr as usize, bytes) { + continue; + } + let tbs = std::slice::from_raw_parts(ptr, count); + let g = TABLE.lock().unwrap(); + let Some(t) = g.as_ref() else { + continue; + }; + for tb in tbs { + let discard = (tb.Flags.0 as u32) & (D3D12_TEXTURE_BARRIER_FLAG_DISCARD.0 as u32) != 0 + || tb.LayoutBefore == D3D12_BARRIER_LAYOUT_UNDEFINED; + if discard { + continue; + } + let res: usize = std::mem::transmute_copy(&tb.pResource); + if res == 0 { + continue; + } + let Some(tex) = t.by_res.get(&res) else { + continue; + }; + if tex.owner != Owner::TitlePlaced || !tex.is_writer || !t.pairs.iter().any(|p| p.writer == res) { + continue; + } + let ab = tb.AccessBefore.0 as u32; + let aa = tb.AccessAfter.0 as u32; + let before_write = (ab & write_access != 0) || is_write_layout(tb.LayoutBefore); + let after_write = (aa & write_access != 0) || is_write_layout(tb.LayoutAfter); + let common_to_read = ab == 0 && is_common_layout(tb.LayoutBefore) && ((aa & read_access != 0) || is_read_layout(tb.LayoutAfter)); + if (before_write && !after_write) || common_to_read { + if let Some(st) = tex.uniform_state() { + writers_to_sync.push((res, st)); + } + } + } + } +} + /// Copy all subresources of `src` into `dst` through an intermediate buffer (`CopyTextureRegion`), /// preserving raw texel bits across incompatible DXGI format families (e.g. `R32_UINT` -> /// `R9G9B9E5_SHAREDEXP` or `BCn` <-> `R32G32B32A32_UINT`). diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ce35cfd510..6d69e995a6 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3051,6 +3051,11 @@ pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, ba super::depth_uav::on_global_uav_barrier(); } } + let mut alias_writers = Vec::new(); + super::format_alias::filter_enhanced_barriers(n, barriers, &mut alias_writers); + if !alias_writers.is_empty() { + super::format_alias::sync_title_writers(this, &alias_writers); + } super::format_alias::on_uav_barrier(this, None); } @@ -4516,6 +4521,7 @@ unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: /// command list #19 ResolveSubresource(dst, dst sub, src, src sub, format) (PC #19) pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32) { + let format = super::device_x::pc_target_format(format as u32) as i32; super::present::note_use(dst, super::present::USE_COPY); trace_resolve("ResolveSubresource", dst, src, format, ""); pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) @@ -4525,6 +4531,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds /// mode) (PC #64) #[allow(clippy::too_many_arguments)] pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_void, dst: usize, dst_sub: u32, x: u32, y: u32, src: usize, src_sub: u32, rect: *const windows::Win32::Foundation::RECT, format: i32, mode: i32) { + let format = super::device_x::pc_target_format(format as u32) as i32; super::present::note_use(dst, super::present::USE_COPY); if super::present::trace_frame() { trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); From f09fc6f13f7e6ac9e742aa012a0d20b20e869e56 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:29:36 +0100 Subject: [PATCH 046/258] D3D12.X: resolve GPU-view buffers directly to contiguous UMA backing buffer_view (used by CreateShaderResourceView and CreateUnorderedAccessView on buffer resources) returned empty V# descriptors for placed GPU-view buffers, and dev_create_cbv_x / buffer_words_at only fell back to read-only sparse::gpu_view mirrors (requiring XCL_GPU_VIEW_BUFFERS=1 and skipping UAVs). Add real::resolve_uma_va(va, len) consulting kernelx::mirrors::mapped_source and mirrors::source with per-64-KiB-page contiguity verification inside UMA, wire it ahead of sparse::gpu_view::base_for in buffer_view, dev_create_cbv_x, and buffer_words_at, and add read-only sparse fallback to buffer_view. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 126 +++++++++++++++++++++++------- 1 file changed, 99 insertions(+), 27 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 56a3527f64..754fc291a7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1255,14 +1255,69 @@ fn resource_dim_to_view(r: &D3D12_RESOURCE_DESC) -> i32 { } static NON_UMA_BUFFER_VIEWS: AtomicU64 = AtomicU64::new(0); +static GPU_VIEW_BUFFER_HITS: AtomicU64 = AtomicU64::new(0); + +/// Resolve a console GPU virtual address range `[va, va + len)` to a shader-readable UMA address. +/// Fast path: addresses already inside UMA return as-is. +/// Fallback: consults `kernelx::mirrors::mapped_source` (and paired CPU view `mirrors::source`), +/// verifying every 64 KiB page across `len` maps contiguously into UMA so direct zero-copy +/// SRV/CBV/UAV access never aliases scattered physical pages. +pub(super) fn resolve_uma_va(va: u64, len: usize) -> Option { + if va == 0 { + return None; + } + let u = crate::gpu::uma::get()?; + let start = va as usize; + if u.contains(start) { + if len == 0 || start.checked_add(len - 1).is_some_and(|e| u.contains(e)) { + return Some(va); + } + return None; + } + const MAX_CHECK: usize = 256 << 20; + if len > MAX_CHECK { + return None; + } + let resolve_byte = |addr: usize| -> Option { + match crate::hle::kernelx::mirrors::mapped_source(addr) { + Some(Some(backing)) => Some(backing), + Some(None) => None, + None => crate::hle::kernelx::mirrors::source(addr), + } + }; + let resolved = resolve_byte(start)?; + if !u.contains(resolved) { + return None; + } + if len > 0 { + let end = start.checked_add(len - 1)?; + let resolved_end = resolved.checked_add(len - 1)?; + if !u.contains(resolved_end) { + return None; + } + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; + let mut page = (start & !(PAGE - 1)).checked_add(PAGE); + while let Some(p) = page { + if p > end { + break; + } + let expected = resolved.checked_add(p - start)?; + if resolve_byte(p) != Some(expected) { + return None; + } + page = p.checked_add(PAGE); + } + } + let n = GPU_VIEW_BUFFER_HITS.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!("D3D12.X: resolved GPU-view buffer/root VA {va:#x} -> UMA {resolved:#x} ({len} B, {} resolved)", n + 1); + } + Some(resolved as u64) +} /// V# of a buffer view (raw: 4-byte elements, num_records in bytes; structured / typed: /// stride = element size, num_records in elements); empty when the buffer is not in UMA. -fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool) -> [u32; 4] { - let Some((at, bytes)) = console_buffer(res) else { - note_buffer_view(); - return [0; 4]; - }; +fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, first: u64, n: u32, stride: u32, raw: bool, read_only: bool) -> [u32; 4] { let fmt = crate::gpu::desc::gfx10_format(format).unwrap_or(22); let (stride, elem) = if raw { (0, 4) @@ -1272,10 +1327,30 @@ fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_ let e = crate::gpu::desc::format_bytes(fmt); (e, e) }; - let base = at as u64 + first * elem as u64; - let room = (bytes as u64).saturating_sub(first * elem as u64); - let records = if stride == 0 { (n as u64 * 4).min(room) } else { (n as u64).min(room / stride as u64) }; - crate::gpu::desc::buffer_words(base, stride, records as u32, fmt) + if let Some((at, bytes)) = console_buffer(res) { + let base = at as u64 + first * elem as u64; + let room = (bytes as u64).saturating_sub(first * elem as u64); + let records = if stride == 0 { (n as u64 * 4).min(room) } else { (n as u64).min(room / stride as u64) }; + return crate::gpu::desc::buffer_words(base, stride, records as u32, fmt); + } + if let Some((ta, width)) = title_address(res).and_then(|ta| { + let raw_ptr = res as *mut c_void; + let w = unsafe { ID3D12Resource::from_raw_borrowed(&raw_ptr) }.map(|r| unsafe { r.GetDesc().Width as usize })?; + Some((ta, w)) + }) { + let off = first.saturating_mul(elem as u64); + let room = (width as u64).saturating_sub(off); + let records = if stride == 0 { (n as u64 * 4).min(room) } else { (n as u64).min(room / stride as u64) }; + let view_bytes = if stride == 0 { records } else { records.saturating_mul(stride as u64) } as usize; + let target = (ta as u64).saturating_add(off); + let resolved = resolve_uma_va(target, view_bytes) + .or_else(|| read_only.then(|| super::sparse::gpu_view::base_for(target as usize, view_bytes).map(|b| b as u64)).flatten()); + if let Some(base) = resolved { + return crate::gpu::desc::buffer_words(base, stride, records as u32, fmt); + } + } + note_buffer_view(); + [0; 4] } /// Console buffer → a placed resource in the unified memory heap, so its console address is @@ -1933,15 +2008,14 @@ unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12 return f(this, desc, cpu); }; let (va, size) = desc.as_ref().map_or((0, 0), |d| (d.BufferLocation, d.SizeInBytes)); - let in_uma = crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); - let mirrored = if in_uma { None } else { super::sparse::gpu_view::base_for(va as usize, size as usize) }; - if !in_uma && mirrored.is_none() { - note_buffer_view(); - } - let (va, size) = match mirrored { - Some(b) => (b as u64, size), - None if in_uma => (va, size), - None => (0, 0), + let resolved = resolve_uma_va(va, size as usize) + .or_else(|| super::sparse::gpu_view::base_for(va as usize, size as usize).map(|b| b as u64)); + let (va, size) = match resolved { + Some(b) => (b, size), + None => { + note_buffer_view(); + (0, 0) + } }; super::console_heap::write(&slot, &crate::gpu::desc::cbv_words(va, size)); } @@ -2320,7 +2394,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; - return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true)); } let rdesc = r.GetDesc(); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { @@ -2403,13 +2477,11 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI (false, s) => (s, s), }; let records = if stride == 0 { n.saturating_mul(4) } else { n }; - let mut base = va + first * elem as u64; - if read_only { - let len = (n as u64).saturating_mul(elem as u64); - if let Some(b) = super::sparse::gpu_view::base_for(base as usize, len as usize) { - base = b as u64; - } - } + let target = va.saturating_add(first.saturating_mul(elem as u64)); + let len = (n as u64).saturating_mul(elem as u64) as usize; + let base = resolve_uma_va(target, len) + .or_else(|| read_only.then(|| super::sparse::gpu_view::base_for(target as usize, len).map(|b| b as u64)).flatten()) + .unwrap_or(target); crate::gpu::desc::buffer_words(base, stride, records, fmt) } @@ -2678,7 +2750,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, if let Some(v) = uav_desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; - return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw)); + return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, false)); } // UAV dimensions: 1 buffer, 2 tex1d, 3 tex1d array, 4 tex2d, 5 tex2d array, 8 tex3d let (format, dim, array, mip) = match uav_desc.as_ref() { From cf931479b57dee6f6f3377587e5a133af6d3c21c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:33:32 +0100 Subject: [PATCH 047/258] kernelx: batch contiguous sparse-window commits in physical-page mapping map_pages and move_away previously called sparse::committed(at, PHYS_PAGE) inside the per-page loop. When a large physical-page allocation (~2+ GB) lands in a sparse UMA window (such as Series S / lockhart TileHeap), this issued ~34,000 separate 64 KiB UpdateTileMappings + queue.Signal calls (>31 s at ~64 MB/s), tripping the title's 30 s init watchdog. Coalesce contiguous 64 KiB sparse-window commits in SparseCommitBatch across map_pages, move_away_batched, MapTitlePhysicalPages, and XMemMapPhysicalPagesScatter, flushing early on any overlapping decommit/unmap. Reduces ~34,000 UpdateTileMappings calls to one batched commit per contiguous run (~34 pool-heap calls, <100 ms). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/kernelx.rs | 112 +++++++++++++++++++++++++++++++--- 1 file changed, 105 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 2f0a243892..1711afb104 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1435,12 +1435,74 @@ unsafe fn release_at(at: usize) { mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT); } +/// Coalesces contiguous 64 KiB sparse-window commits inside `map_pages` / scatter calls so a +/// multi-gigabyte `XMemMapPhysicalPages` issues one `sparse::committed(start, len)` per run +/// instead of one `UpdateTileMappings` + `Signal` per page. +#[derive(Default)] +struct SparseCommitBatch { + run: Option<(usize, usize)>, +} + +impl SparseCommitBatch { + fn push_with(&mut self, at: usize, mut emit: impl FnMut(usize, usize)) { + if let Some((start, len)) = &mut self.run { + if start.checked_add(*len) == Some(at) { + *len += PHYS_PAGE; + return; + } + } + if let Some((start, len)) = self.run.take() { + emit(start, len); + } + self.run = Some((at, PHYS_PAGE)); + } + + fn flush_if_contains_with(&mut self, addr: usize, mut emit: impl FnMut(usize, usize)) { + if let Some((start, len)) = self.run { + if addr >= start && addr < start.saturating_add(len) { + self.run = None; + emit(start, len); + } + } + } + + fn flush_with(&mut self, mut emit: impl FnMut(usize, usize)) { + if let Some((start, len)) = self.run.take() { + emit(start, len); + } + } + + unsafe fn push(&mut self, at: usize) { + self.push_with(at, |a, n| crate::hle::d3d12x::sparse::committed(a, n)); + } + + unsafe fn flush_if_contains(&mut self, addr: usize) { + self.flush_if_contains_with(addr, |a, n| crate::hle::d3d12x::sparse::committed(a, n)); + } + + unsafe fn flush(&mut self) { + self.flush_with(|a, n| crate::hle::d3d12x::sparse::committed(a, n)); + } +} + /// A page mapped away from home (at `old`) that the title maps at `at`: what `old` holds copied /// to `at`, and `old` given up – its home is not used. By way of its home a move was four /// commits and decommits, each a tile mapping in a sparse window: a retail game moving pages one /// at a time after its first movie spent 20 s in them and its watchdog ended it. False: the page /// was never used at `old` (its home holds it, zeros) and is not mapped anywhere now. +#[cfg(test)] unsafe fn move_away(away: &mut Away, old: usize, at: usize, page: usize, in_uma: bool) -> Result { + move_away_batched(away, old, at, page, in_uma, None) +} + +unsafe fn move_away_batched( + away: &mut Away, + old: usize, + at: usize, + page: usize, + in_uma: bool, + mut sparse_batch: Option<&mut SparseCommitBatch>, +) -> Result { if lazy::unmark(old) { away.at.remove(&old); away.page.remove(&page); @@ -1454,7 +1516,13 @@ unsafe fn move_away(away: &mut Away, old: usize, at: usize, page: usize, in_uma: away.page.remove(&page); std::ptr::copy_nonoverlapping(old as *const u8, at as *mut u8, PHYS_PAGE); if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { - crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); + match sparse_batch.as_deref_mut() { + Some(batch) => batch.push(at), + None => crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE), + } + } + if let Some(batch) = sparse_batch { + batch.flush_if_contains(old); } release_at(old); away.at.insert(at, page); @@ -1589,7 +1657,9 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _ } let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); - let r = map_pages(away, va, n, arr); + let mut sparse_batch = SparseCommitBatch::default(); + let r = map_pages(away, va, n, arr, &mut sparse_batch); + sparse_batch.flush(); give_back_homes(away); r } @@ -1607,8 +1677,9 @@ unsafe fn map_aliased(va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void } /// `MapTitlePhysicalPages` with `AWAY` held; the homes it moves away are given back by the -/// caller (`give_back_homes`). -unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void { +/// caller (`give_back_homes`), and contiguous sparse-window commits are flushed by the caller +/// (`sparse_batch.flush()`). +unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize, sparse_batch: &mut SparseCommitBatch) -> *mut c_void { note_mapping_at(va as usize); if crate::gpu::uma::get().is_none() || n == 0 || (va.is_null() && arr.is_null()) { fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); @@ -1659,6 +1730,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) let at = base + i * PHYS_PAGE; // what was mapped at `at` goes; the new page is written down once it is in place away.title.remove(&at); + sparse_batch.flush_if_contains(at); if unmap_away(away, at, &(0..0)) { (at_run, home_run) = Default::default(); } @@ -1668,7 +1740,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) if let Some(&old) = away.page.get(&p) { // (a move commits `at` and decommits `old`, which may lie in a run already answered: // both runs go – #556) - match move_away(away, old, at, p, in_uma(at)) { + match move_away_batched(away, old, at, p, in_uma(at), Some(sparse_batch)) { Ok(true) => { (at_run, home_run) = Default::default(); away.title.insert(at, p); @@ -1707,7 +1779,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize) std::ptr::write_bytes(at as *mut u8, 0, PHYS_PAGE); // a page never used: zeros } if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) { - crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE); + sparse_batch.push(at); } away.at.insert(at, p); away.page.insert(p, at); @@ -1748,7 +1820,9 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut } let mut g = AWAY.lock().unwrap(); let away = g.get_or_insert_with(Away::default); - let ok = (0..n).all(|i| !map_pages(away, *addresses.add(i), 1, page(i)).is_null()); + let mut sparse_batch = SparseCommitBatch::default(); + let ok = (0..n).all(|i| !map_pages(away, *addresses.add(i), 1, page(i), &mut sparse_batch).is_null()); + sparse_batch.flush(); give_back_homes(away); ok as BOOL } @@ -3103,6 +3177,30 @@ mod tests { } } + #[test] + fn sparse_commit_batch_coalesces_contiguous_pages_and_flushes_on_overlap() { + let mut batch = SparseCommitBatch::default(); + let mut emitted = Vec::new(); + let base = 0x1_0000_0000usize; + // 4 contiguous 64 KiB pages coalesce into a single 256 KiB run. + for i in 0..4 { + batch.push_with(base + i * PHYS_PAGE, |a, n| emitted.push((a, n))); + } + assert!(emitted.is_empty()); + // Discontiguous page flushes the first run and starts a second. + batch.push_with(base + 10 * PHYS_PAGE, |a, n| emitted.push((a, n))); + assert_eq!(emitted, vec![(base, 4 * PHYS_PAGE)]); + batch.push_with(base + 11 * PHYS_PAGE, |a, n| emitted.push((a, n))); + // Unrelated address does not flush; overlapping address flushes immediately. + batch.flush_if_contains_with(base + 9 * PHYS_PAGE, |a, n| emitted.push((a, n))); + assert_eq!(emitted.len(), 1); + batch.flush_if_contains_with(base + 10 * PHYS_PAGE, |a, n| emitted.push((a, n))); + assert_eq!(emitted, vec![(base, 4 * PHYS_PAGE), (base + 10 * PHYS_PAGE, 2 * PHYS_PAGE)]); + // Trailing flush on empty batch is a no-op. + batch.flush_with(|a, n| emitted.push((a, n))); + assert_eq!(emitted.len(), 2); + } + /// Timing (`--ignored --nocapture`; `XCL_SCATTER_PAGES=4096,8192`): pages written at their /// home, scattered from there into a reservation in one call, scattered again in reverse, /// and mapped back home. From 40f499a7e99ab382dbc2d38a2586c868eb14689c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:33:35 +0100 Subject: [PATCH 048/258] DirectStorage: defer half-full auto-submit for heap page-array batches Titles can enqueue DirectStorage requests with heap-backed DestinationPageArray pointers, populate/map the physical page lists, and then call Submit(). Auto-submitting the queue at half capacity let worker threads run mid-batch against unpopulated page entries, dropping streamed geometry. When the pending queue contains any non-stack DestinationPageArray request, suppress the half-capacity auto-submit and wait for explicit Submit() (or full queue capacity), while keeping normal half-capacity auto-submit for memory, file, and stack-backed page-list requests. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/dstorage.rs | 44 ++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 01be8299b4..b9aab9ed6c 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -1205,8 +1205,19 @@ impl QueueInner { } } + fn should_auto_submit(entries: &[Entry], capacity: usize) -> bool { + // Heap-backed `DestinationPageArray` batches may still have their physical-page lists + // populated before the title calls `Submit()`: never auto-submit them mid-batch at half + // capacity, only if the queue actually fills. + let has_deferred_pages = entries + .iter() + .any(|e| matches!(e, Entry::Request { dest_pages: Some(_), dest_on_stack: false, .. })); + let limit = if has_deferred_pages { capacity } else { (capacity / 2).max(1) }; + entries.len() >= limit + } + fn enqueue(self: &Arc, e: Entry) { - let n = { + let auto = { let mut p = self.pending.lock().unwrap(); if self.closed.load(Ordering::Acquire) { return; @@ -1217,10 +1228,9 @@ impl QueueInner { } } p.entries.push(e); - p.entries.len() + Self::should_auto_submit(&p.entries, self.capacity) }; - // as on PC: a half-full queue submits by itself - if n >= (self.capacity / 2).max(1) { + if auto { self.submit(); } } @@ -1235,7 +1245,7 @@ impl QueueInner { } fn enqueue_numbered(self: &Arc, entry: impl FnOnce(u64) -> Entry) { - let n = { + let auto = { let mut p = self.pending.lock().unwrap(); if self.closed.load(Ordering::Acquire) { return; @@ -1243,9 +1253,9 @@ impl QueueInner { let seq = p.next_seq; p.next_seq += 1; p.entries.push(entry(seq)); - p.entries.len() + Self::should_auto_submit(&p.entries, self.capacity) }; - if n >= (self.capacity / 2).max(1) { + if auto { self.submit(); } } @@ -2864,4 +2874,24 @@ mod tests { status_release(s); } } + + #[test] + fn deferred_page_array_batch_does_not_auto_submit_at_half_capacity() { + let mk = |dest_pages: Option>, dest_on_stack: bool| Entry::Request { + seq: 1, + req: Request::parse(&[0u8; REQUEST_BYTES]), + file: None, + dest_pages, + dest_on_stack, + src_pages: None, + }; + // Regular requests still auto-submit at half capacity (capacity = 4 -> 2). + assert!(QueueInner::should_auto_submit(&[mk(None, false), mk(None, false)], 4)); + // Stack-backed page arrays are already snapshotted at enqueue, so half-capacity stays on. + assert!(QueueInner::should_auto_submit(&[mk(Some(vec![1]), true), mk(None, false)], 4)); + // Heap-backed page arrays wait until Submit() or full capacity. + assert!(!QueueInner::should_auto_submit(&[mk(Some(vec![1]), false), mk(None, false)], 4)); + assert!(!QueueInner::should_auto_submit(&[mk(Some(vec![1]), false), mk(None, false), mk(None, false)], 4)); + assert!(QueueInner::should_auto_submit(&[mk(Some(vec![1]), false), mk(None, false), mk(None, false), mk(None, false)], 4)); + } } From 8b0db35d0152c0d035a34fb974332ea33c0dda94 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:33:38 +0100 Subject: [PATCH 049/258] Recompiler: ignore non-source SRC0 on VOP3 v_interp_* literal scan VOP3 v_interp_p1ll_f16, v_interp_p1lv_f16, and v_interp_p2_f16 encode (high << 8) | (chan << 6) | attr in SRC0 (OPR_ATTR). For attr63.w (attr=63, chan=3, high=0), SRC0 == 0xFF == 255, which rdna2::decode's VALU fallback literal scan mistook for a 32-bit inline literal and consumed the following instruction word. Skip fields explicitly typed as non-source operands (!is_src_type) during the VALU fallback literal scan while keeping v_nop's empty-operand hidden shader hash literals intact. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/rdna2.rs | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/rdna2.rs b/crates/xcl/src/gpu/rdna2.rs index 45430f355a..202aa941cc 100644 --- a/crates/xcl/src/gpu/rdna2.rs +++ b/crates/xcl/src/gpu/rdna2.rs @@ -222,9 +222,14 @@ pub fn decode(code: &[u8], pc: u64) -> Result { && o.field.and_then(|f| field_value(enc, &base_words, f)) == Some(255) }); // VALU: the literal is fetched whenever a source field selects it, even one the - // opcode does not read – console compilers hide the shader hash in v_nop literals + // opcode does not read – console compilers hide the shader hash in v_nop literals. + // Skip fields whose operand definition is a non-source index (e.g. VOP3 v_interp_* + // SRC0 = OPR_ATTR, where attr63.w encodes 0xFF == 255). if !has_literal && is_valu(enc) { - has_literal = ["SRC0", "SRC1", "SRC2"].iter().any(|f| field_value(enc, &base_words, f) == Some(255)); + has_literal = ["SRC0", "SRC1", "SRC2"].iter().any(|f| { + !ienc.operands.iter().any(|o| !o.implicit && o.field == Some(*f) && !is_src_type(o.ty)) + && field_value(enc, &base_words, f) == Some(255) + }); } } if has_literal { @@ -1291,4 +1296,28 @@ mod tests { assert!(total > 2500 && modified > 250, "the SDWA tests are not all there: {total} lines, {modified} with source or output modifiers"); assert!(wrong.is_empty(), "{} of {total} SDWA lines differ from LLVM's, the first: {:?}", wrong.len(), &wrong[..wrong.len().min(8)]); } + + #[test] + fn vop3_interp_attr63_w_does_not_consume_literal() { + // VOP3 v_interp_p1ll_f16 / v_interp_p2_f16 encode (high<<8)|(chan<<6)|attr in SRC0. + // attr63.w (high=0, chan=3, attr=63) yields SRC0 == 0xFF == 255, which is OPR_ATTR + // rather than a 32-bit inline literal. + for name in ["V_INTERP_P1LL_F16", "V_INTERP_P2_F16"] { + let mut bytes = encode(name, "ENC_VOP3", &[("VDST", 1), ("SRC0", 0xFF), ("SRC1", 256), ("SRC2", 257)], None).unwrap(); + assert_eq!(bytes.len(), 8); + bytes.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let d = decode(&bytes, 0).unwrap(); + assert_eq!(d.inst.name, name); + assert_eq!(d.len, 8, "{name} attr63.w must not consume a 32-bit literal"); + assert_eq!(d.literal, None); + let next = decode(&bytes[d.len..], d.len as u64).unwrap(); + assert_eq!(next.inst.name, "S_ENDPGM"); + } + // Console compilers still hide shader hashes in v_nop with SRC0 == 255. + let vnop = encode("V_NOP", "ENC_VOP1", &[("SRC0", 255)], Some(0x1234_5678)).unwrap(); + let d = decode(&vnop, 0).unwrap(); + assert_eq!(d.inst.name, "V_NOP"); + assert_eq!(d.len, 8); + assert_eq!(d.literal, Some(0x1234_5678)); + } } From 85a9480d2b86c52f28664799ecefad71e0ca2f88 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:34:10 +0100 Subject: [PATCH 050/258] Recompiler: emit global UAV fence on s_barrier in UAV-writing or glc shaders On AMD RDNA4, GroupMemoryBarrierWithGroupSync (barrier::GROUP_SYNC) flushes only LDS/TGSM, not L0/L1 global device memory. Shaders that perform global or image UAV stores, atomics, or GLC=1 coherent loads and synchronize with s_barrier can otherwise observe stale cache lines across waves/workgroups, causing infinite spin-wait loops (0x887A0006 TDR) or corrupted buffers. Pre-scan shaders via has_uav_write_or_glc and upgrade s_barrier to barrier::ALL_SYNC (Direct DXIL) and AllMemoryBarrierWithGroupSync / AllMemoryBarrier (HLSL) when the program writes/atomics global or image UAVs or uses GLC=1, leaving pure-LDS/ALU shaders on GROUP_SYNC. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/core_tests.rs | 38 +++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 1 + crates/xcl/src/gpu/dxil/lower.rs | 9 ++++++- crates/xcl/src/gpu/recomp/emit.rs | 38 +++++++++++++++++++++++---- 4 files changed, 80 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index e9be9d3444..e619fc3954 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -632,3 +632,41 @@ fn dot8_u32_u4_unclamped_lowers_to_dot4_add_u8_packed() { let dis_clamped = super::validate::disassemble(&dxil_clamped).unwrap(); assert!(!dis_clamped.contains("dot4AddPacked"), "clamped dot8 should stay 64-bit saturating:\n{dis_clamped}"); } + +#[test] +fn s_barrier_emits_all_sync_when_shader_writes_uav_or_uses_glc() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + + // Pure ALU + s_barrier keeps GROUP_SYNC (mode 9 = SYNC_THREAD_GROUP | TGSM_FENCE). + let lds_only = prog(&[ + ("S_BARRIER", "ENC_SOPP", &[], None), + ]); + let dxil_lds = translate(&lds_only, ko).expect("lds-only barrier translates"); + super::validate::validate(&dxil_lds).expect("lds-only validates"); + if let Ok(dis) = super::validate::disassemble(&dxil_lds) { + assert!(dis.contains("dx.op.barrier(i32 80, i32 9)"), "expected GROUP_SYNC (9):\n{dis}"); + assert!(!dis.contains("dx.op.barrier(i32 80, i32 11)"), "unexpected ALL_SYNC (11):\n{dis}"); + } + + // Shader with a global store upgrades s_barrier to ALL_SYNC (mode 11 = GROUP_SYNC | UAV_FENCE_GLOBAL). + let with_store = prog(&[ + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 1), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("S_BARRIER", "ENC_SOPP", &[], None), + ]); + let dxil_store = translate(&with_store, ko).expect("store + barrier translates"); + super::validate::validate(&dxil_store).expect("store + barrier validates"); + if let Ok(dis) = super::validate::disassemble(&dxil_store) { + assert!(dis.contains("dx.op.barrier(i32 80, i32 11)"), "expected ALL_SYNC (11):\n{dis}"); + } + + // Shader with a GLC=1 load also upgrades s_barrier to ALL_SYNC (mode 11). + let with_glc = prog(&[ + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 1), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 0), ("GLC", 1)], None), + ("S_BARRIER", "ENC_SOPP", &[], None), + ]); + let dxil_glc = translate(&with_glc, ko).expect("glc load + barrier translates"); + super::validate::validate(&dxil_glc).expect("glc load + barrier validates"); + if let Ok(dis) = super::validate::disassemble(&dxil_glc) { + assert!(dis.contains("dx.op.barrier(i32 80, i32 11)"), "expected ALL_SYNC (11) for GLC load:\n{dis}"); + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 3fe8c6ce4a..6adb05d0a2 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -529,6 +529,7 @@ impl Lw { track_frexp_denorm: crate::gpu::recomp::emit::tracks_frexp_f32_denorm(insts), has_f64_round_op: false, img_writes: crate::gpu::recomp::emit::image_write_srsrcs(insts), + barrier_uav_fence: crate::gpu::recomp::emit::has_uav_write_or_glc(insts), exec_cache: HashMap::new(), xs: None, xw: None, diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..a0af2c8f88 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -216,6 +216,8 @@ pub struct Lw { pub has_f64_round_op: bool, /// the T# SGPRs of the program's image stores and atomics (`recomp::emit::image_write_srsrcs`) pub img_writes: Vec, + /// program writes/atomics global or image UAVs or uses `GLC=1`: `s_barrier` emits `ALL_SYNC` + pub barrier_uav_fence: bool, /// static samplers bound so far: (S#, comparison, handle) at `s, space1` pub static_used: Vec<([u32; 4], bool, super::ops::Sampler)>, pub sampler_base: u32, @@ -1016,7 +1018,12 @@ impl Lw { fn sopp(&mut self, d: &Decoded, name: &str) -> LResult<()> { match name { "s_barrier" => { - self.s.barrier(super::ops::barrier::GROUP_SYNC); + let mode = if self.barrier_uav_fence { + super::ops::barrier::ALL_SYNC + } else { + super::ops::barrier::GROUP_SYNC + }; + self.s.barrier(mode); Ok(()) } "s_round_mode" => { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 64acd2d57b..f90c7e3956 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -72,12 +72,32 @@ pub(super) struct Em { /// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits, /// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`. safe_barrier: bool, + /// program writes/atomics global or image UAVs or uses `GLC=1`: `s_barrier` must also flush + /// global device memory (`AllMemoryBarrierWithGroupSync` / `AllMemoryBarrier`) on RDNA4. + barrier_uav_fence: bool, /// the T# SGPRs of the program's image stores and atomics (`image_write_srsrcs`) img_writes: Vec, /// compute program needs `globallycoherent` on flat memory windows (`needs_coherent_mem`) pub coherent_mem: bool, } +/// True when the program writes or atomically updates global/image memory or performs a +/// globally-coherent (`GLC=1`) memory access. On RDNA4, `s_barrier` in such shaders must emit +/// a global UAV fence (`AllMemoryBarrierWithGroupSync` / `barrier::ALL_SYNC`) so L0/L1 caches +/// become visible across waves/workgroups alongside LDS/TGSM. +pub fn has_uav_write_or_glc(insts: &[Decoded]) -> bool { + insts.iter().any(|d| { + if !matches!(d.enc.name, "ENC_MUBUF" | "ENC_MTBUF" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_SMEM") { + return false; + } + if rdna2::field_value(d.enc, &d.words, "GLC") == Some(1) { + return true; + } + let n = d.inst.name; + n.contains("STORE") || n.contains("ATOMIC") + }) +} + /// The T# SGPRs (SRSRC) of a program's image stores and atomics, at most 16, sorted. An /// image_load reads through the UAV (`tw0 + 1`) where the invocation stored to the same image /// before (`xcl_iw{srsrc}` holds `tw0 + 1` of the last such store): the SRV need not see a @@ -624,6 +644,7 @@ impl Em { dynamic_f16_rm: false, track_frexp_denorm: false, safe_barrier: false, + barrier_uav_fence: false, img_writes: Vec::new(), coherent_mem: false, } @@ -645,6 +666,7 @@ impl Em { pub fn configure_round_modes(&mut self, insts: &[Decoded], stop_at_endpgm: bool) { self.track_frexp_denorm = tracks_frexp_f32_denorm(insts); self.img_writes = image_write_srsrcs(insts); + self.barrier_uav_fence = has_uav_write_or_glc(insts); let mut writes_nonzero_dp = false; let mut has_s_barrier = false; for d in insts { @@ -1300,20 +1322,26 @@ impl Em { match name { "s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" => Flow::End, "s_barrier" => { + let sync_fn = if self.barrier_uav_fence { "AllMemoryBarrierWithGroupSync" } else { "GroupMemoryBarrierWithGroupSync" }; + let mem_fn = if self.barrier_uav_fence { "AllMemoryBarrier" } else { "GroupMemoryBarrier" }; if self.x64() && matches!(self.opt.mode, Mode::Geometry(_)) { // split ES+GS: the GS phase runs in the lower hardware wave alone (one console // wave: nothing to wait for), a group barrier there would wait for the other - self.line("if (xcl_es_phase) GroupMemoryBarrierWithGroupSync();"); + self.line(&format!("if (xcl_es_phase) {sync_fn}();")); } else if matches!(self.opt.mode, Mode::Compute(_) | Mode::Mesh(_)) { if self.safe_barrier { - self.line("xcl_s_barrier();"); + if self.barrier_uav_fence { + self.line("AllMemoryBarrier(); xcl_s_barrier(); AllMemoryBarrier();"); + } else { + self.line("xcl_s_barrier();"); + } } else if self.compute_or_mesh_hw_waves() == Some(1) { - self.line("GroupMemoryBarrier();"); + self.line(&format!("{mem_fn}();")); } else { - self.line("GroupMemoryBarrierWithGroupSync();"); + self.line(&format!("{sync_fn}();")); } } else if matches!(self.opt.mode, Mode::Kernel | Mode::Geometry(_)) { - self.line("GroupMemoryBarrierWithGroupSync();"); + self.line(&format!("{sync_fn}();")); } Flow::Next } From f44e17b7889e5927fb5ccb1686dd81c53e01ee09 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:34:29 +0100 Subject: [PATCH 051/258] Recompiler: prefer live lanes in Direct DXIL PS v_readfirstlane and wave64 masks Bring Direct DXIL pixel shaders and wave64 HLSL pixel shaders in line with 6ec402b1 (first_lane_live) and 8fcc1113 (mask_live): - Direct DXIL v_readfirstlane_b32 now calls Lw::first_lane_live, intersecting EXEC with ballot(true) in pixel shaders when any live lane is active so helper-lane zeroing inside loops on AMD drivers cannot spin to LOOP_BUDGET. - Wave64 HLSL pixel shader s_and_b64 / s_andn2_b64 with EXEC or VCC now tests live lanes only via mask_live64, matching mask_live for wave32 pixel loops. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/lanes.rs | 38 +++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_valu.rs | 2 +- crates/xcl/src/gpu/recomp/emit.rs | 18 ++++++++++++- 3 files changed, 56 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 4ee59b5cc8..14fc4e56f9 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -626,6 +626,44 @@ impl Lw { let lnz = self.nz(lo); self.sel(lnz, fl, hv) } + + /// Hardware live-lane ballot (excludes pixel-shader helper lanes, unlike [`Lw::ballot`]). + fn ballot_live(&mut self, cond: Value) -> (Value, Value) { + let w = self.s.wave_ballot(cond); + if !self.wave64 { + let z = self.c(0); + if let Some(h) = self.gfx_half { + return (self.sel(h, w[1], w[0]), z); + } + return (w[0], z); + } + if !self.split { + return (w[0], w[1]); + } + let m = w[0]; + let o = self.exchange(m); + let u = self.upper; + let lo = self.sel(u, o, m); + let hi = self.sel(u, m, o); + (lo, hi) + } + + /// First live lane of (lo, hi) in a pixel shader when EXEC has one, else first set lane + /// (the recompiler's `first_lane_live`: avoids reading helper-lane registers inside PS loops). + pub fn first_lane_live(&mut self, lo: Value, hi: Value) -> Value { + if self.gfx.as_ref().is_some_and(|g| g.ps.is_some()) { + let t = self.s.m.i1c(true); + let (lv_lo, lv_hi) = self.ballot_live(t); + let ml = self.and(lo, lv_lo); + let mh = self.and(hi, lv_hi); + let any = self.or(ml, mh); + let has_live = self.nz(any); + let lo = self.sel(has_live, ml, lo); + let hi = self.sel(has_live, mh, hi); + return self.first_lane(lo, hi); + } + self.first_lane(lo, hi) + } } #[cfg(test)] diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index 6803fa7d18..633250dd9b 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -988,7 +988,7 @@ impl Lw { } "v_readfirstlane_b32" => { let (el, eh) = self.exec_mask(); - let l = self.first_lane(el, eh); + let l = self.first_lane_live(el, eh); let t = self.read_lane_uniform(a, l); self.write32(&dst, t); return Ok(()); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index f90c7e3956..43dd909f81 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1910,7 +1910,15 @@ impl Em { } }; self.line(&format!("uint {t0} = {lo}; uint {t1} = {hi};")); - if let Some(c) = scc { + // "is a lane left" of a 64-bit lane mask (an AND with EXEC or VCC) in a wave64 pixel + // shader: over the live lanes (`mask_live64`), matching `mask_live` for wave32. + let lanes_left = matches!(name, "s_and_b64" | "s_andn2_b64") + && matches!(self.opt.mode, Mode::Pixel(_)) + && d.enc.name == "ENC_SOP2" + && ["SSRC0", "SSRC1", "SDST"].iter().any(|f| matches!(Self::field(d, f), 106 | 126)); + if lanes_left { + self.line(&format!("scc = (uint)(mask_live64({t0}, {t1}) != 0u);")); + } else if let Some(c) = scc { self.line(&format!("scc = (uint)({c});")); } if matches!(name, "s_bcnt0_i32_b64" | "s_bcnt1_i32_b64" | "s_ff0_i32_b64" | "s_ff1_i32_b64" | "s_flbit_i32_b64" | "s_flbit_i32_i64") { @@ -6345,6 +6353,14 @@ uint mask_live(uint m) { #endif return m; } +uint mask_live64(uint lo, uint hi) { +#ifdef XCL_PIXEL + uint2 lv = ballot(true); + lo &= lv.x; + hi &= lv.y; +#endif + return lo | hi; +} uint first_lane_live(uint lo, uint hi) { #ifdef XCL_PIXEL uint2 lv = ballot(true); From 5b3f0a4b8cf8546663c38c62684061e24031f7c3 Mon Sep 17 00:00:00 2001 From: Diskuss Date: Wed, 25 Nov 2026 11:18:33 +0100 Subject: [PATCH 052/258] Direct DXIL: fold Countbits of constants (AMD folds Bfrev(Countbits(K)) wrong) amdxc64 on RDNA4 folds Bfrev(Countbits(K)) for a constant K to Bfrev(n) | n (0x80000001 for K = 2). Fold Countbits of constants in bit_count so the driver never sees that pattern. Fixes fuzz seed 1599 on the RX 9070 XT (#2115). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/module.rs | 10 ++++++++++ crates/xcl/src/gpu/dxil/ops.rs | 12 +++++++++--- crates/xcl/src/gpu/dxil/ops_tests.rs | 26 ++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..a7f0128da4 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -417,6 +417,16 @@ impl Module { let sext = if w >= 64 { v as i64 } else { ((v << (64 - w)) as i64) >> (64 - w) }; self.constant(ConstDef::Int(ty, sext)) } + /// The value of an integer constant (sign-extended to 64 bits), if `v` is one. + pub fn int_const(&self, v: Value) -> Option { + match v { + Value::Const(c) => match self.consts[c as usize] { + ConstDef::Int(_, x) => Some(x), + _ => None, + }, + _ => None, + } + } pub fn i32c(&mut self, v: u32) -> Value { let t = self.i32(); self.const_int(t, v as u64) diff --git a/crates/xcl/src/gpu/dxil/ops.rs b/crates/xcl/src/gpu/dxil/ops.rs index cf7d47b145..8c1272bd14 100644 --- a/crates/xcl/src/gpu/dxil/ops.rs +++ b/crates/xcl/src/gpu/dxil/ops.rs @@ -358,12 +358,18 @@ impl Shader { pub fn bit_count(&mut self, op: BitCount, v: Value) -> Value { let t = self.m.type_of(v); let i32 = self.m.i32(); + if let (BitCount::Countbits, Some(x), Some(w)) = (op, self.m.int_const(v), self.m.int_width(t)) { + // Fold `Countbits` of a constant here: AMD's driver (amdxc64, + // RDNA4) folds `Bfrev(Countbits(K))` to `Bfrev(n) | n` (n = + // countbits(K)), e.g. 0x80000001 for K = 2 (fuzz seed 1599, #2115). + let mask = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 }; + return self.m.i32c(((x as u64) & mask).count_ones()); + } if self.is_i64(v) { self.require(Feature::Int64Ops); if matches!(op, BitCount::Countbits) { - // Count each 32-bit half: AMD's driver (amdxc64, RDNA4) gets - // i64 bit ops wrong (see `bfrev`); fuzz seed 1599 reads a wrong - // value downstream of `Countbits.i64(i64 2)` there only. + // Count each 32-bit half: AMD's driver (amdxc64) gets i64 bit + // ops wrong (see `bfrev`). let lo = self.m.cast(CastOp::Trunc, v, i32); let c32 = self.m.const_int(t, 32); let hi = self.m.bin(BinOp::LShr, v, c32); diff --git a/crates/xcl/src/gpu/dxil/ops_tests.rs b/crates/xcl/src/gpu/dxil/ops_tests.rs index 71989884db..f38723bf86 100644 --- a/crates/xcl/src/gpu/dxil/ops_tests.rs +++ b/crates/xcl/src/gpu/dxil/ops_tests.rs @@ -1053,6 +1053,32 @@ fn i1_to_i64_sign_extension_and_shift_match_cpu() { } } +/// `Bfrev(Countbits(K))` with a constant `K`: AMD's driver (amdxc64, RDNA4) +/// folds it to `Bfrev(n) | n` (0x80000001 for K = 2), so `bit_count` folds +/// `Countbits` of constants itself (#2115, fuzz seed 1599). +#[test] +fn bfrev_of_countbits_of_a_constant_matches_cpu() { + let ks: [u64; 6] = [0, 2, 3, 0xF0, 0xFFFF_FFFF, 0x8000_0000_0000_0003]; + let mut k = kernel(); + let (i32, i64) = (k.s.m.i32(), k.s.m.i64()); + let mut outs = vec![]; + for (i, &c) in ks.iter().enumerate() { + let v = if i == ks.len() - 1 { k.s.m.const_int(i64, c) } else { k.s.m.const_int(i32, c) }; + let n = k.s.bit_count(BitCount::Countbits, v); + outs.push(k.s.bfrev(n)); + } + for (i, &o) in outs.iter().enumerate() { + k.out(i as u32, o); + } + let c = k.finish([32, 1, 1]); + let dis = validate::disassemble(&c).unwrap_or_else(|d| d); + assert!(!dis.contains("Countbits(value)"), "Countbits of a constant is folded:\n{dis}"); + let Some(r) = gpu(&c, &mem_of(&[vec![0; 32]]), &[], &[]) else { return }; + for (i, &v) in ks.iter().enumerate() { + assert_eq!(outv(&r, i)[0], v.count_ones().reverse_bits(), "Bfrev(Countbits({v:#x}))"); + } +} + #[test] fn uav_array_3d_stores_loads_and_texture_atomics_run() { // u: heap 3 = RWTexture2DArray 4×4×2, heap 5 = RWTexture3D 4×4×2. From 324193c00553f4ba154af3f0e5ac471042763382 Mon Sep 17 00:00:00 2001 From: 0xkn0wh3r3 <360897260+0xkn0wh3r3@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:07:31 -0500 Subject: [PATCH 053/258] Recompiler: console pixel shaders tested depth-first keep early depth A console pixel shader compiled with [earlydepthstencil] runs with DB_SHADER_CONTROL.DEPTH_BEFORE_SHADER (bit 12) set: depth and stencil are tested before it runs, so it runs only for pixels that pass, even when it writes memory. XCL never read the register, so the PC ran such shaders for hidden pixels too and kept their memory writes (work the console skips, and writes it never makes). DB_SHADER_CONTROL is the dword after SPI_PS_INPUT_ENA in the FSSM's PS input table (+0x114 from the table, + the sub-version shift); the same place VIctory's FSSM layout gives it. The bit is read only where the input table was recognised. Pixel shaders with it get [earlydepthstencil] on the HLSL path and ForceEarlyDepthStencil (shader flag bit 3) on the direct DXIL path, which had it hard-coded to false. DXC accepts the attribute together with an SV_Depth export. The translator's source id covers these files, so cached translations are made again. --- crates/xcl/src/gpu/dxil/core_tests.rs | 53 +++++++++++++++++++-- crates/xcl/src/gpu/dxil/kernel.rs | 3 +- crates/xcl/src/gpu/dxil/robustness_tests.rs | 1 + crates/xcl/src/gpu/recomp/emit.rs | 8 +++- crates/xcl/src/gpu/recomp/mod.rs | 45 ++++++++++++++++- crates/xcl/src/gpu/recomp/tests.rs | 10 +++- 6 files changed, 112 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index e619fc3954..dda5533f6e 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -133,6 +133,7 @@ fn direct_and_hlsl_graphics_stages_link() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let (vo, po) = (Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }, Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }); let hvs = crate::gpu::recomp::dxc::compile(&translate(&vs_code, &vo).unwrap().hlsl, "main", "vs_6_6", &[]).unwrap(); @@ -181,7 +182,7 @@ fn branchy_graphics_stages_validate() { } // v2 = front face (SPI_PS_INPUT_ENA bit 12 after the two I/J pairs of 0x3) let ps_code = body(("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 2), ("VSRC3", 5), ("DONE", 1), ("VM", 1)], None)); - let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x1002, attrs: None }; + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x1002, attrs: None, early_depth: false }; for wave64 in [true, false] { super::kernel::translate_pixel(&ps_code, KernelOptions { wave64, ..ko }, &psi).unwrap_or_else(|e| panic!("PS wave64 {wave64}: {}", &e[..e.len().min(800)])); } @@ -204,7 +205,7 @@ fn long_pixel_shader_translates_fast() { list.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let code = prog(&refs); - let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None }; + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None, early_depth: false }; let t = std::time::Instant::now(); let k = super::kernel::translate_pixel(&code, KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); println!("3000 instructions: {:?}, {} B", t.elapsed(), k.dxil.len()); @@ -254,6 +255,7 @@ fn graphics_stages_with_a_branch_before_their_exports() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; let dvs = super::kernel::translate_vertex(&vs_code, ko, &vsi).unwrap_or_else(|e| panic!("VS: {}", &e[..e.len().min(600)])).dxil; @@ -429,7 +431,7 @@ fn ps_get_lod_with_a_static_sampler() { list.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let code = prog(&refs); - let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None }; + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x2, attrs: None, early_depth: false }; let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; let k = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); assert_eq!(k.static_samplers, vec![(linear, false)], "one static sampler, shared by get_lod and sample"); @@ -670,3 +672,48 @@ fn s_barrier_emits_all_sync_when_shader_writes_uav_or_uses_glc() { assert!(dis.contains("dx.op.barrier(i32 80, i32 11)"), "expected ALL_SYNC (11) for GLC load:\n{dis}"); } } + +/// A console PS with DB_SHADER_CONTROL.DEPTH_BEFORE_SHADER (`PsInterface::early_depth`) gets +/// `[earlydepthstencil]` on the HLSL path and the ForceEarlyDepthStencil shader flag (bit 3) on +/// both paths, also when it exports depth; without it, neither. +#[test] +fn early_depth_pixel_shaders_test_depth_first_on_both_paths() { + use crate::gpu::recomp::{dxc, runner, translate, Mode, Options, PsInterface}; + if dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + // the shader flags of the entry (`!{i32 0, i64 , ...}`) + let early_flag = |c: &[u8]| { + let dis = super::validate::disassemble(c).unwrap_or_else(|e| panic!("{e}")); + dis.match_indices("!{i32 0, i64 ").any(|(i, m)| { + let n: String = dis[i + m.len()..].chars().take_while(char::is_ascii_digit).collect(); + n.parse::().is_ok_and(|f| f & 8 != 0) + }) + }; + let color = ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 4), ("VSRC2", 4), ("VSRC3", 4), ("DONE", 1), ("VM", 1)][..], None); + let target = sig("SV_Target", 0, 64, 3, 0, 0xF); + let cases = [ + ("color", prog(&[("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 242)], None), color]), vec![target.clone()]), + ( + "color and depth", + prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 4), ("SRC0", 240)], None), + ("EXP", "ENC_EXP", &[("TGT", 8), ("EN", 0x1), ("VSRC0", 4), ("VSRC1", 4), ("VSRC2", 4), ("VSRC3", 4)], None), + color, + ]), + vec![target, sig("SV_Depth", 0, 65, 3, u32::MAX, 0x1)], + ), + ]; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + for (name, code, outputs) in &cases { + for early_depth in [false, true] { + let psi = PsInterface { inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], outputs: outputs.clone(), input_ena: 0x2, attrs: None, early_depth }; + let t = translate(code, &Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert_eq!(t.hlsl.contains("[earlydepthstencil]\nXclOut main("), early_depth, "{name}, early {early_depth}: HLSL\n{}", t.hlsl); + let hlsl = dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{name}, early {early_depth}: {e}\n{}", t.hlsl)); + assert_eq!(early_flag(&hlsl), early_depth, "{name}, early {early_depth}: HLSL path's shader flags"); + let direct = super::kernel::translate_pixel(code, ko, &psi).unwrap_or_else(|e| panic!("{name}, early {early_depth}: {}", &e[..e.len().min(800)])); + assert_eq!(early_flag(&direct.dxil), early_depth, "{name}, early {early_depth}: direct path's shader flags"); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 6adb05d0a2..6b259e3814 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -621,7 +621,8 @@ impl Lw { let mut dispatch_chain = None; let c = if matches!(stage, Stage::Vertex | Stage::Pixel) { let g = self.gfx.take().ok_or("graphics entry without graphics I/O")?; - let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil: false } } else { super::graphics::StageInfo::Vertex }; + let early_depth_stencil = g.ps.as_ref().is_some_and(|p| p.early_depth); + let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil } } else { super::graphics::StageInfo::Vertex }; self.s.try_finish_graphics(g.io, info) } else if limit > 0 && (numthreads == [32, 1, 1] || split_tid.is_some()) && hw == 32 { self.s.m.optimize(); diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index 46a06c63d4..e9a2cedadc 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -68,6 +68,7 @@ fn translate_all() -> Vec> { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let cs = CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 43dd909f81..2e2823b58c 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5239,7 +5239,13 @@ impl Em { if !self.ps_writes_mask && !ps.outputs.iter().any(|e| matches!(e.system_value, 64 | 65 | 67 | 68)) { h.push_str(" float4 xcl_unused : SV_Target7;\n"); } - h.push_str("};\nXclOut main(XclIn xi)\n{\n XclOut xo = (XclOut)0;\n"); + h.push_str("};\n"); + // the console tests depth first: without it the PC runs (and keeps the memory + // writes of) hidden pixels too + if ps.early_depth { + h.push_str("[earlydepthstencil]\n"); + } + h.push_str("XclOut main(XclIn xi)\n{\n XclOut xo = (XclOut)0;\n"); if self.ps_writes_mask { h.push_str(" xo.xcl_mask = 0xFFFFFFFFu;\n"); } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index c2548d56e5..680ae9e9c3 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -151,6 +151,9 @@ pub struct PsInterface { pub input_ena: u32, /// the console's PS input table (`ps_input_table`; None: attributes in register order) pub attrs: Option>, + /// DB_SHADER_CONTROL.DEPTH_BEFORE_SHADER (`ps_shader_control`): depth and stencil are tested + /// before the program runs (`[earlydepthstencil]`), so it runs only for pixels that pass + pub early_depth: bool, } /// Mesh (NGG) shader interface. @@ -390,6 +393,17 @@ pub fn ps_input_table(fssm: &[u8]) -> Option<(u32, Vec)> { Some((ena, out)) } +/// DB_SHADER_CONTROL bit 12 (DEPTH_BEFORE_SHADER, as AMD's GFX10.3 register headers name it): +/// the compiler sets it for `[earlydepthstencil]`. +pub const DEPTH_BEFORE_SHADER: u32 = 1 << 12; + +/// DB_SHADER_CONTROL of an FSSM: the dword after SPI_PS_INPUT_ENA in the PS input table +/// (`ps_input_table`, +0x114; the same layout VIctory's `native.rs` reads it from). +pub fn ps_shader_control(fssm: &[u8]) -> Option { + let o = 0x130 + fssm_shift(fssm)? + 0x114; + fssm.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())) +} + /// The VS output table of an FSSM: per `exp param N`, the OSG1 register it writes. 32 records /// of 6 bytes at +0x1D4 (+ the sub-version shift): kind (6 user, 0 position), register, param /// number, 0, 0, 0; the record count after them (+0xC0). Usually param N = the N-th output @@ -469,7 +483,9 @@ pub fn interface(blob: &[u8], sh: &super::xbox::XboxShader, f: &super::xbox::Fss Some((ena, t)) => (ena, Some(t)), None => (f.data.get(0x248..0x24C).map(|b| u32::from_le_bytes(b.try_into().unwrap()))?, None), }; - Some(Mode::Pixel(PsInterface { inputs, outputs, input_ena: ena, attrs })) + // only where the input table was found: elsewhere the layout is not known + let early_depth = attrs.is_some() && ps_shader_control(&f.data).is_some_and(|c| c & DEPTH_BEFORE_SHADER != 0); + Some(Mode::Pixel(PsInterface { inputs, outputs, input_ena: ena, attrs, early_depth })) } // ES variant of a VS (before a GS) and the GS itself, each translatable on its own ("VS", 2) => Some(Mode::Geometry(GsInterface { es_inputs: inputs, es_outputs: outputs, max_vertex_count: 1, ..Default::default() })), @@ -1662,6 +1678,33 @@ mod attribute_tests { assert_eq!(ps_attribute_slot(&ps, 1, 0), Some(1)); } + /// DB_SHADER_CONTROL follows SPI_PS_INPUT_ENA in the input table: DEPTH_BEFORE_SHADER (bit + /// 12) makes a PS early-depth; other bits (Z export, kill, the ordered-section bit 16) do not. + #[test] + fn ps_depth_before_shader_from_the_input_table() { + let early = |sub: u32, control: u32, valid: bool| { + let base = if sub == 5 { 0x130 } else { 0x138 }; + let mut data = vec![0u8; 0x400]; + data[0x10..0x14].copy_from_slice(&sub.to_le_bytes()); + data[base..base + 8].copy_from_slice(&[6, 1, 0xF, 0, 0, 0, 1, 2]); + data[base + 0x100] = if valid { 1 } else { 33 }; + data[base + 0x110] = 2; + data[base + 0x114..base + 0x118].copy_from_slice(&control.to_le_bytes()); + assert_eq!(ps_shader_control(&data), Some(control)); + let f = super::super::xbox::Fssm { data, stages: vec![super::super::xbox::HwStage { offset: 0, hw: 5, api: 1 }], ..Default::default() }; + let sh = super::super::xbox::XboxShader { stage: "PS".into(), ..Default::default() }; + let Some(Mode::Pixel(ps)) = interface(&[], &sh, &f) else { panic!("not a PS") }; + ps.early_depth + }; + for sub in [5, 6] { + assert!(early(sub, DEPTH_BEFORE_SHADER, true), "sub-version {sub}"); + assert!(early(sub, DEPTH_BEFORE_SHADER | 1 << 16 | 0x41, true), "sub-version {sub}, with other bits"); + assert!(!early(sub, 1 << 16 | 0x41, true), "sub-version {sub}, without the bit"); + // no input table found: the layout is not known, the bit not trusted + assert!(!early(sub, DEPTH_BEFORE_SHADER, false), "sub-version {sub}, no table"); + } + } + /// Minecraft's UI vertex shader: an ISG1 input the program never reads (NORMAL0, r1) gets /// no fetch-shader VGPRs – POSITION0 (r2) is read in v8, TEXCOORD0 (r3) in v12. #[test] diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 3cfa8e2ec2..16f91facb9 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1851,6 +1851,7 @@ fn gpu_graphics_vs_ps_draw() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let (vo, po) = (Options { mode: Mode::Vertex(vsi), wave64: true, ..Default::default() }, Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }); let vt = translate(&vs_code, &vo).unwrap(); @@ -1935,6 +1936,7 @@ fn ps_exp_vm_hlsl_and_direct_dxil_codegen() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let po = Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }; for (name, ps_code, has_vm) in ps_exp_vm_cases() { @@ -1984,6 +1986,7 @@ fn gpu_ps_exp_vm_controls_pixel_survival() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let vo = Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }; let po = Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }; @@ -2169,6 +2172,7 @@ fn gpu_rect_list_corners() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let outputs = vsi.outputs.clone(); let vt = translate(&vs_code, &Options { mode: Mode::Vertex(vsi), wave64: true, ..Default::default() }).unwrap(); @@ -2239,6 +2243,7 @@ fn draw_psi() -> super::PsInterface { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, } } @@ -2752,7 +2757,7 @@ fn helper_lane_masks_ps(wave64: bool) -> super::Translation { ps_code.extend(encode("S_CBRANCH_EXECNZ", "ENC_SOPP", &[("SIMM16", back)], None).unwrap()); ps_code.extend(enc(&tail)); ps_code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); - let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None }; + let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; translate(&ps_code, &Options { mode: Mode::Pixel(psi), wave64, ..Default::default() }).unwrap() } } @@ -6476,7 +6481,7 @@ fn isa_coverage() { let Ok(mut code) = encode(inst.name, enc, fields, lit) else { continue }; code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); let ok = std::panic::catch_unwind(|| { - try_mode(&code, Mode::Kernel) || try_mode(&code, Mode::Pixel(super::PsInterface { inputs: vec![], outputs: vec![], input_ena: 0x7F, attrs: None })) + try_mode(&code, Mode::Kernel) || try_mode(&code, Mode::Pixel(super::PsInterface { inputs: vec![], outputs: vec![], input_ena: 0x7F, attrs: None, early_depth: false })) }) .unwrap_or(false); let e = per_enc.entry(enc.trim_start_matches("ENC_")).or_default(); @@ -8321,6 +8326,7 @@ fn ps_interp_p0_preserves_bits_and_p2_converts_to_float() { outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, + early_depth: false, }; let pt = translate(&ps_code, &Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }).unwrap(); assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); From b6df9a7f0557b9b289ba41e505f1ff53f4e998a4 Mon Sep 17 00:00:00 2001 From: John Howard <49204095+Royalflamejlh@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:12:46 -0700 Subject: [PATCH 054/258] Recompiler: the compact form's larger tables on every GPU again This takes out e964ad2, which kept the table limit of 8,192 words on a GPU with 64-lane waves. It was added after a run on an RX 9070 XT at cbc296a, where neither form of the program it let in built within 24 GB and the compact form reached that sooner. Since #2174 the compact form nests its dispatch by default, and on the same card model with 64 GB that program's nested compact form built in 159 to 203 s at about 34 GB with heap memory windows, where its plain form, which the guard kept, passed 48 GB (komglebissarov on #2088, 1 run per form). With the default switch windows both forms passed 48 GB, so that path does not change. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/compact.rs | 8 ++--- crates/xcl/src/gpu/dxil/compact_tests.rs | 44 +++++++----------------- crates/xcl/src/gpu/dxil/kernel.rs | 28 ++++++--------- crates/xcl/src/gpu/recomp/pso.rs | 2 +- 4 files changed, 27 insertions(+), 55 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index b5d615a297..f8dfe6a544 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -22,9 +22,7 @@ pub struct Plan { } /// Most 32-bit words of tables a program may need to take the form by itself. -pub const TABLE_WORDS: usize = 8192; -/// `TABLE_WORDS` on a GPU that runs only 32-lane waves. -pub const TABLE_WORDS_WAVE32: usize = 12288; +const MAX_TABLE_WORDS: usize = 12288; impl Plan { /// Bits of a table entry: the class, and the taken successor or the index of the pair of offsets. @@ -40,11 +38,11 @@ impl Plan { } /// Whether a program takes the form by itself: large, mostly repeated blocks, small tables. -pub fn wanted(cfg: &Cfg, p: &Plan, tables: usize) -> bool { +pub fn wanted(cfg: &Cfg, p: &Plan) -> bool { let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); let all: usize = (0..p.order.len()).map(insts).sum(); let once: usize = p.rep.iter().map(|&n| insts(n)).sum(); - large(cfg) && once * 10 < all * 3 && p.words() <= tables + large(cfg) && once * 10 < all * 3 && p.words() <= MAX_TABLE_WORDS } /// Whether a program is large enough for `wanted` to be asked. diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 7602b5da43..5b278ebb40 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -169,7 +169,16 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() { assert_ne!(p.class[0], p.class[2]); } -fn two_segments(copies: usize) -> Vec { +#[test] +fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { + if compact_mode().is_some() { + return; + } + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + const COPIES: usize = 8192; let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); let mut code = Vec::new(); code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 2)])); @@ -177,50 +186,23 @@ fn two_segments(copies: usize) -> Vec { code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", r), ("SRC0", 256 + r)])); } for marker in [3, 4] { - for k in 0..copies { + for k in 0..COPIES { code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)])); code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 256), ("VSRC1", 1)])); - let offset = (copies - 1 - k) * 3 + 1; + let offset = (COPIES - 1 - k) * 3 + 1; assert!(offset <= i16::MAX as usize); code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", offset as u64)])); } code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", marker), ("SSRC0", 129)])); } code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); - code -} - -#[test] -fn a_gpu_with_64_lane_waves_keeps_the_first_table_limit() { - if compact_mode().is_some() { - return; - } - let code = two_segments(8192); - let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; - let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; - let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only).unwrap().dxil.len(); - let (compact, plain) = (size(true), size(false)); - assert!(compact * 20 < plain, "{compact} B on a GPU with 32-lane waves only, {plain} B on one with 64-lane waves"); -} - -#[test] -fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { - if compact_mode().is_some() { - return; - } - match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { - (Ok(_), Ok(true), Ok(_)) => {} - (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), - } - const COPIES: usize = 8192; - let code = two_segments(COPIES); let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; let cfg = super::cfg::Cfg::build(&code).unwrap(); let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); let p = super::compact::plan(&cfg, &lw).unwrap(); assert!(p.inline && p.words() > 8192 && p.words() <= 12288); - assert!(super::compact::wanted(&cfg, &p, super::compact::TABLE_WORDS_WAVE32)); + assert!(super::compact::wanted(&cfg, &p)); let k = translate_full(&code, o).unwrap(); for initial in [0u32, u32::MAX - 1, 0u32.wrapping_sub(COPIES as u32), 0u32.wrapping_sub((2 * COPIES) as u32), 0u32.wrapping_sub(COPIES as u32 + 1)] { let mut st = KernelState::default(); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 6b259e3814..a51ac76ebc 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -91,39 +91,39 @@ pub fn compact_nest_tag() -> Option { /// `translate_full` in the compact form (`compact = true`) or the plain one. #[cfg(test)] pub fn translate_full_as(code: &[u8], o: KernelOptions, compact: bool) -> Result { - translate_entry(code, o, Entry::Kernel, Some(compact), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(compact), None) } /// `translate_full` in the compact form with an explicit dispatch nesting policy. #[cfg(test)] pub fn translate_full_nested(code: &[u8], o: KernelOptions, nest: super::compact::Nest) -> Result { - translate_entry(code, o, Entry::Kernel, Some(true), Some(nest), super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(true), Some(nest)) } pub fn translate_full(code: &[u8], o: KernelOptions) -> Result { - translate_entry(code, o, Entry::Kernel, compact_mode(), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, compact_mode(), None) } /// A mesh-mode (NGG) program: the first pass that writes one record per group into /// `res` (the recompiler's `Mode::Mesh`; the pass-through mesh shader draws them). pub fn translate_mesh(code: &[u8], o: KernelOptions, ms: &MsInterface) -> Result { - translate_entry(code, o, Entry::Mesh(ms.clone()), None, None, 0) + translate_entry(code, o, Entry::Mesh(ms.clone()), None, None) } /// A vertex shader (the recompiler's `Mode::Vertex`; wave-size independent). pub fn translate_vertex(code: &[u8], o: KernelOptions, vs: &VsInterface) -> Result { - translate_entry(code, o, Entry::Vertex(vs.clone()), None, None, 0) + translate_entry(code, o, Entry::Vertex(vs.clone()), None, None) } /// A pixel shader (the recompiler's `Mode::Pixel`; wave-size independent). pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Result { - translate_entry(code, o, Entry::Pixel(ps.clone()), None, None, 0) + translate_entry(code, o, Entry::Pixel(ps.clone()), None, None) } /// A geometry-mode (ES+GS) program: the compute pass that writes one mesh record per /// group of 21 triangles into `res` (the recompiler's `Mode::Geometry`). Always wave64. pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Result { - translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0) + translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None) } /// The entry ABI. @@ -139,13 +139,7 @@ pub enum Entry { /// A compute-mode program (the CS ABI of `cs`). pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result { - translate_compute_on(code, o, cs, true) -} - -/// `translate_compute` for a GPU: one that runs only 32-lane waves takes larger compact tables. -pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool) -> Result { - let tables = if wave32_only { super::compact::TABLE_WORDS_WAVE32 } else { super::compact::TABLE_WORDS }; - translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables) + translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None) } fn translate_entry( @@ -154,7 +148,6 @@ fn translate_entry( entry: Entry, compact: Option, nest: Option, - tables: usize, ) -> Result { // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs @@ -162,7 +155,7 @@ fn translate_entry( std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables)) + .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest)) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -192,7 +185,6 @@ fn translate_on_this_thread( entry: Entry, compact: Option, nest: Option, - tables: usize, ) -> Result { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), @@ -279,7 +271,7 @@ fn translate_on_this_thread( } let plan = if (compute || kernel) && compact.unwrap_or_else(|| super::compact::large(&cfg)) { super::compact::plan(&cfg, &lw) } else { None }; - let plan = plan.filter(|p| compact.unwrap_or_else(|| super::compact::wanted(&cfg, p, tables))); + let plan = plan.filter(|p| compact.unwrap_or_else(|| super::compact::wanted(&cfg, p))); if let Some(p) = &plan { crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 37beb50d9d..b04b396d50 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -958,7 +958,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } } } - let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?; + let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?; dump_direct(blob, &k.dxil); Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) } From f4a2cd8e6184feb3b2feb2736a09533c11f02dfc Mon Sep 17 00:00:00 2001 From: veyn-sudo <360844188+veyn-sudo@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:11:13 +0100 Subject: [PATCH 055/258] D3D12.X: a pipeline is forgotten before its address is free pso_release dropped what XCL keeps of a pipeline after the driver had freed it. A pipeline made by another thread in between could get the same address and lose its own entries: a translated compute program then counts as untranslated and its dispatches are skipped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WStEFektfHt5AEbK6Wupac --- crates/xcl/src/hle/d3d12x/real.rs | 59 ++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 754fc291a7..fbeb916f80 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1796,9 +1796,19 @@ pub(super) fn standin_released(pso: usize) { /// A stand-in pipeline released for good takes its background-built real pipeline with it. unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { + let add: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + // The last reference: forgotten while the object has its address. A pipeline another thread + // makes can get that address as soon as it is free, and must keep its own entries. + let last = add(this) == 2; + if last { + forget_pso(this as usize); + super::pso_async::release(super::pso_async::released(this as usize)); + } + f(this); let n = f(this); - if n == 0 { + // (two last-but-one releases at once: neither saw itself as the last) + if n == 0 && !last { forget_pso(this as usize); super::pso_async::release(super::pso_async::released(this as usize)); } @@ -9291,3 +9301,50 @@ void main() { } } + +#[cfg(test)] +mod pso_release_tests { + use super::*; + + /// An adopted pipeline as `orig_fn` sees it: its vtable, the original one before that. + #[repr(C)] + struct Pipeline { + vtable: *const usize, + refs: u32, + /// the pipeline was still known when its last reference went + known_when_freed: Option, + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let p = &mut *(this as *mut Pipeline); + p.refs += 1; + p.refs + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let p = &mut *(this as *mut Pipeline); + p.refs -= 1; + if p.refs == 0 { + p.known_when_freed = Some(is_translated_compute(this as usize)); + } + p.refs + } + + /// What XCL keeps of a pipeline goes before the driver frees it, not after: its address can be + /// another pipeline's by then. It stays while there are other references. + #[test] + fn a_pipeline_is_forgotten_before_its_address_is_free() { + let orig: [usize; 3] = [0, add_ref as usize, release as usize]; + let ext: [usize; 4] = [orig.as_ptr() as usize, 0, 0, 0]; + let mut p = Box::new(Pipeline { vtable: &ext[1], refs: 2, known_when_freed: None }); + let this = p.as_mut() as *mut Pipeline as *mut c_void; + register_translated_compute_for_test(this as usize); + unsafe { + assert_eq!(pso_release(this), 1); + assert!(is_translated_compute(this as usize), "another reference is left"); + assert_eq!(pso_release(this), 0); + } + assert_eq!(p.known_when_freed, Some(false)); + assert!(!is_translated_compute(this as usize)); + } +} From a1ab351784b4cea153576932c4064d17e6acdfb5 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:56:59 +0300 Subject: [PATCH 056/258] D3D12.X: harden PresentX compositor and single-plane sub-rect scaling Follow-up hardening to #615's PresentX multi-plane compositor: - Release `ManuallyDrop>` after `CreateGraphicsPipelineState` in `Compositor::psos_for` on both success and failure paths so `self.root_sig` does not leak 2 COM references per RTV format. - Validate all active planes upfront in `Compositor::record` (non-empty, `TEXTURE2D`, `SampleDesc.Count == 1`, no `DENY_SHADER_RESOURCE`, and supported `swap_format`) before creating PSOs/descriptors or recording draws so invalid planes fall back cleanly to plane-0 copy. - Cap `plane_count` to `MAX_PLANES` in `present_x_frame`'s raw-word logging helper to match `extract_planes` and avoid overflow/over-read on large counts. - Route single-plane `PresentX` frames with a non-full `uv_rect` through `Compositor` (with plane-0 copy fallback) while preserving the full-rect `CopyResource` fast path. Part of #1452 Part of #1333 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/hle/d3d12x/present.rs | 131 +++++++++++++++++++++++++-- 1 file changed, 125 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index b582501543..c41e3bfea0 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -113,6 +113,11 @@ fn source_uv_rect(rect: Option<[i32; 4]>, w: u32, h: u32) -> [f32; 4] { [0.0, 0.0, 1.0, 1.0] } +unsafe fn raw_plane_words(plane_count: u32, planes: *const u8) -> Vec { + let n = (PLANE_STRIDE / 8) * (plane_count as usize).min(MAX_PLANES); + if crate::gpu::shader::readable(planes as usize, 8 * n) { (0..n).map(|k| (planes as *const u64).add(k).read_unaligned()).collect() } else { Vec::new() } +} + unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u8) { let frames = BOUNDARIES.fetch_add(1, Ordering::Relaxed) + 1; if frames % 300 == 0 { @@ -132,8 +137,7 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u // plane over the game's): logged with the planes' raw words static LAST: AtomicU64 = AtomicU64::new(1); if LAST.swap(plane_count as u64, Ordering::Relaxed) != plane_count as u64 { - let n = (PLANE_STRIDE / 8) * plane_count as usize; - let words: Vec = if crate::gpu::shader::readable(planes as usize, 8 * n) { (0..n).map(|k| (planes as *const u64).add(k).read_unaligned()).collect() } else { Vec::new() }; + let words = raw_plane_words(plane_count, planes); crate::xlog_info!("D3D12.X: PresentX now with {plane_count} plane(s): {words:x?}"); } } @@ -820,7 +824,9 @@ impl Compositor { } else { rt.BlendEnable = false.into(); } - dev.CreateGraphicsPipelineState(&pd).ok() + let pso = dev.CreateGraphicsPipelineState(&pd).ok(); + let _ = ManuallyDrop::into_inner(pd.pRootSignature); + pso }; let pair = (make_pso(false)?, make_pso(true)?); self.psos.insert(fmt.0, pair.clone()); @@ -838,6 +844,16 @@ impl Compositor { planes: &[(ID3D12Resource, D3D12_RESOURCE_DESC, [f32; 4])], slot: usize, ) -> bool { + let active = &planes[..planes.len().min(MAX_PLANES)]; + let plane_ok = |d: &D3D12_RESOURCE_DESC| { + d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && d.SampleDesc.Count == 1 + && !d.Flags.contains(D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) + && swap_format(d.Format).is_some() + }; + if dst_w == 0 || dst_h == 0 || active.is_empty() || !active.iter().all(|(_, d, _)| plane_ok(d)) { + return false; + } let first = slot % PRESENT_SLOTS * MAX_PLANES; let Some((opaque_pso, blend_pso)) = self.psos_for(dev, dst_fmt) else { return false }; let rtv_cpu = self.rtv_heap.GetCPUDescriptorHandleForHeapStart(); @@ -848,7 +864,7 @@ impl Compositor { }; dev.CreateRenderTargetView(dst, Some(&rtv_desc), rtv_cpu); let srv_cpu_base = self.srv_heap.GetCPUDescriptorHandleForHeapStart(); - for (i, (res, desc, _)) in planes.iter().take(MAX_PLANES).enumerate() { + for (i, (res, desc, _)) in active.iter().enumerate() { let mut srv_cpu = srv_cpu_base; srv_cpu.ptr += (first + i) * self.srv_inc as usize; let mut srv_desc = D3D12_SHADER_RESOURCE_VIEW_DESC { @@ -874,7 +890,7 @@ impl Compositor { list.SetDescriptorHeaps(&[Some(self.srv_heap.clone())]); list.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); let srv_gpu_base = self.srv_heap.GetGPUDescriptorHandleForHeapStart(); - for (i, (_, _, uv_rect)) in planes.iter().take(MAX_PLANES).enumerate() { + for (i, (_, _, uv_rect)) in active.iter().enumerate() { list.SetPipelineState(if i == 0 { &opaque_pso } else { &blend_pso }); list.SetGraphicsRoot32BitConstants(0, 4, uv_rect.as_ptr() as *const c_void, 0); let mut gpu = srv_gpu_base; @@ -1015,6 +1031,10 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D } } +fn needs_compositor(planes: &[(ID3D12Resource, D3D12_RESOURCE_DESC, [f32; 4])]) -> bool { + planes.len() > 1 || planes.first().is_some_and(|(_, _, uv)| *uv != [0.0, 0.0, 1.0, 1.0]) +} + unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, Option<[i32; 4]>)>)>) { if IN_PRESENT.with(|c| c.replace(true)) { return; @@ -1101,7 +1121,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, let due = frame_dump_due(); let mut dumps = Vec::new(); let mut composited = false; - if resolved.len() > 1 { + if needs_compositor(&resolved) { if p.compositor.is_none() { p.compositor = Compositor::new(&p.dev); } @@ -1595,6 +1615,10 @@ mod tests { assert_eq!(source_uv_rect(got[0].1, 1600, 900), [0.1, 0.1, 0.5, 0.5]); assert_eq!(source_uv_rect(got[1].1, 3840, 2160), [0.0, 0.0, 1.0, 1.0]); assert_eq!(source_uv_rect(Some([0, 0, 4000, 900]), 1920, 1080), [0.0, 0.0, 1.0, 1.0]); + let big = vec![0u8; (MAX_PLANES + 2) * PLANE_STRIDE]; + let cap = MAX_PLANES * (PLANE_STRIDE / 8); + assert_eq!(unsafe { raw_plane_words((MAX_PLANES + 2) as u32, big.as_ptr()) }.len(), cap); + assert_eq!(unsafe { raw_plane_words(u32::MAX, big.as_ptr()) }.len(), cap); } } @@ -1821,4 +1845,99 @@ mod frame_dump_tests { rb.Unmap(0, None); } } + + unsafe fn warp_env() -> (ID3D12Device, ID3D12CommandAllocator, ID3D12GraphicsCommandList, Compositor) { + let adapter: IDXGIAdapter = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)).unwrap().EnumWarpAdapter().unwrap(); + let mut dev: Option = None; + D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).unwrap(); + let dev = dev.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + (dev.clone(), alloc, list, Compositor::new(&dev).unwrap()) + } + + unsafe fn make_tex_2d(dev: &ID3D12Device, w: u32, h: u32, samples: u32, flags: D3D12_RESOURCE_FLAGS) -> ID3D12Resource { + let mut r: Option = None; + let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: w as u64, Height: h, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8G8B8A8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: samples, Quality: 0 }, Flags: flags, ..Default::default() }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + r.unwrap() + } + + #[test] + fn compositor_releases_root_sig_and_rejects_invalid_planes() { + unsafe { + let (dev, _alloc, list, mut comp) = warp_env(); + let refcount = |p: *mut c_void| -> u32 { + let vtbl = *(p as *const *const usize); + std::mem::transmute:: u32>(*vtbl.add(1))(p); + std::mem::transmute:: u32>(*vtbl.add(2))(p) + }; + let before = refcount(comp.root_sig.as_raw()); + drop(comp.psos_for(&dev, DXGI_FORMAT_R8G8B8A8_UNORM).unwrap()); + assert!(comp.psos_for(&dev, DXGI_FORMAT_BC1_UNORM).is_none()); + comp.psos.clear(); + assert_eq!(refcount(comp.root_sig.as_raw()), before, "psos_for leaked root_sig COM refs"); + + let out = make_tex_2d(&dev, 8, 8, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let ok = make_tex_2d(&dev, 4, 4, 1, D3D12_RESOURCE_FLAG_NONE); + let msaa = make_tex_2d(&dev, 4, 4, 4, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let (mut deny, mut bad_fmt, mut buf) = (ok.GetDesc(), ok.GetDesc(), ok.GetDesc()); + deny.Flags |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; + bad_fmt.Format = DXGI_FORMAT_R32_FLOAT; + buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + let full = [0.0, 0.0, 1.0, 1.0]; + let cases: &[&[(ID3D12Resource, D3D12_RESOURCE_DESC, [f32; 4])]] = &[ + &[(ok.clone(), ok.GetDesc(), full), (ok.clone(), deny, full)], + &[(ok.clone(), ok.GetDesc(), full), (msaa.clone(), msaa.GetDesc(), full)], + &[(ok.clone(), bad_fmt, full)], &[(ok.clone(), buf, full)], &[], + ]; + for (idx, planes) in cases.iter().enumerate() { + assert!(!comp.record(&dev, &list, &out, 8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, planes, 0), "case {idx}"); + assert!(comp.psos.is_empty(), "case {idx} mutated compositor state"); + } + list.Close().unwrap(); + } + } + + #[test] + fn compositor_scales_single_plane_sub_rect() { + unsafe { + let (dev, _alloc, list, mut comp) = warp_env(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() }).unwrap(); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let (src, out) = (make_tex_2d(&dev, 8, 8, 1, D3D12_RESOURCE_FLAG_NONE), make_tex_2d(&dev, 8, 8, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)); + let (full, sub) = ([0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 0.5, 0.5]); + assert!(!needs_compositor(&[(src.clone(), src.GetDesc(), full)])); + assert!(needs_compositor(&[(src.clone(), src.GetDesc(), sub)])); + assert!(needs_compositor(&[(src.clone(), src.GetDesc(), full), (src.clone(), src.GetDesc(), full)])); + + let mut up: Option = None; + let up_desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: 256 * 8, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &up_desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut up).unwrap(); + let (up, mut ptr) = (up.unwrap(), std::ptr::null_mut()); + up.Map(0, None, Some(&mut ptr)).unwrap(); + let bytes = std::slice::from_raw_parts_mut(ptr as *mut u8, 256 * 8); + for y in 0..8usize { + for x in 0..8usize { bytes[y * 256 + x * 4..y * 256 + x * 4 + 4].copy_from_slice(if x < 4 && y < 4 { &[0, 255, 0, 255] } else { &[255, 0, 0, 255] }); } + } + up.Unmap(0, None); + let dst_loc = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&src), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + let src_loc = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: 0, Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: DXGI_FORMAT_R8G8B8A8_UNORM, Width: 8, Height: 8, Depth: 1, RowPitch: 256 } } } }; + list.ResourceBarrier(&[transition(&src, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.CopyTextureRegion(&dst_loc, 0, 0, 0, &src_loc, None); + list.ResourceBarrier(&[transition(&src, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON), transition(&out, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)]); + assert!(comp.record(&dev, &list, &out, 8, 8, DXGI_FORMAT_R8G8B8A8_UNORM, &[(src.clone(), src.GetDesc(), sub)], 0)); + list.ResourceBarrier(&[transition(&out, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let (rb, fp) = readback_copy(&list, &out, &out.GetDesc()).unwrap(); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + fence::wait(&fence, 1, &dev, None, 5000).unwrap(); + rb.Map(0, None, Some(&mut ptr)).unwrap(); + for (x, y) in [(1usize, 1usize), (5, 5), (6, 6)] { + assert_eq!((ptr as *const u8).add(fp.Offset as usize + y * fp.Footprint.RowPitch as usize + x * 4).cast::<[u8; 4]>().read_unaligned(), [0, 255, 0, 255], "pixel ({x},{y})"); + } + rb.Unmap(0, None); + } + } } From 32f09674a8930d45879f0d169957c0369e835da5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:36:38 +0100 Subject: [PATCH 057/258] D3D12.X: serialize AMD driver PSO calls, honor DispatchX 0x20, gate BVH RT Three AMD RDNA4 stability and ray-tracing fixes: 1. Serialize only the driver Create*PipelineState call in real::driver_pso on AMD adapters (PCI vendor 0x1002, XCL_AMD_SERIAL_PSO=0|1 override) while keeping Direct DXIL / HLSL translation parallel across worker threads, avoiding concurrent amdxc64 compiler crashes. 2. Parse compute [numthreads] in gpu::recomp::pso::compute_threads, track it per compute PSO, and convert thread counts to workgroups in list_x::dispatch_x when D3D12XBOX_DISPATCH_FLAG_USE_THREAD_DIMENSIONS (0x20) is set (preventing 64x over-dispatch of BVH builder passes), with a unit test for thread_dims_to_groups. 3. Detect IMAGE_BVH*_INTERSECT_RAY shaders in gpu::effects::uses_bvh_intersect, enforce an all-or-nothing BVH builder gate in dispatch_x (skipping partial builds if any builder PSO fails), and hold back BVH traversal compute dispatches without stalling the title thread until a builder pass succeeds (XCL_RT_GATE=0 disables). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/effects.rs | 23 +++- crates/xcl/src/gpu/recomp/pso.rs | 13 ++ crates/xcl/src/hle/d3d12x/list_x.rs | 57 ++++++++- crates/xcl/src/hle/d3d12x/pso_async.rs | 13 +- crates/xcl/src/hle/d3d12x/real.rs | 162 ++++++++++++++++++++++++- 5 files changed, 258 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index 4fe79eb859..fcce17c284 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -17,6 +17,8 @@ pub struct Effects { pub memory: bool, /// image stores and image atomics pub images: bool, + /// ray-tracing BVH intersection instructions (`IMAGE_BVH_INTERSECT_RAY` / `IMAGE_BVH64_INTERSECT_RAY`) + pub bvh_intersect: bool, /// instructions in the program pub instructions: usize, } @@ -63,7 +65,10 @@ pub fn of(code: &[u8]) -> Option { let n = d.inst.name; let writes = n.contains("_STORE") || n.contains("_ATOMIC"); match d.enc.name { - "ENC_MIMG" => e.images |= writes, + "ENC_MIMG" => { + e.images |= writes; + e.bvh_intersect |= n == "IMAGE_BVH_INTERSECT_RAY" || n == "IMAGE_BVH64_INTERSECT_RAY"; + } "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_SMEM" => e.memory |= writes, // LDS is the group's own and gone after it; the global data share is not "ENC_DS" => { @@ -104,6 +109,12 @@ pub fn big_and_image_only(blob: &[u8]) -> bool { code.len() >= BIG_CODE && of(&code).is_some_and(|e| !e.memory) } +/// Whether the compute shader `blob` issues `IMAGE_BVH_INTERSECT_RAY` or `IMAGE_BVH64_INTERSECT_RAY`. +pub fn uses_bvh_intersect(blob: &[u8]) -> bool { + let Some(code) = compute_code(blob) else { return false }; + of(&code).is_some_and(|e| e.bvh_intersect) +} + #[cfg(test)] mod tests { use super::*; @@ -121,8 +132,10 @@ mod tests { fn images_and_memory_are_told_apart() { // loads of either kind write nothing let load: (&str, &str, &[(&str, u64)]) = ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]); - assert_eq!(of(&asm(&[MOV, IMAGE_LOAD, load, END])), Some(Effects { memory: false, images: false, instructions: 4 })); - assert_eq!(of(&asm(&[MOV, IMAGE_STORE, END])), Some(Effects { memory: false, images: true, instructions: 3 })); + assert_eq!(of(&asm(&[MOV, IMAGE_LOAD, load, END])), Some(Effects { memory: false, images: false, bvh_intersect: false, instructions: 4 })); + assert_eq!(of(&asm(&[MOV, IMAGE_STORE, END])), Some(Effects { memory: false, images: true, bvh_intersect: false, instructions: 3 })); + let bvh: (&str, &str, &[(&str, u64)]) = ("IMAGE_BVH64_INTERSECT_RAY", "ENC_MIMG", &[("DMASK", 15), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]); + assert_eq!(of(&asm(&[bvh, END])).map(|e| (e.memory, e.images, e.bvh_intersect)), Some((false, false, true))); let image_atomic: (&str, &str, &[(&str, u64)]) = ("IMAGE_ATOMIC_ADD", "ENC_MIMG", &[("DMASK", 1), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]); assert_eq!(of(&asm(&[image_atomic, END])).map(|e| (e.memory, e.images)), Some((false, true))); // every way into memory another pass or an indirect call reads @@ -148,12 +161,12 @@ mod tests { // a branch can jump past an early s_endpgm: a store after it is the program's (were it // constant data instead, taking it for a store only makes binds wait, as before) let store: (&str, &str, &[(&str, u64)]) = ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]); - assert_eq!(of(&asm(&[IMAGE_STORE, END, store, END])), Some(Effects { memory: true, images: true, instructions: 4 })); + assert_eq!(of(&asm(&[IMAGE_STORE, END, store, END])), Some(Effects { memory: true, images: true, bvh_intersect: false, instructions: 4 })); // what does not decode after the end is trailing data let mut code = asm(&[IMAGE_STORE, END]); code.extend_from_slice(&[0xff; 8]); if rdna2::decode(&[0xff; 8], 0).is_err() { - assert_eq!(of(&code), Some(Effects { memory: false, images: true, instructions: 2 })); + assert_eq!(of(&code), Some(Effects { memory: false, images: true, bvh_intersect: false, instructions: 2 })); } } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b04b396d50..b5eb61d71a 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -920,6 +920,19 @@ pub fn compute_user_sgprs(blob: &[u8]) -> Option { } } +/// Thread-group dimensions `[x, y, z]` of a console compute shader (FSPX or FSSM). +pub fn compute_threads(blob: &[u8]) -> Option<[u32; 3]> { + if let Some(f) = fspx(blob) { + return Some(f.threads); + } + let sh = xbox::parse(blob)?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; + match interface(blob, &sh, f)? { + Mode::Compute(cs) => Some(cs.threads), + _ => None, + } +} + /// The HLSL and profile a console program compiles from at pipeline creation (for /// `xcl shaders --export-hlsl`: compile-time investigations outside a title). pub fn console_hlsl(blob: &[u8], stage: Stage, windows: u32, split_wave64: bool) -> Result<(String, &'static str), String> { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 6d69e995a6..0c1af74956 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3022,8 +3022,54 @@ pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min: pc::(this, PC_OM_SET_DEPTH_BOUNDS)(this, min, max); } +/// `D3D12XBOX_DISPATCH_FLAG_USE_THREAD_DIMENSIONS`: `(x, y, z)` are total thread counts rather +/// than workgroup counts (used by `XboxBvhBuilder.dll` BVH build passes). +const DISPATCH_FLAG_USE_THREAD_DIMENSIONS: u32 = 0x20; + +/// Convert `(x, y, z)` thread dimensions into workgroup counts for a compute shader with +/// `[numthreads(tx, ty, tz)]`. Returns `None` if any thread count is 0. +pub(crate) fn thread_dims_to_groups(threads: [u32; 3], group_size: [u32; 3]) -> Option<[u32; 3]> { + if threads[0] == 0 || threads[1] == 0 || threads[2] == 0 { + return None; + } + Some([ + threads[0].div_ceil(group_size[0].max(1)), + threads[1].div_ceil(group_size[1].max(1)), + threads[2].div_ceil(group_size[2].max(1)), + ]) +} + /// command list #78 DispatchX(x, y, z, flags) -pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, _flags: u32) { +pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + if flags & DISPATCH_FLAG_USE_THREAD_DIMENSIONS != 0 { + if super::real::bvh_builder_failed() { + return; + } + let raw_pso = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).map_or(0, |s| s.bound_pso); + let resolved = super::pso_async::resolve_wait(raw_pso); + if !super::real::is_translated_compute_raw(resolved) || super::pso_async::is_pending(raw_pso) { + super::real::note_bvh_builder_failed(raw_pso); + return; + } + let group_size = super::real::pso_compute_threads(raw_pso) + .or_else(|| super::real::pso_compute_threads(resolved)) + .unwrap_or([64, 1, 1]); + let Some([gx, gy, gz]) = thread_dims_to_groups([x, y, z], group_size) else { + return; + }; + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: DispatchX USE_THREAD_DIMENSIONS ({x}, {y}, {z}) / {:?} -> groups ({gx}, {gy}, {gz}) ({} dispatches)", + group_size, + n + 1 + ); + } + super::real::note_bvh_builder_dispatched(); + super::bind::dispatch(this, gx, gy, gz); + return; + } super::bind::dispatch(this, x, y, z); } @@ -7362,4 +7408,13 @@ mod tests { assert!(got.iter().all(|&v| v == 0xDEAD_BEEF), "the UAV was not cleared: {:x?}", &got[..4]); } } + + #[test] + fn thread_dims_to_groups_divides_and_ceils_each_axis() { + assert_eq!(thread_dims_to_groups([0, 1, 1], [64, 1, 1]), None); + assert_eq!(thread_dims_to_groups([64, 1, 1], [64, 1, 1]), Some([1, 1, 1])); + assert_eq!(thread_dims_to_groups([70, 1, 1], [64, 1, 1]), Some([2, 1, 1])); + assert_eq!(thread_dims_to_groups([1920, 1080, 3], [8, 8, 1]), Some([240, 135, 3])); + assert_eq!(thread_dims_to_groups([1, 1, 1], [0, 0, 0]), Some([1, 1, 1])); + } } diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 2702fcf1bc..89340392c2 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -33,6 +33,8 @@ struct Pending { late: std::sync::atomic::AtomicBool, /// its dispatches may be left out while it is built (`image_only`): binds do not wait for it spared: std::sync::atomic::AtomicBool, + /// shader issues `image_bvh*_intersect_ray`: held back without blocking until BVH builds succeed + bvh_traversal: std::sync::atomic::AtomicBool, demand: Mutex, } @@ -385,6 +387,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { orphan: Default::default(), late: Default::default(), spared: Default::default(), + bvh_traversal: Default::default(), demand: Default::default(), }); PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); @@ -1032,7 +1035,7 @@ pub fn resolve_wait(pso: usize) -> usize { fn resolve_wait_for(pso: usize, budget: Option) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); - if p.spared.load(Ordering::Acquire) { + if p.spared.load(Ordering::Acquire) || (p.bvh_traversal.load(Ordering::Acquire) && !super::real::bvh_traversal_allowed()) { return resolve_spared(&p, pso); } // (the title's thread is held from here until the pipeline is built or the budget is over) @@ -1117,6 +1120,14 @@ pub fn image_only(standin: usize) { } } +/// The compute pipeline behind stand-in `standin` issues `image_bvh*_intersect_ray`: binds do not +/// block waiting for it while the BVH builder gate is still closed. +pub fn bvh_traversal(standin: usize) { + if let Some(p) = entry(standin) { + p.bvh_traversal.store(true, Ordering::Release); + } +} + /// `resolve_wait` for a pipeline binds do not wait for (`image_only`): the real one once built, /// else the stand-in, with the build sent to the workers. Nobody waits, so the build is not /// `wanted`: a big one takes its turn among the driver's compiles and waits for free commit. diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fbeb916f80..91613c3392 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -455,6 +455,47 @@ fn wave32_only(device: *mut c_void) -> bool { } } +/// Whether `device` runs on an AMD adapter (PCI vendor ID `0x1002`), cached per device pointer. +fn is_amd_device(device: *mut c_void) -> bool { + use windows::Win32::Graphics::Dxgi::*; + if device.is_null() { + return false; + } + static CACHE: Mutex>> = Mutex::new(None); + let key = device as usize; + if let Some(&v) = CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { + return v; + } + let amd = unsafe { + ID3D12Device::from_raw_borrowed(&device) + .and_then(|dev| { + let luid = dev.GetAdapterLuid(); + let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?; + let adapter: IDXGIAdapter1 = factory.EnumAdapterByLuid(luid).ok()?; + let desc = adapter.GetDesc1().ok()?; + Some(desc.VendorId == 0x1002) + }) + .unwrap_or(false) + }; + CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, amd); + amd +} + +/// Serialize driver `Create*PipelineState` calls on AMD adapters to prevent concurrent compiler +/// access violations on AMD RDNA4 (`XCL_AMD_SERIAL_PSO=0` disables; `=1` forces on all vendors). +/// Direct DXIL / HLSL translation still runs fully in parallel across worker threads. +fn serialize_driver_pso(device: *mut c_void) -> bool { + static OVERRIDE: OnceLock> = OnceLock::new(); + match *OVERRIDE.get_or_init(|| match std::env::var("XCL_AMD_SERIAL_PSO").ok().as_deref().map(str::trim) { + Some("0") => Some(false), + Some("1") => Some(true), + _ => None, + }) { + Some(v) => v, + None => is_amd_device(device), + } +} + /// A wave64 VS / PS may run in 32-lane waves here (`pso::graphics_wave32`: the driver picks /// the wave size of graphics shaders): the split flag for VS / PS translation. Unknown /// device: assume so. @@ -1860,11 +1901,90 @@ fn note_rect_list_gs(pso: usize, copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect } } -/// Whether `pso` runs a translated console compute shader. -pub fn is_translated_compute(pso: usize) -> bool { +/// Thread-group dimensions `[x, y, z]` of console compute PSOs (stand-in and real) for +/// `DispatchX` with `USE_THREAD_DIMENSIONS` (`0x20`). +static PSO_COMPUTE_THREADS: Mutex>> = Mutex::new(None); +/// Compute PSOs (stand-in and real) that issue `image_bvh*_intersect_ray`. +static BVH_TRAVERSAL_PSOS: Mutex>> = Mutex::new(None); +/// At least one `DispatchX(..., 0x20)` BVH builder pass succeeded with no failed builder PSOs. +static BVH_BUILD_READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// At least one `DispatchX(..., 0x20)` BVH builder PSO failed or stayed pending: gate stays closed. +static BVH_BUILD_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn bvh_gate_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_RT_GATE").map_or(true, |v| v.trim() != "0")) +} + +/// Whether BVH traversal compute shaders (`image_bvh*_intersect_ray`) are allowed to run. +pub(super) fn bvh_traversal_allowed() -> bool { + !bvh_gate_enabled() || (BVH_BUILD_READY.load(Ordering::Acquire) && !BVH_BUILD_FAILED.load(Ordering::Acquire)) +} + +/// Whether any BVH builder pass failed (all-or-nothing gate disables further partial builds). +pub(super) fn bvh_builder_failed() -> bool { + bvh_gate_enabled() && BVH_BUILD_FAILED.load(Ordering::Acquire) +} + +pub(super) fn note_bvh_builder_dispatched() { + if !BVH_BUILD_FAILED.load(Ordering::Acquire) && !BVH_BUILD_READY.swap(true, Ordering::AcqRel) { + crate::xlog_info!("D3D12.X: BVH builder dispatch ready — enabling RT traversal shaders"); + } +} + +pub(super) fn note_bvh_builder_failed(pso: usize) { + BVH_BUILD_READY.store(false, Ordering::Release); + if !BVH_BUILD_FAILED.swap(true, Ordering::AcqRel) { + crate::xlog_warn!("D3D12.X: BVH builder PSO {pso:#x} unavailable — holding back partial BVH builds and RT traversal (XCL_RT_GATE=0 to override)"); + } +} + +pub(super) fn pso_compute_threads(pso: usize) -> Option<[u32; 3]> { + if pso == 0 { + return None; + } + PSO_COMPUTE_THREADS.lock().unwrap().as_ref()?.get(&pso).copied() +} + +fn note_compute_threads(pso: usize, cs: &[u8]) { + if pso != 0 { + if let Some(t) = crate::gpu::recomp::pso::compute_threads(cs) { + PSO_COMPUTE_THREADS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, t); + } + } +} + +fn note_bvh_traversal(pso: usize, cs: &[u8]) { + if pso != 0 && crate::gpu::effects::uses_bvh_intersect(cs) { + BVH_TRAVERSAL_PSOS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + } +} + +fn is_bvh_traversal_pso(pso: usize) -> bool { + pso != 0 && BVH_TRAVERSAL_PSOS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) +} + +/// Raw check without BVH traversal hold-back (used by `DispatchX` builder passes). +pub(super) fn is_translated_compute_raw(pso: usize) -> bool { pso != 0 && TRANSLATED_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } +/// Whether `pso` runs a translated console compute shader (holding back BVH traversal shaders +/// until a full BVH build has succeeded with zero failed builder passes). +pub fn is_translated_compute(pso: usize) -> bool { + if !is_translated_compute_raw(pso) { + return false; + } + if bvh_gate_enabled() && is_bvh_traversal_pso(pso) && !bvh_traversal_allowed() { + static LOGGED: std::sync::Once = std::sync::Once::new(); + LOGGED.call_once(|| { + crate::xlog_info!("D3D12.X: holding back BVH traversal compute dispatches until BVH builders succeed (XCL_RT_GATE=0 to disable)"); + }); + return false; + } + true +} + /// compute pipelines the title made from a console shader that runs untranslated: a background /// build's stand-in (until it is resolved) and the fallback of a console shader that failed static CONSOLE_COMPUTE: Mutex>> = Mutex::new(None); @@ -1935,6 +2055,12 @@ fn forget_pso(pso: usize) { if let Some(m) = PSO_USER_SGPRS.lock().unwrap().as_mut() { m.remove(&pso); } + if let Some(m) = PSO_COMPUTE_THREADS.lock().unwrap().as_mut() { + m.remove(&pso); + } + if let Some(s) = BVH_TRAVERSAL_PSOS.lock().unwrap().as_mut() { + s.remove(&pso); + } super::device_x::forget_base(pso); // the compute pass goes with the last user of its entry (`Drop for TwoPassPso`) let gone = TWO_PASS.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)); @@ -3937,9 +4063,21 @@ pub fn switch_form_retries() -> u64 { /// A driver pipeline call; E_OUTOFMEMORY while this thread translates with heap windows is /// noted for `with_switch_fallback`. unsafe fn driver_pso(f: PsoFn, this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + static AMD_DRIVER_PSO_LOCK: Mutex<()> = Mutex::new(()); let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; let injected = heap && INJECTED_OOM.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)).is_ok(); - let hr = if injected { E_OUTOFMEMORY } else { f(this, desc, riid, ppv) }; + let hr = if injected { + E_OUTOFMEMORY + } else if serialize_driver_pso(this) { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + crate::xlog_info!("D3D12.X: serializing driver Create*PipelineState on AMD adapter (XCL_AMD_SERIAL_PSO=0 to disable)"); + }); + let _guard = AMD_DRIVER_PSO_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + f(this, desc, riid, ppv) + } else { + f(this, desc, riid, ppv) + }; if hr == E_OUTOFMEMORY && heap { HEAP_WINDOW_OOM.with(|o| o.set(true)); } @@ -4487,6 +4625,8 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } + note_compute_threads(*ppv as usize, cs); + note_bvh_traversal(*ppv as usize, cs); note_translated_compute(0, ppv); TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); return Some(Ok(0)); @@ -4519,6 +4659,8 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } + note_compute_threads(*ppv as usize, cs); + note_bvh_traversal(*ppv as usize, cs); note_translated_compute(hr, ppv); crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", @@ -5735,6 +5877,17 @@ unsafe fn go_background( let key = owned.shaders_key(); // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); + let bvh_trav = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::uses_bvh_intersect(b))); + if compute { + if let OwnedDesc::Compute(_, b) = &owned { + if let Some(cs) = b.first() { + note_compute_threads(*ppv as usize, cs); + } + } + if bvh_trav { + BVH_TRAVERSAL_PSOS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + } + } let job: super::pso_async::Job = Box::new(move || { let mut out: *mut c_void = std::ptr::null_mut(); if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { @@ -5754,6 +5907,9 @@ unsafe fn go_background( if image_only { super::pso_async::image_only(*ppv as usize); } + if bvh_trav { + super::pso_async::bvh_traversal(*ppv as usize); + } Some(hr) } From b124884456dfde1312c5de894aac417de24e29b6 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:01:55 +0100 Subject: [PATCH 058/258] D3D12.X: make AMD_DRIVER_PSO_LOCK opt-in via XCL_AMD_SERIAL_PSO=1 Serializing every Create*PipelineState behind a global mutex blocked urgent title-thread and cached-blob PSOs for 142+ s behind slow background compiles. Default off (XCL_AMD_SERIAL_PSO=1 or =auto to enable) since big_compile_turn already gates huge background compiles. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 91613c3392..ea7094f3b1 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -481,15 +481,16 @@ fn is_amd_device(device: *mut c_void) -> bool { amd } -/// Serialize driver `Create*PipelineState` calls on AMD adapters to prevent concurrent compiler -/// access violations on AMD RDNA4 (`XCL_AMD_SERIAL_PSO=0` disables; `=1` forces on all vendors). -/// Direct DXIL / HLSL translation still runs fully in parallel across worker threads. +/// Serialize driver `Create*PipelineState` calls when explicitly requested (`XCL_AMD_SERIAL_PSO=1` +/// forces on all vendors; `=auto` serializes on AMD adapters). Default is off because +/// `big_compile_turn` already gates huge background compiles without blocking urgent title-thread +/// and cached PSO creation behind multi-minute background shader builds. fn serialize_driver_pso(device: *mut c_void) -> bool { static OVERRIDE: OnceLock> = OnceLock::new(); match *OVERRIDE.get_or_init(|| match std::env::var("XCL_AMD_SERIAL_PSO").ok().as_deref().map(str::trim) { - Some("0") => Some(false), Some("1") => Some(true), - _ => None, + Some("auto") => None, + _ => Some(false), }) { Some(v) => v, None => is_amd_device(device), From cd7e64e030fb6cf67fb3be22adaa5e01cf721f4c Mon Sep 17 00:00:00 2001 From: Digitaw <326406099+Digit4w@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:21:56 -0300 Subject: [PATCH 059/258] D3D12.X: a create that fails on a lost device keeps the driver's blob A pipeline create that was given a driver blob and failed dropped the blob, in memory and on disk, whatever the HRESULT was. A removed or hung device and a driver out of memory fail every create, with a blob or without one, so those failures say nothing about the blob. After a device removal the title lives on for a second or two before it is stopped, and every pipeline it creates in that time deleted a valid file; the next run built those pipelines in the driver again. driver_cache::refused(hr) now decides: DXGI_ERROR_DEVICE_REMOVED, _HUNG, _RESET and E_OUTOFMEMORY keep the blob, every other failure drops it as before. Used by the three creates that take a blob (compute, graphics, the compute pass of a two-pass pipeline). The retry without the blob is unchanged. Measured on 68a284a, RTX 4070 SUPER, a retail title, with the device removed during loading by a local ID3D12Device5::RemoveDevice() switch that is not part of this commit. Compute creates with a blob that failed after the removal (all 0x887a0005) and blob files gone afterwards: main 12/12, 24/24, 12/12; with this change 24/0, 12/0. In a next run under an exe name the driver's own cache had never seen, the 24 pipelines took 22.1 s in the driver without their blobs and 0.7 s with them. No graphics create with a blob fell after the removal in those runs: the graphics path is covered by the unit test only. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/real.rs | 66 +++++++++++++++++++++++++++---- 1 file changed, 59 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5b4094af4d..ce04c366e5 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4756,9 +4756,11 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL ); if hr < 0 && cached.is_some() { // a blob the driver does not take (another root signature at the same address…): compiled - forget_compute_blob(key); - if from_disk { - driver_cache::note(false, disk.as_deref()); + if driver_cache::refused(hr) { + forget_compute_blob(key); + if from_disk { + driver_cache::note(false, disk.as_deref()); + } } copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let (retried, took) = driver_compile_identified( @@ -4841,6 +4843,16 @@ pub(crate) mod driver_cache { std::fs::read(p).ok().filter(|b| !b.is_empty()) } + /// Whether a create that failed with `hr` refused the blob it was given. A removed or hung + /// device and a driver out of memory fail every create, with a blob or without one, and + /// say nothing about the blob: it is kept. (A retail title's run that ended in a device + /// removal dropped the blobs of 15 large compute programs in its last two seconds; the next + /// run built them again, 10 – 18 s each.) + pub fn refused(hr: crate::util::HRESULT) -> bool { + use windows::Win32::Graphics::Dxgi::{DXGI_ERROR_DEVICE_HUNG, DXGI_ERROR_DEVICE_REMOVED, DXGI_ERROR_DEVICE_RESET}; + hr < 0 && ![DXGI_ERROR_DEVICE_REMOVED.0, DXGI_ERROR_DEVICE_HUNG.0, DXGI_ERROR_DEVICE_RESET.0, crate::util::E_OUTOFMEMORY].contains(&hr) + } + /// A pipeline was made from a kept blob (`ok`), or the driver refused the blob: dropped. pub fn note(ok: bool, p: Option<&Path>) { if ok { @@ -4945,6 +4957,19 @@ pub(crate) mod driver_cache { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_lost_device_or_no_memory_does_not_refuse_a_blob() { + use crate::util::{E_INVALIDARG, E_OUTOFMEMORY}; + use windows::Win32::Graphics::Dxgi::{DXGI_ERROR_DEVICE_HUNG, DXGI_ERROR_DEVICE_REMOVED, DXGI_ERROR_DEVICE_RESET}; + // the driver's answers to a blob of another driver, adapter or root signature + for hr in [E_INVALIDARG, 0x887E_0001u32 as i32, 0x887E_0002u32 as i32, 0x8000_4005u32 as i32] { + assert!(refused(hr), "{hr:#x}"); + } + for hr in [DXGI_ERROR_DEVICE_REMOVED.0, DXGI_ERROR_DEVICE_HUNG.0, DXGI_ERROR_DEVICE_RESET.0, E_OUTOFMEMORY, 0, 1] { + assert!(!refused(hr), "{hr:#x}"); + } + } + #[test] fn an_overlapping_writer_cannot_modify_the_published_blob() { use std::io::Write; @@ -5336,6 +5361,29 @@ mod graphics_blob_tests { assert_eq!((attempts[1].0.as_str(), attempts[1].1, attempts[1].2), ("graphics retry", false, 0)); } + #[test] + fn cached_graphics_blob_is_kept_when_the_device_is_removed() { + let removed = windows::Win32::Graphics::Dxgi::DXGI_ERROR_DEVICE_REMOVED.0; + let blob = [0xEFu8; 32]; + let mut copy = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + let mut calls = 0usize; + let build = create_graphics_pso_cached( + &mut copy, + Some(&blob), + false, + || panic!("a removed device says nothing about the blob: it must not be evicted"), + |_, _, f| (f(), std::time::Duration::from_millis(1)), + |_| { + calls += 1; + removed + }, + ); + assert_eq!(build.hr, removed); + assert_eq!(calls, 2, "with the blob, then without it"); + assert!(!build.reused); + assert!(!build.cache_eligible); + } + #[test] fn rect_list_gs_fallback_does_not_cache_under_with_gs_key() { const E_INVALIDARG: HRESULT = -2147024809; @@ -5415,7 +5463,9 @@ fn create_graphics_pso_cached( if hr >= 0 { return GraphicsPsoBuild { hr, in_driver, reused: true, cache_eligible: false }; } - on_stale_cache(); + if driver_cache::refused(hr) { + on_stale_cache(); + } copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let (retried, took) = run("graphics retry", false, &mut || retry_without_rect_gs(copy, rect_gs, &mut create)); let dropped_rect_gs = rect_gs && copy.GS.pShaderBytecode.is_null(); @@ -6306,9 +6356,11 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); if hc < 0 && ccached.is_some() { - forget_compute_blob(ckey); - if cfrom_disk { - driver_cache::note(false, cdisk.as_deref()); + if driver_cache::refused(hc) { + forget_compute_blob(ckey); + if cfrom_disk { + driver_cache::note(false, cdisk.as_deref()); + } } cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); compute = std::ptr::null_mut(); From 5730337550a71cfb27ee08d18241ab6a1466b6c4 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:40:56 +0100 Subject: [PATCH 060/258] D3D12.X: batch vram tile-mapping fence signals into before_execute Pages::map and Pages::unmap previously called queue.Signal(&self.fence, ...) synchronously on every placed texture (~42,600 kernel transitions during world streaming). Defer the fence signal behind a dirty_signal flag and flush it once per queue submission in before_execute() (and before capturing unmap_mark for heap retirement), preserving strict GPU ordering while removing per-texture Signal overhead. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/vram.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 46d22ef9c4..b0f9d13b70 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -583,9 +583,11 @@ fn keep_spare_pools() -> usize { /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { queue: ID3D12CommandQueue, - /// signalled after each mapping; title queues wait for it before their next work + /// signalled after mappings before GPU queues execute; title queues wait for it before their next work fence: ID3D12Fence, value: u64, + /// true when `map()` / `unmap()` queued tile mappings not yet followed by `queue.Signal` + dirty_signal: bool, /// per-device timestamp of the last periodic reclaim check last_reclaim: std::time::Instant, pools: PoolHeaps, @@ -633,6 +635,7 @@ impl Pages { queue, fence, value: 0, + dirty_signal: false, last_reclaim: std::time::Instant::now(), pools: PoolHeaps::new(), pool: TilePool::new(), @@ -720,9 +723,7 @@ impl Pages { D3D12_TILE_MAPPING_FLAG_NONE, ); } - let _timer = step(Step::Signal); - self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + self.dirty_signal = true; } /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return @@ -746,8 +747,17 @@ impl Pages { Some(&total), D3D12_TILE_MAPPING_FLAG_NONE, ); - self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + self.dirty_signal = true; + } + + /// Emit one `queue.Signal` covering all batched `map()` / `unmap()` calls since the last flush. + unsafe fn flush_signal(&mut self) { + if self.dirty_signal { + let _timer = step(Step::Signal); + self.value += 1; + let _ = self.queue.Signal(&self.fence, self.value); + self.dirty_signal = false; + } } fn release_tiles(&mut self, used: Vec, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) { @@ -1222,6 +1232,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { + pages.flush_signal(); let key = queue.as_raw() as usize; if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { let _ = queue.Wait(&pages.fence, pages.value); @@ -1233,6 +1244,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { do_reclaim = true; newly_reclaimed = pages.sweep_and_reclaim(now); if !newly_reclaimed.is_empty() { + pages.flush_signal(); unmap_mark = Some((pages.fence.clone(), pages.value)); } } From 70e600d5c6a8484ded6174d70cacff2abbedc286 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:40:56 +0100 Subject: [PATCH 061/258] Recompiler: guard 32-bit raw-buffer OOB wraparound in Direct DXIL In Direct DXIL mubuf and buffer_atomic (stride == 0), off = voff + OFFSET and e = off + bytes were compared against d2 without checking for 32-bit unsigned wraparound (#1893). A large voff near 2^32 wrapped below d2 and passed the OOB guard while 64-bit buffer_window() carried into the adjacent 4 GiB UMA window. Check unsigned carry in pure 32-bit arithmetic (off >= voff when OFFSET != 0, and e >= off) before comparing e <= d2, avoiding i64 promotion while closing the wraparound bypass. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/core_tests.rs | 17 +++++++++++++++ crates/xcl/src/gpu/dxil/lower_mem.rs | 31 +++++++++++++++++++++------ 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index dda5533f6e..a6ecb0dbda 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -615,6 +615,23 @@ fn window_at_lowers_to_32bit_carry_without_int64() { } } +#[test] +fn raw_buffer_oob_check_guards_32bit_wraparound() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 2, sampler_base: 0 }; + // Non-zero OFFSET + OFFEN on a raw buffer load/atomic must emit unsigned wraparound checks + // (`icmp uge`) for both `voff + OFFSET` and `off + bytes` (#1893). + let code = prog(&[ + ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 3), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 16)], None), + ("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 16)], None), + ]); + let dxil = translate(&code, ko).expect("mubuf + atomic translates"); + super::validate::validate(&dxil).expect("validates"); + if let Ok(dis) = super::validate::disassemble(&dxil) { + let uge = dis.matches("icmp uge i32").count(); + assert!(uge >= 4, "expected wraparound icmp uge checks for load and atomic (got {uge}):\n{dis}"); + } +} + #[test] fn dot8_u32_u4_unclamped_lowers_to_dot4_add_u8_packed() { use crate::gpu::recomp::{dxc, runner}; diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 17069ff6b5..78d15e20ad 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -1178,18 +1178,29 @@ impl Lw { let voff = if offen { self.vreg(vaddr + idxen as u64) } else { self.c(0) }; let stride = self.lshrc(d1, 16); let stride = self.andc(stride, 0x3FFF); - let off = self.addc(voff, f("OFFSET") as u32); + let imm_off = f("OFFSET") as u32; + let off = self.addc(voff, imm_off); + // 32-bit unsigned add `voff + imm_off` wraps iff `off < voff`; catch wraparound so a + // huge `voff` cannot wrap below `d2` while 64-bit `buffer_window()` carries into the next + // 4 GiB UMA window (#1893). + let off_no_wrap = if imm_off != 0 { Some(self.cmp(Pred::UGe, off, voff)) } else { None }; let a = self.add(d0, soff); let a = self.add(a, off); let si = self.mul(stride, index); let a = self.add(a, si); - self.buffer_window(d0, d1, &[Ea::U(soff), Ea::U(voff), Ea::K(f("OFFSET") as u32), Ea::Mul(stride, index)], name.contains("store")); + self.buffer_window(d0, d1, &[Ea::U(soff), Ea::U(voff), Ea::K(imm_off), Ea::Mul(stride, index)], name.contains("store")); let act = self.act(); let szero = self.cmpc(Pred::Eq, stride, 0); let idx_ok = self.cmp(Pred::ULt, index, d2); let in_range = |lw: &mut Lw, bytes: Value| -> Value { let e = lw.add(off, bytes); - let ok = lw.cmp(Pred::ULe, e, d2); + let e_no_wrap = lw.cmp(Pred::UGe, e, off); + let in_bounds = lw.cmp(Pred::ULe, e, d2); + let ok = lw.land(e_no_wrap, in_bounds); + let ok = match off_no_wrap { + Some(nw) => lw.land(nw, ok), + None => ok, + }; lw.sel(szero, ok, idx_ok) }; if let Some((n, signed, store, half)) = d16s { @@ -1828,16 +1839,24 @@ impl Lw { let bytes = if x2 { 8 } else { 4 }; let stride = self.lshrc(d1, 16); let stride = self.andc(stride, 0x3FFF); - let off = self.addc(voff, f("OFFSET") as u32); + let imm_off = f("OFFSET") as u32; + let off = self.addc(voff, imm_off); + let off_no_wrap = if imm_off != 0 { Some(self.cmp(Pred::UGe, off, voff)) } else { None }; let a = self.add(d0, soff); let a = self.add(a, off); let si = self.mul(stride, index); let a = self.add(a, si); - self.buffer_window(d0, d1, &[Ea::U(soff), Ea::U(voff), Ea::K(f("OFFSET") as u32), Ea::Mul(stride, index)], true); + self.buffer_window(d0, d1, &[Ea::U(soff), Ea::U(voff), Ea::K(imm_off), Ea::Mul(stride, index)], true); let a = self.andc(a, !(bytes - 1)); let szero = self.cmpc(Pred::Eq, stride, 0); let e = self.addc(off, bytes); - let r1 = self.cmp(Pred::ULe, e, d2); + let e_no_wrap = self.cmp(Pred::UGe, e, off); + let in_bounds = self.cmp(Pred::ULe, e, d2); + let r1 = self.land(e_no_wrap, in_bounds); + let r1 = match off_no_wrap { + Some(nw) => self.land(nw, r1), + None => r1, + }; let r2 = self.cmp(Pred::ULt, index, d2); let ok = self.sel(szero, r1, r2); let act = self.act(); From 354efa2f4e84dd25423019dc0ce3eaaaf9e6a260 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:40:56 +0100 Subject: [PATCH 062/258] Recompiler: honour emit and cut ops on geometry s_sendmsg MSG_GS_DONE Both Direct DXIL (lower_geom.rs) and HLSL (emit.rs) only handled s_sendmsg msg == 2 (MSG_GS) and ignored msg == 3 (MSG_GS_DONE) even when op != 0 (cut, emit, or emit+cut on stream 0), dropping the final strip vertices/triangles emitted by geometry shaders (#2412). Handle msg == 2 | 3 when stream == 0 and op != 0 on both backends. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/lower_geom.rs | 5 +++-- crates/xcl/src/gpu/recomp/emit.rs | 7 +++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_geom.rs b/crates/xcl/src/gpu/dxil/lower_geom.rs index cff04b289e..f01aa7ec7a 100644 --- a/crates/xcl/src/gpu/dxil/lower_geom.rs +++ b/crates/xcl/src/gpu/dxil/lower_geom.rs @@ -42,10 +42,11 @@ impl Lw { match name { "s_barrier" if self.split && gs_phase => Some(()), "s_sendmsg" => { - // MSG_GS (2): op 1 cut, 2 emit, 3 emit + cut (stream 0); the rest: nothing + // MSG_GS (2) and MSG_GS_DONE (3): op 1 cut, 2 emit, 3 emit + cut (stream 0); + // op 0 (NOP / bare done) and other messages do nothing here. let simm = rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0); let (msg, op, stream) = (simm & 0xF, (simm >> 4) & 3, (simm >> 8) & 3); - if msg == 2 && stream == 0 { + if matches!(msg, 2 | 3) && stream == 0 && op != 0 { self.gs_emit_cut(op); } Some(()) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index e133c22010..c8dc7e228b 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1346,10 +1346,13 @@ impl Em { Flow::Next } "s_sendmsg" if matches!(self.opt.mode, Mode::Geometry(_)) => { - // MSG_GS (2): op 1 cut, 2 emit, 3 emit + cut (stream 0); GS_DONE (3) – nothing to do + // MSG_GS (2) and MSG_GS_DONE (3): op 1 cut, 2 emit, 3 emit + cut (stream 0) let simm = rdna2::field_value(d.enc, &d.words, "SIMM16").unwrap_or(0); let (msg, op, stream) = (simm & 0xF, (simm >> 4) & 3, (simm >> 8) & 3); - if let (2, 0, Mode::Geometry(g)) = (msg, stream, &self.opt.mode) { + if let (2 | 3, 0, Mode::Geometry(g)) = (msg, stream, &self.opt.mode) { + if op == 0 { + return Flow::Next; + } let maxt = g.max_vertex_count.saturating_sub(2).max(1); let act = self.act(); if op & 2 != 0 { From 2c33f9f2a60dcf3825d04e80e0ed8c9c6632b77f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:41:14 +0100 Subject: [PATCH 063/258] Recompiler: fix Direct DXIL live double-ext scan and movrel VGPR range Fixes two Direct DXIL correctness bugs (#1894, #1890): - Module::uses_double_extensions now iterates live instructions in self.blocks (matching insts_use_type) instead of all self.insts, preventing DCE-removed f64 ops from spuriously setting DoubleExtensions shader flags. - Lw::top_vgpr now incorporates Lw::max_vgpr precomputed across all decoded instructions (init.touched is empty outside Entry::Kernel), and v_movrels / v_movreld / v_movrelsd mask M0 to M0[7:0] (& 0xFF) per RDNA2 ISA. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/core_tests.rs | 20 ++++++++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 9 +++++++++ crates/xcl/src/gpu/dxil/lower.rs | 2 ++ crates/xcl/src/gpu/dxil/lower_wide.rs | 12 ++++++++---- crates/xcl/src/gpu/dxil/module.rs | 13 ++++++++----- 5 files changed, 47 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index a6ecb0dbda..8494a68bb7 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -632,6 +632,26 @@ fn raw_buffer_oob_check_guards_32bit_wraparound() { } } +#[test] +fn compute_movrel_uses_program_max_vgpr_and_masks_m0() { + use crate::gpu::recomp::CsInterface; + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + // Compute mode (not Entry::Kernel): v_movrels_b32 reading v[1 + (m0 & 0xFF)] when v5 is + // written later in the shader must still include k=4 (v5) in the switch and mask m0 & 0xFF. + let code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 129)], None), + ("V_MOVRELS_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", 256 + 1)], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 130)], None), + ]); + let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; + let k = super::kernel::translate_compute(&code, ko, &cs).expect("compute movrel translates"); + super::validate::validate(&k.dxil).expect("validates"); + if let Ok(dis) = super::validate::disassemble(&k.dxil) { + assert!(dis.contains("and i32") && dis.contains(", 255"), "expected m0 & 0xFF mask:\n{dis}"); + assert!(dis.contains("icmp eq i32") && dis.contains(", 4"), "expected k=4 (v5) branch from max_vgpr:\n{dis}"); + } +} + #[test] fn dot8_u32_u4_unclamped_lowers_to_dot4_add_u8_packed() { use crate::gpu::recomp::{dxc, runner}; diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index a51ac76ebc..e7066a713a 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -522,6 +522,15 @@ impl Lw { has_f64_round_op: false, img_writes: crate::gpu::recomp::emit::image_write_srsrcs(insts), barrier_uav_fence: crate::gpu::recomp::emit::has_uav_write_or_glc(insts), + max_vgpr: insts + .iter() + .flat_map(|d| { + let (r, w) = crate::gpu::rdna2::vgpr_uses(d); + r.into_iter().chain(w) + }) + .filter(|&v| v < 256) + .max() + .unwrap_or(0), exec_cache: HashMap::new(), xs: None, xw: None, diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index a0af2c8f88..53b63bdb6a 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -218,6 +218,8 @@ pub struct Lw { pub img_writes: Vec, /// program writes/atomics global or image UAVs or uses `GLC=1`: `s_barrier` emits `ALL_SYNC` pub barrier_uav_fence: bool, + /// highest VGPR index referenced by the program (for `v_movrel*` outside `Entry::Kernel`) + pub max_vgpr: u64, /// static samplers bound so far: (S#, comparison, handle) at `s, space1` pub static_used: Vec<([u32; 4], bool, super::ops::Sampler)>, pub sampler_base: u32, diff --git a/crates/xcl/src/gpu/dxil/lower_wide.rs b/crates/xcl/src/gpu/dxil/lower_wide.rs index 91f90ffddc..b52981140d 100644 --- a/crates/xcl/src/gpu/dxil/lower_wide.rs +++ b/crates/xcl/src/gpu/dxil/lower_wide.rs @@ -280,7 +280,8 @@ impl Lw { /// The highest VGPR the program names (relative moves index up to it). fn top_vgpr(&self) -> u64 { - self.init.touched.iter().filter(|&&v| (VAR_VGPR..VAR_VGPR + 256).contains(&v)).map(|&v| (v - VAR_VGPR) as u64).max().unwrap_or(0) + let touched = self.init.touched.iter().filter(|&&v| (VAR_VGPR..VAR_VGPR + 256).contains(&v)).map(|&v| (v - VAR_VGPR) as u64).max().unwrap_or(0); + touched.max(self.max_vgpr) } pub fn movrel(&mut self, d: &Decoded, name: &str) -> LResult<()> { @@ -292,9 +293,12 @@ impl Lw { let m0 = self.sreg(124); let top = self.top_vgpr().max(vdst).max(src_code.saturating_sub(256)); let (rd_idx, wr_idx) = match name { - "v_movrels_b32" => (Some(m0), None), - "v_movreld_b32" => (None, Some(m0)), - "v_movrelsd_b32" => (Some(m0), Some(m0)), + "v_movrels_b32" => (Some(self.andc(m0, 0xFF)), None), + "v_movreld_b32" => (None, Some(self.andc(m0, 0xFF))), + "v_movrelsd_b32" => { + let m = self.andc(m0, 0xFF); + (Some(m), Some(m)) + } "v_movrelsd_2_b32" => { let r = self.andc(m0, 0x3FF); let w = self.lshrc(m0, 16); diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index a7f0128da4..6b00340eba 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -1426,11 +1426,14 @@ impl Module { /// integers (DXC's shader-flag rules; `Fma` is flagged by its helper). pub fn uses_double_extensions(&self) -> bool { let Some(f64) = self.type_ids.get(&TypeDef::Double).copied() else { return false }; - self.insts.iter().any(|d| match &d.op { - Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, - Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, - Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, - _ => false, + self.blocks.iter().flatten().any(|&i| { + let d = &self.insts[i as usize]; + match &d.op { + Op::Bin(BinOp::UDiv | BinOp::SDiv, ..) => d.ty == f64, + Op::Cast(CastOp::FPToUI | CastOp::FPToSI, v, _) => self.value_ty(*v) == f64, + Op::Cast(CastOp::UIToFP | CastOp::SIToFP, _, t) => *t == f64, + _ => false, + } }) } pub fn insts_use_type(&self, t: Ty) -> bool { From fcb17c951f40220a2adbd1a3655614c7c3793d1e Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:54:05 +0100 Subject: [PATCH 064/258] D3D12.X: bind shared view heap before console ClearUnorderedAccessView* MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a console-slot ClearUnorderedAccessViewUint or ClearUnorderedAccessViewFloat resolves its GPU descriptor handle into console_heap::global_heap(), D3D12 requires that shader-visible heap to be currently bound on the command list. After Reset() or SetDescriptorHeaps(0, NULL) — and whenever XCL_HEAP_WINDOWS is off so ensure_view_heap() leaves the view heap unbound — the clear could miss its descriptor heap and be dropped (for example OIT 0x7f800000 clears). Bind console_heap::global_heap() on both list_x::clear_uav and console_list CLEAR_UAV_MARKER replay whenever the console GPU slot is backed by the shared heap, preserving any currently bound sampler heap and skipping SetDescriptorHeaps when already bound. Adds unit coverage for heap binding and shared-slot detection. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/console_list.rs | 31 +++++++++ crates/xcl/src/hle/d3d12x/list_x.rs | 85 +++++++++++++++++++---- 2 files changed, 103 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 48f5b4db36..93db4a9fc1 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -772,6 +772,34 @@ unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Ve ensure_dispatch_heaps_with(list, bound, has_sampler, view, sampler); } +unsafe fn ensure_uav_clear_heap(list: &ID3D12GraphicsCommandList, bound: &mut Vec, has_sampler: &mut bool) { + let mut dev: Option = None; + let _ = list.GetDevice(&mut dev); + let view = super::console_heap::global_heap(); + let view = match dev.as_ref().map(|d| d.as_raw() as usize) { + Some(dev_raw) => heap_on_device(view, dev_raw), + None => view, + }; + let Some(view) = view else { return }; + if bound.iter().any(|h| h.as_raw() == view.as_raw()) { + return; + } + let sampler = (*has_sampler) + .then(|| bound.iter().find(|h| h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER).cloned()) + .flatten(); + let mut next = Vec::with_capacity(2); + next.push(view); + if let Some(s) = sampler { + next.push(s); + *has_sampler = true; + } else { + *has_sampler = false; + } + let args: Vec> = next.iter().cloned().map(Some).collect(); + list.SetDescriptorHeaps(&args); + *bound = next; +} + /// Turn the recorded console commands into commands on the PC list and close it. pub unsafe fn close(obj: *mut c_void) -> Result { let obj = obj as usize; @@ -870,6 +898,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let (gpu, cpu) = (super::console_heap::slot(q(0)), super::console_heap::slot(q(1))); match (gpu, cpu, ID3D12Resource::from_raw_borrowed(&res)) { (Some(g), Some(c), Some(r)) if g.pc_gpu_uav != 0 => { + if g.shared_srv != 0 { + ensure_uav_clear_heap(&list, &mut bound_heaps, &mut has_sampler_heap); + } let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: g.pc_gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); if get(1) != 0 { let f = values.map(f32::from_bits); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 0c1af74956..0fa07a2fdd 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3910,6 +3910,43 @@ pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec bool) -> Option<(Vec, bool)> { + if current.contains(&view) { + return None; + } + if has_sampler { + if let Some(&s) = current.iter().find(|&&p| is_sampler(p)) { + return Some((vec![view, s], true)); + } + } + Some((vec![view], false)) +} + +/// Bind `console_heap::global_heap()` on `this` when a console-slot `ClearUnorderedAccessView*` +/// passes a GPU handle from the shared view heap and that heap is not currently bound (for +/// example after `Reset()` or `SetDescriptorHeaps(0, NULL)`, even when `heap_windows()` is off). +unsafe fn ensure_console_view_heap(this: *mut c_void) { + let Some(view) = super::console_heap::global_heap() else { return }; + let view_raw = view.as_raw() as usize; + let mut to_bind: Option> = None; + with_bindings(this, |b| { + let next = bind_view_heap(view_raw, &b.heaps, b.has_sampler_heap, |p| { + let p = p as *mut c_void; + ID3D12DescriptorHeap::from_raw_borrowed(&p).is_some_and(|h| h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) + }); + if let Some((next, has_sampler)) = next { + b.heaps = next.clone(); + b.has_sampler_heap = has_sampler; + to_bind = Some(next); + } + }); + if let Some(raw) = to_bind { + pc::(this, 28)(this, raw.len() as u32, raw.as_ptr()); + } +} + /// Translated shaders with directly-indexed root signatures (`CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` /// / `SAMPLER_HEAP_DIRECTLY_INDEXED`) and heap windows (`pso::heap_windows`) require valid /// shader-visible view and sampler heaps to be bound even if the title bound 0 heaps (or only a @@ -4495,8 +4532,8 @@ const PC_CLEAR_UAV_FLOAT: usize = 50; #[derive(Debug, PartialEq)] enum UavClearHandles { /// both are console slots: their PC UAVs (GPU: in the heap lists bind; CPU: in the - /// title's CPU-only heap) - Console { gpu: u64, cpu: u64 }, + /// title's CPU-only heap); `shared` is true when `gpu` lives in `console_heap::global_heap()` + Console { gpu: u64, cpu: u64, shared: bool }, /// neither is a console slot: PC handles already Pc, /// one console slot and one not, or a slot with no shader-visible UAV @@ -4506,7 +4543,9 @@ enum UavClearHandles { fn uav_clear_handles(gpu: Option, cpu: Option) -> UavClearHandles { match (gpu, cpu) { (None, None) => UavClearHandles::Pc, - (Some(g), Some(c)) if !g.sampler && !c.sampler && g.pc_gpu_uav != 0 => UavClearHandles::Console { gpu: g.pc_gpu_uav, cpu: c.pc_uav }, + (Some(g), Some(c)) if !g.sampler && !c.sampler && g.pc_gpu_uav != 0 => { + UavClearHandles::Console { gpu: g.pc_gpu_uav, cpu: c.pc_uav, shared: g.shared_srv != 0 } + } _ => UavClearHandles::Unusable, } } @@ -4515,9 +4554,9 @@ fn uav_clear_handles(gpu: Option, cpu: Option (gpu, cpu), - UavClearHandles::Pc => (gpu, cpu), + let (gpu, cpu, shared) = match uav_clear_handles(super::console_heap::slot(gpu), super::console_heap::slot(cpu)) { + UavClearHandles::Console { gpu, cpu, shared } => (gpu, cpu, shared), + UavClearHandles::Pc => (gpu, cpu, false), UavClearHandles::Unusable => { static N: AtomicU64 = AtomicU64::new(0); if once(&N, 1) { @@ -4526,6 +4565,9 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi return; } }; + if shared { + ensure_console_view_heap(this); + } pc::(this, slot)(this, gpu, cpu, res, values, n, rects) } @@ -7286,21 +7328,38 @@ mod tests { assert_eq!(default_bound_heaps(Some(0x10), Some(0x20), &[0x10, 0x99], true), None); } + #[test] + fn bind_view_heap_binds_shared_heap_after_reset_and_preserves_sampler() { + let is_sampler = |p: usize| p == 0x20 || p == 0x99; + // Empty after Reset() / SetDescriptorHeaps(0, NULL) -> binds shared view heap + assert_eq!(bind_view_heap(0x10, &[], false, is_sampler), Some((vec![0x10], false))); + // Shared view heap already bound -> no-op + assert_eq!(bind_view_heap(0x10, &[0x10], false, is_sampler), None); + assert_eq!(bind_view_heap(0x10, &[0x10, 0x20], true, is_sampler), None); + // Sampler heap bound alone -> bind shared view heap alongside it + assert_eq!(bind_view_heap(0x10, &[0x20], true, is_sampler), Some((vec![0x10, 0x20], true))); + // Different view heap bound with sampler -> replace view heap while keeping sampler + assert_eq!(bind_view_heap(0x10, &[0x77, 0x99], true, is_sampler), Some((vec![0x10, 0x99], true))); + // Different view heap bound alone -> replace with shared view heap + assert_eq!(bind_view_heap(0x10, &[0x77], false, is_sampler), Some((vec![0x10], false))); + } + /// ClearUnorderedAccessView* handles: two console slots → their PC UAVs, two PC handles as /// they are, anything else not usable. #[test] fn uav_clear_handles_translate_console_slots() { use super::super::console_heap::Slot; - let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0 }); - assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), s(0x20, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20 }); + let s = |pc_uav: u64, pc_gpu_uav: u64, shared_srv: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv, k: 0 }); + assert_eq!(uav_clear_handles(s(0x10, 0x5010, 0, false), s(0x20, 0, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20, shared: false }); + assert_eq!(uav_clear_handles(s(0x10, 0x5010, 0x9000, false), s(0x20, 0, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20, shared: true }); assert_eq!(uav_clear_handles(None, None), UavClearHandles::Pc); // a console slot beside a PC handle, a GPU slot of a heap that is not shader visible, // sampler slots - assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), None), UavClearHandles::Unusable); - assert_eq!(uav_clear_handles(None, s(0x20, 0, false)), UavClearHandles::Unusable); - assert_eq!(uav_clear_handles(s(0x10, 0, false), s(0x20, 0, false)), UavClearHandles::Unusable); - assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), s(0, 0, true)), UavClearHandles::Unusable); - assert_eq!(uav_clear_handles(s(0, 0, true), s(0x20, 0, false)), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(s(0x10, 0x5010, 0, false), None), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(None, s(0x20, 0, 0, false)), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(s(0x10, 0, 0, false), s(0x20, 0, 0, false)), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(s(0x10, 0x5010, 0, false), s(0, 0, 0, true)), UavClearHandles::Unusable); + assert_eq!(uav_clear_handles(s(0, 0, 0, true), s(0x20, 0, 0, false)), UavClearHandles::Unusable); } /// Console code clears a UAV with its console heap slots (heap #9 / #10 give it their From e74b7c20b1b1b234237c9ac3a5248f0122d4f0a4 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:54:05 +0100 Subject: [PATCH 065/258] D3D12.X: evict unmapped and stale GPU-view mirror tiles in sparse windows Mirrored GPU-view buffer tiles (#2384) previously stayed mapped indefinitely, causing sessions to hit XCL_GPU_VIEW_MB and permanently refuse later buffer views (or leak VRAM on 16 GiB AMD RDNA4 GPUs). Track per-tile submit recency and backing state in Mirrors: 1. Reclaim tiles in sync() once their GPU-view reservation is released, explicitly unmapped via CopyPageMappingsBatchX, or a previously committed backing tile is completely decommitted (checked via VirtualQuery + lazy::is_lazy + physical_page_at), decommitting contiguous window runs via State::decommit_range. 2. Under XCL_GPU_VIEW_MB budget pressure in base_for(), evict the oldest cold tiles outside a 16-submit in-flight grace window (never evicting active or requested tiles) so new GPU-view buffers stay mapped instead of reading zeros. Adds unit tests for mirror index cleanup and LRU grace/protection rules. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 249 ++++++++++++++++++- crates/xcl/src/hle/kernelx/lazy.rs | 5 + 2 files changed, 246 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs index 2ce62ec0ae..fcef239dee 100644 --- a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -11,7 +11,7 @@ //! replaced by the window's. Only what is read is mirrored: a write through it is lost, so UAVs //! keep their address. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use super::*; @@ -20,6 +20,13 @@ use super::*; const EXTENT: usize = 1 << 20; /// Views longer than this keep their address. const MOST: usize = 64 << 20; +/// Minimum submit age before budget-pressure LRU eviction can reclaim a still-backed tile, +/// ensuring tiles referenced in the current frame or in-flight submissions are never evicted. +const EVICT_GRACE_SUBMITS: u64 = 16; +/// Rotating title tiles inspected per submit for unmapped/decommitted reclamation. +const SWEEP_PER_SUBMIT: usize = 64; +/// Extra cold tiles reclaimed alongside a budget eviction to amortize tile-mapping updates. +const EVICT_BATCH_EXTRA: usize = 32; pub fn on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -44,6 +51,12 @@ pub(super) struct Mirrors { by_read: FxHashMap>, /// window tiles none of whose bytes have gone up yet (or whose pages changed place) fresh: Vec, + /// window tile → submit epoch when last referenced (`base_for`, `show`, or dirty upload) + last_used: FxHashMap, + /// title tiles whose backing read page has been observed committed at least once + backed: HashSet, + /// monotonically incremented once per `sync()` submission + epoch: u64, /// the next title tile the slow check looks at turn: usize, /// GPU-view mappings seen (`kernelx::gpu_view_map_gen`) @@ -59,6 +72,13 @@ impl Mirrors { self.read.insert(title, read); self.by_read.entry(read).or_default().push(win); self.fresh.push(win); + self.last_used.insert(win, self.epoch); + } + + fn touch(&mut self, win: usize) { + if self.title_of.contains_key(&win) { + self.last_used.insert(win, self.epoch); + } } fn set_read(&mut self, title: usize, read: usize) { @@ -67,13 +87,88 @@ impl Mirrors { return; } let wins: Vec = self.title_of.iter().filter(|&(_, &t)| t == title).map(|(&w, _)| w).collect(); - if let Some(o) = old.and_then(|o| self.by_read.get_mut(&o)) { - o.retain(|w| !wins.contains(w)); + if let Some(o) = old { + if let Some(v) = self.by_read.get_mut(&o) { + v.retain(|w| !wins.contains(w)); + if v.is_empty() { + self.by_read.remove(&o); + } + } } self.by_read.entry(read).or_default().extend(&wins); self.fresh.extend(wins); } + /// Remove `wins` from all mirror tables and prune orphaned `by_read`, `read`, `backed`, and + /// `fresh` entries. Returns the number of mapped window tiles removed. + fn evict_windows(&mut self, wins: &[usize]) -> usize { + if wins.is_empty() { + return 0; + } + let mut evicted = 0usize; + let mut affected_titles: HashSet = HashSet::new(); + let mut touched_reads: HashSet = HashSet::new(); + for &w in wins { + let Some(title) = self.title_of.remove(&w) else { continue }; + self.last_used.remove(&w); + affected_titles.insert(title); + if let Some(&r) = self.read.get(&title) { + touched_reads.insert(r); + } + evicted += 1; + } + if evicted == 0 { + return 0; + } + for r in touched_reads { + if let Some(v) = self.by_read.get_mut(&r) { + v.retain(|w| self.title_of.contains_key(w)); + if v.is_empty() { + self.by_read.remove(&r); + } + } + } + self.fresh.retain(|w| self.title_of.contains_key(w)); + for &t in self.title_of.values() { + affected_titles.remove(&t); + } + for title in affected_titles { + self.read.remove(&title); + self.backed.remove(&title); + } + evicted + } + + /// Evict every window tile showing `title` if none were touched in the current submit epoch. + fn evict_title_if_idle(&mut self, title: usize) -> Vec { + let wins: Vec = self.title_of.iter().filter(|&(_, &t)| t == title).map(|(&w, _)| w).collect(); + if wins.is_empty() || wins.iter().any(|w| self.last_used.get(w).copied().unwrap_or(0) >= self.epoch) { + return Vec::new(); + } + self.evict_windows(&wins); + wins + } + + /// Select up to `want` least-recently-used window tiles at least `min_age` submits old and + /// outside `protect`, ordered oldest-first. + fn lru_eviction_candidates(&self, want: usize, min_age: u64, protect: &HashSet) -> Vec { + if want == 0 { + return Vec::new(); + } + let mut cold: Vec<(u64, usize)> = self + .title_of + .keys() + .filter(|w| !protect.contains(w)) + .filter_map(|&w| { + let last = self.last_used.get(&w).copied().unwrap_or(0); + (self.epoch.saturating_sub(last) >= min_age).then_some((last, w)) + }) + .collect(); + cold.sort_unstable(); + cold.truncate(want); + cold.into_iter().map(|(_, w)| w).collect() + } + /// The window tiles and pages a set of written pages (`dirty`, title or CPU addresses) is /// shown at: (window page, the read address of its bytes). pub(super) fn shown_at(&self, dirty: &[usize]) -> Vec<(usize, usize)> { @@ -92,6 +187,49 @@ impl Mirrors { } } +/// Decommit evicted mirror window tiles in coalesced contiguous runs so `sparse::State` parks, +/// unmaps, and returns their 64 KiB VRAM tiles (and empty 64 MiB pools) safely. +unsafe fn decommit_window_tiles(s: &mut State, wins: &mut [usize]) { + if wins.is_empty() { + return; + } + wins.sort_unstable(); + let mut i = 0; + while i < wins.len() { + let start = wins[i]; + let mut end = start + TILE; + i += 1; + while i < wins.len() && (wins[i] == end || wins[i] == end - TILE) { + if wins[i] == end { + end += TILE; + } + i += 1; + } + s.decommit_range(start, end - start); + } +} + +/// Whether `title` (a 64 KiB tile in a GPU view) has lost its backing: either the GPU-view +/// reservation was released, the page was explicitly unmapped via `CopyPageMappingsBatchX`, or +/// a previously committed backing tile has been completely decommitted. Returns `(dead, read)`. +unsafe fn check_title_tile(title: usize, was_backed: bool) -> (bool, usize) { + if crate::hle::kernelx::mirrors::source(title).is_none() { + return (true, title); + } + if crate::hle::kernelx::mirrors::mapped_source(title) == Some(None) { + return (true, title); + } + let read = super::super::title_textures::mirror_source(title) & !(TILE - 1); + if was_backed + && query_tile_holes(read) == 0xFFFF + && !crate::hle::kernelx::lazy::is_lazy(read) + && !crate::hle::kernelx::physical_page_at(read) + { + return (true, read); + } + (false, read) +} + /// Copies `n` bytes from the title's memory at `at`; false when the page went away (nothing read). unsafe fn read_title(at: usize, out: *mut u8, n: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; @@ -104,6 +242,10 @@ impl State { /// the pages the title wrote (`dirty`). Before the title's lists; `m` is held by the caller. pub(super) unsafe fn mirror_up(&mut self, m: &mut Mirrors, dirty: &[usize]) -> usize { let mut pages: Vec<(usize, usize)> = m.shown_at(dirty); + let dirty_count = pages.len(); + for &(win, _) in &pages[..dirty_count] { + m.touch(win & !(TILE - 1)); + } for win in std::mem::take(&mut m.fresh) { let Some(&title) = m.title_of.get(&win) else { continue }; let read = m.read[&title]; @@ -120,6 +262,9 @@ impl State { if !read_title(read, bytes.as_mut_ptr(), PAGE) { continue; } + if let Some(&title) = m.title_of.get(&tile) { + m.backed.insert(title); + } let i = (win - tile) / PAGE; entry.holes &= !(1u16 << i); scan_page(&bytes, win, &mut entry.sent[i], &mut runs); @@ -182,8 +327,29 @@ pub fn base_for(va: usize, len: usize) -> Option { let mut mg = MIRRORS.lock().unwrap(); let m = mg.get_or_insert_with(Mirrors::default); let new: Vec = (t0..t1).step_by(TILE).filter(|t| !m.title_of.contains_key(&(win + (t - first)))).collect(); + for t in (t0..t1).step_by(TILE) { + m.touch(win + (t - first)); + } if !new.is_empty() { - if m.tiles() + new.len() > budget() / TILE { + let limit = budget() / TILE; + if m.tiles() + new.len() > limit { + let need = (m.tiles() + new.len()).saturating_sub(limit); + let protect: HashSet = (t0..t1).step_by(TILE).map(|t| win + (t - first)).collect(); + let want = need.saturating_add(EVICT_BATCH_EXTRA); + let mut victims = m.lru_eviction_candidates(want, EVICT_GRACE_SUBMITS, &protect); + if victims.len() >= need { + let n = m.evict_windows(&victims); + // SAFETY: evicted mirror tiles live in sparse window VA with no CPU backing. + unsafe { decommit_window_tiles(s, &mut victims) }; + static EVICTED: AtomicU64 = AtomicU64::new(0); + let prev = EVICTED.fetch_add(n as u64, Ordering::Relaxed); + let total = prev + n as u64; + if prev == 0 || (total >> 10) > (prev >> 10) { + crate::xlog_info!("D3D12.X: GPU view mirrors evicted {n} cold tiles ({} MB total reclaimed, {} tiles live)", (total as usize * TILE) >> 20, m.tiles()); + } + } + } + if m.tiles() + new.len() > limit { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| crate::xlog_warn!("D3D12.X: the buffers of the GPU view take more than XCL_GPU_VIEW_MB: the rest keeps its address")); drop(mg); @@ -204,7 +370,11 @@ pub fn base_for(va: usize, len: usize) -> Option { for &t in &new[i..j] { let w = win + (t - first); if s.mapped.contains_key(&w) { - m.show(w, t, super::super::title_textures::mirror_source(t) & !(TILE - 1)); + let src = super::super::title_textures::mirror_source(t) & !(TILE - 1); + m.show(w, t, src); + if unsafe { query_tile_holes(src) } != 0xFFFF { + m.backed.insert(t); + } } } i = j; @@ -248,19 +418,39 @@ pub fn sources() -> Vec<(usize, usize)> { pub(super) unsafe fn sync(s: &mut State, dirty: &[usize]) { let mut g = MIRRORS.lock().unwrap(); let Some(m) = g.as_mut().filter(|m| m.tiles() != 0) else { return }; + m.epoch = m.epoch.wrapping_add(1); let gen = crate::hle::kernelx::gpu_view_map_gen(); let titles: Vec = m.read.keys().copied().collect(); let look: Vec = if std::mem::replace(&mut m.gen, gen) != gen { titles } else { let n = titles.len().max(1); - (0..8.min(titles.len())).map(|i| titles[(m.turn + i) % n]).collect() + (0..SWEEP_PER_SUBMIT.min(titles.len())).map(|i| titles[(m.turn + i) % n]).collect() }; - m.turn = m.turn.wrapping_add(8); + m.turn = m.turn.wrapping_add(SWEEP_PER_SUBMIT); + let mut dead_wins: Vec = Vec::new(); for t in look { - let r = super::super::title_textures::mirror_source(t) & !(TILE - 1); + let was_backed = m.backed.contains(&t); + let (dead, r) = check_title_tile(t, was_backed); + if dead { + dead_wins.extend(m.evict_title_if_idle(t)); + continue; + } + if !was_backed && query_tile_holes(r) != 0xFFFF { + m.backed.insert(t); + } m.set_read(t, r); } + if !dead_wins.is_empty() { + let evicted = dead_wins.len(); + decommit_window_tiles(s, &mut dead_wins); + static UNMAPPED_EVICTED: AtomicU64 = AtomicU64::new(0); + let prev = UNMAPPED_EVICTED.fetch_add(evicted as u64, Ordering::Relaxed); + let total = prev + evicted as u64; + if prev == 0 || (total >> 10) > (prev >> 10) { + crate::xlog_info!("D3D12.X: GPU view mirrors reclaimed {evicted} unmapped tiles ({} MB total, {} tiles live)", (total as usize * TILE) >> 20, m.tiles()); + } + } let n = s.mirror_up(m, dirty); static SENT: AtomicU64 = AtomicU64::new(0); static CALLS: AtomicU64 = AtomicU64::new(0); @@ -297,6 +487,49 @@ mod tests { assert_eq!(m.fresh, vec![0x30_0000], "the same place again is nothing new"); } + #[test] + fn evict_windows_cleans_all_indices_and_orphaned_sources() { + let mut m = Mirrors::default(); + m.show(0x10_0000, 0xAA_0000, 0xCC_0000); + m.show(0x20_0000, 0xAA_0000, 0xCC_0000); + m.show(0x30_0000, 0xBB_0000, 0xDD_0000); + m.backed.insert(0xAA_0000); + m.backed.insert(0xBB_0000); + // Evicting one of two window aliases keeps the shared title/read entry alive. + assert_eq!(m.evict_windows(&[0x10_0000]), 1); + assert_eq!(m.tiles(), 2); + assert!(m.read.contains_key(&0xAA_0000)); + assert_eq!(m.shown_at(&[0xCC_1000]), vec![(0x20_1000, 0xCC_1000)]); + assert!(!m.fresh.contains(&0x10_0000)); + // Evicting the last alias removes title, backed, and empty by_read source entries. + assert_eq!(m.evict_windows(&[0x20_0000]), 1); + assert_eq!(m.tiles(), 1); + assert!(!m.read.contains_key(&0xAA_0000)); + assert!(!m.backed.contains(&0xAA_0000)); + assert!(!m.by_read.contains_key(&0xCC_0000)); + assert_eq!(m.shown_at(&[0xDD_2000]), vec![(0x30_2000, 0xDD_2000)]); + } + + #[test] + fn lru_eviction_respects_grace_window_and_protected_tiles() { + let mut m = Mirrors::default(); + m.epoch = 1; + m.show(0x10_0000, 0xA0_0000, 0xA0_0000); + m.epoch = 5; + m.show(0x20_0000, 0xB0_0000, 0xB0_0000); + m.epoch = 20; + m.show(0x30_0000, 0xC0_0000, 0xC0_0000); + m.epoch = 25; + // At epoch 25 with grace 16: 0x10 (age 24) and 0x20 (age 20) are cold; 0x30 (age 5) is hot. + let protect: HashSet = [0x10_0000].into_iter().collect(); + assert_eq!(m.lru_eviction_candidates(4, EVICT_GRACE_SUBMITS, &protect), vec![0x20_0000]); + assert_eq!(m.lru_eviction_candidates(4, EVICT_GRACE_SUBMITS, &HashSet::new()), vec![0x10_0000, 0x20_0000]); + // Touching 0x10 makes it hot in the current epoch, so evict_title_if_idle skips it too. + m.touch(0x10_0000); + assert!(m.evict_title_if_idle(0xA0_0000).is_empty()); + assert_eq!(m.evict_title_if_idle(0xB0_0000), vec![0x20_0000]); + } + /// The bytes of the title's pages reach the window tiles mapped for them, and again when the /// title writes a page; a page that went away is left as it is. #[test] diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index fc0f11de8d..bb4d07d093 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -84,6 +84,11 @@ pub(crate) fn mark(page: usize) { LAZY.write().unwrap_or_else(|e| e.into_inner()).insert(page); } +/// Whether `page` (64 KiB aligned) is mapped but not committed yet. +pub fn is_lazy(page: usize) -> bool { + LAZY.read().unwrap_or_else(|e| e.into_inner()).contains(&page) +} + /// `page` is unmapped: true if it was never used (nothing to keep of it). pub(super) fn unmark(page: usize) -> bool { LAZY.write().unwrap_or_else(|e| e.into_inner()).remove(&page) From 3058ce8712a17ec8b37d5217bb9af60b739e13f4 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:54:05 +0100 Subject: [PATCH 066/258] D3D12.X: skip mapping uncommitted graphics-reservation texture pages Port #1514 onto the batched TilePool/signal vram path and enforce the 96 MiB coherent UMA headroom guard in alloc_physical_home: 1. Non-lazy placed textures whose owned 64 KiB pages lie inside a title graphics reservation leave uncommitted/unmapped pages unmapped (tier-2 reserved textures read zero) instead of allocating VRAM pool tiles up front, using a region-cached VirtualQuery run and reservation overlap fast path. 2. When VirtualAlloc, VirtualFree, or MapTitlePhysicalPages/Scatter commits, maps, decommits, or releases memory in a graphics reservation (or a CPU view mirrored by GPU views), apply_backing() maps or unmaps the followed texture tiles before the next submit and shares before_execute()'s batched fence signal. 3. Share COHERENT_KEEP (96 MiB) with kernelx::alloc_physical_home so non-sparse coherent fallbacks cannot starve XCL's reserved coherent headroom. Adds unit test coverage for selective tile-range updates. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/vram.rs | 407 ++++++++++++++++++++++++++---- crates/xcl/src/hle/kernelx.rs | 113 +++++++-- 2 files changed, 455 insertions(+), 65 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index b0f9d13b70..2a3a0264d0 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -232,10 +232,89 @@ struct Target { mapped: bool, used: Vec, used_extra: Vec<(usize, usize)>, + /// its owned pages in graphics reservations (`Pages::follow`) + follows: Vec, /// its levels get their pages one by one (`map_levels`); None: all of it has pages levels: Option, } +/// An owned page of placed textures in a graphics reservation: mapped only while the title +/// has memory there (committed, a physical page, or one mapped but not yet touched). +struct Follow { + /// (texture, its tile at this page) + users: Vec<(usize, u32)>, + /// whether the textures' tiles there are on a page of video memory + mapped: bool, +} + +/// Ranges of title memory a graphics reservation gained or lost memory in since the last +/// submit (`title_memory_changed`): the pages there are mapped or unmapped before the next one. +static BACKING: Mutex> = Mutex::new(Vec::new()); + +/// The title committed, mapped, decommitted or unmapped `[a, a + n)` of a graphics reservation: +/// the texture pages there follow it before the title's next submit (`before_execute`). +pub fn title_memory_changed(a: usize, n: usize) { + if n > 0 { + // a CPU view's change is its GPU views' too + let gpus = crate::hle::kernelx::mirrors::gpu_views_of(a); + let mut b = BACKING.lock().unwrap(); + b.push((a, n)); + for g in gpus { + b.push((g, n)); + } + } +} + +/// Cached `VirtualQuery` region run so checking contiguous uncommitted pages in a reservation +/// issues one syscall per region instead of one per 64 KiB page. +#[derive(Default)] +struct BackedRun { + start: usize, + end: usize, + committed: bool, +} + +/// Whether the title has memory at the 64 KiB page `a`: committed, a physical page mapped there, +/// or one mapped and not touched yet (`lazy`). In a GPU view of the title's CPU memory +/// (`kernelx::mirrors`) that is the memory of the mapped source or CPU view behind it. +fn title_backed_in(a: usize, run: &mut BackedRun) -> bool { + let a = match crate::hle::kernelx::mirrors::mapped_source(a) { + Some(Some(s)) => s, + Some(None) => return false, + None => crate::hle::kernelx::mirrors::source(a).unwrap_or(a), + }; + let committed = if (run.start..run.end).contains(&a) { + run.committed + } else { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + if unsafe { VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) } != 0 && m.RegionSize > 0 { + let start = m.BaseAddress as usize; + *run = BackedRun { start, end: start.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT }; + run.committed + } else { + false + } + }; + committed || crate::hle::kernelx::lazy::is_lazy(a) || crate::hle::kernelx::physical_page_at(a) +} + +/// The ranges of one UpdateTileMappings call over all `total` tiles of a resource: `sel(i)` is +/// the heap offset of tile i when this call sets it (Some), else it is skipped. `flag` for the +/// set runs (NONE: onto a heap; NULL: unmapped). +fn update_ranges(total: u32, flag: D3D12_TILE_RANGE_FLAGS, sel: impl Fn(u32) -> Option) -> Vec<(D3D12_TILE_RANGE_FLAGS, u32, u32)> { + let mut out: Vec<(D3D12_TILE_RANGE_FLAGS, u32, u32)> = Vec::new(); + for i in 0..total { + match (sel(i), out.last_mut()) { + (Some(o), Some(r)) if r.0 == flag && (flag == D3D12_TILE_RANGE_FLAG_NULL || r.1 + r.2 == o) => r.2 += 1, + (Some(o), _) => out.push((flag, if flag == D3D12_TILE_RANGE_FLAG_NULL { 0 } else { o }, 1)), + (None, Some(r)) if r.0 == D3D12_TILE_RANGE_FLAG_SKIP => r.2 += 1, + (None, _) => out.push((D3D12_TILE_RANGE_FLAG_SKIP, 0, 1)), + } + } + out +} + /// The tiles of a texture whose levels get video memory when an upload first has texels for /// them (`level_pages`): a group for each level with tiles of its own, in order, then one for /// the packed levels. @@ -603,9 +682,12 @@ struct Pages { targets: std::collections::HashMap, /// queue → the fence value it last waited for waited: std::collections::HashMap, + /// owned pages of textures in graphics reservations → their textures (`Follow`) + follow: std::collections::HashMap, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, /// reusable scratch buffers for `map()` + scratch_tiles: Vec, scratch_heaps: Vec, scratch_flags: Vec, scratch_offsets: Vec, @@ -644,7 +726,9 @@ impl Pages { idle: std::collections::VecDeque::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + follow: std::collections::HashMap::new(), reservable_cache: std::collections::HashMap::new(), + scratch_tiles: Vec::new(), scratch_heaps: Vec::new(), scratch_flags: Vec::new(), scratch_offsets: Vec::new(), @@ -681,19 +765,25 @@ impl Pages { dropped } - /// Map every tile of `res` (`tiles[i]`: overall tile i) – one call per pool heap. - /// `tiles` for the tiles of `res` from the first one of subresource `sub` on. - unsafe fn map(&mut self, res: &ID3D12Resource, sub: u32, tiles: &[Tile]) { + /// Map every tile of `res` (`tiles[i]`: overall tile i; `None` stays unmapped) – one call + /// per pool heap. `tiles` for the tiles of `res` from the first one of subresource `sub` on. + unsafe fn map(&mut self, res: &ID3D12Resource, sub: u32, tiles: &[Option]) { if tiles.is_empty() { return; } + // a tile left out (None) stays unmapped: a sentinel heap no pool has + self.scratch_tiles.clear(); + self.scratch_tiles.extend(tiles.iter().map(|t| t.unwrap_or((u32::MAX, 0)))); self.scratch_heaps.clear(); - self.scratch_heaps.extend(tiles.iter().map(|t| t.0)); + self.scratch_heaps.extend(self.scratch_tiles.iter().map(|t| t.0).filter(|&h| h != u32::MAX)); + if self.scratch_heaps.is_empty() { + return; + } self.scratch_heaps.sort_unstable(); self.scratch_heaps.dedup(); for i in 0..self.scratch_heaps.len() { let h = self.scratch_heaps[i]; - let ranges = heap_ranges_trimmed(h, tiles); + let ranges = heap_ranges_trimmed(h, &self.scratch_tiles); if ranges.is_empty() { continue; } @@ -794,31 +884,79 @@ impl Pages { } /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. - unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>)> { - self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize) + /// A page in a graphics reservation the title has no memory at yet is left unmapped (tier 2: + /// reads zero) and mapped when the title puts memory there (`apply_backing`); the texture's + /// followed pages are returned third. + unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, key: usize, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { + self.bind_range(dev, res, Some(key), va, console_bytes, total, 0, 0..total as usize) } /// `bind` for the tiles `range` of the resource's `total`, which start at subresource `sub`. #[allow(clippy::too_many_arguments)] - unsafe fn bind_range(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option, total: u32, sub: u32, range: std::ops::Range) -> Option<(Vec, Vec<(usize, usize)>)> { + unsafe fn bind_range( + &mut self, + dev: &ID3D12Device, + res: &ID3D12Resource, + follow_key: Option, + va: usize, + console_bytes: Option, + total: u32, + sub: u32, + range: std::ops::Range, + ) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); let timer = step(Step::Sweep); self.sweep(now); drop(timer); + enum TilePlan { + FollowSkip(usize), + Own { addr: usize, follow: bool }, + Extra(usize, usize), + } + + let check_res = follow_key.is_some() + && own > 0 + && crate::hle::kernelx::overlaps_graphics_reservation(first, own.saturating_mul(PAGE)); + let mut res_bounds: Option<(usize, usize)> = None; + let mut backed_run = BackedRun::default(); + + let mut plan = Vec::with_capacity(range.len()); let mut missing = 0usize; let mut preferred: Option = None; for i in range.clone() { - let existing = if i < own { - self.pages.get(&(first + i * PAGE)).map(|p| p.tile.0) + if i < own { + let a = first + i * PAGE; + let in_res = if check_res { + if res_bounds.is_none_or(|(lo, hi)| a < lo || a >= hi) { + res_bounds = crate::hle::kernelx::graphics_reservation_bounds(a); + } + res_bounds.is_some_and(|(lo, hi)| a >= lo && a < hi) + } else { + false + }; + if in_res { + let shared = self.pages.get(&a).is_some_and(|p| p.users > 0); + let already_mapped = self.follow.get(&a).is_some_and(|f| f.mapped); + if !(already_mapped || shared || title_backed_in(a, &mut backed_run)) { + plan.push(TilePlan::FollowSkip(a)); + continue; + } + } + match self.pages.get(&a).map(|p| p.tile.0) { + Some(h) if preferred.is_none() => preferred = Some(h), + Some(_) => {} + None => missing += 1, + } + plan.push(TilePlan::Own { addr: a, follow: in_res }); } else { - self.extra_pages.get(&(va, i)).map(|p| p.tile.0) - }; - match existing { - Some(h) if preferred.is_none() => preferred = Some(h), - Some(_) => {} - None => missing += 1, + match self.extra_pages.get(&(va, i)).map(|p| p.tile.0) { + Some(h) if preferred.is_none() => preferred = Some(h), + Some(_) => {} + None => missing += 1, + } + plan.push(TilePlan::Extra(va, i)); } } @@ -834,44 +972,194 @@ impl Pages { let mut tiles = Vec::with_capacity(range.len()); let mut used = Vec::with_capacity(own.min(range.len())); let mut used_extra = Vec::new(); - for i in range { - let tile = if i < own { - let a = first + i * PAGE; - let t = match self.pages.get_mut(&a) { - Some(p) => { - p.users += 1; - p.idle_since = None; - p.tile + let mut follows = Vec::new(); + for (i, slot) in range.zip(plan) { + match slot { + TilePlan::FollowSkip(a) => { + follows.push(a); + if let Some(key) = follow_key { + self.follow.entry(a).or_insert(Follow { users: Vec::new(), mapped: false }).users.push((key, i as u32)); } - None => { - let t = fresh_iter.next().unwrap(); - self.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); - t + tiles.push(None); + } + TilePlan::Own { addr: a, follow } => { + if follow { + follows.push(a); + if let Some(key) = follow_key { + let f = self.follow.entry(a).or_insert(Follow { users: Vec::new(), mapped: false }); + f.users.push((key, i as u32)); + f.mapped = true; + } } - }; - used.push(a); - t - } else { - let k = (va, i); - let t = match self.extra_pages.get_mut(&k) { + let t = match self.pages.get_mut(&a) { + Some(p) => { + p.users += 1; + p.idle_since = None; + p.tile + } + None => { + let t = fresh_iter.next().unwrap(); + self.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); + t + } + }; + used.push(a); + tiles.push(Some(t)); + } + TilePlan::Extra(va, idx) => { + let k = (va, idx); + let t = match self.extra_pages.get_mut(&k) { + Some(p) => { + p.users += 1; + p.idle_since = None; + p.tile + } + None => { + let t = fresh_iter.next().unwrap(); + self.extra_pages.insert(k, Page { tile: t, users: 1, idle_since: None }); + t + } + }; + used_extra.push(k); + tiles.push(Some(t)); + } + } + } + self.map(res, sub, &tiles); + Some((used, used_extra, follows)) + } + + /// Texture `key` no longer at its followed pages `addrs`. + fn unfollow(&mut self, key: usize, addrs: &[usize]) { + for a in addrs { + if let Some(f) = self.follow.get_mut(a) { + f.users.retain(|u| u.0 != key); + if f.users.is_empty() { + self.follow.remove(a); + } + } + } + } + + /// The followed pages in `ranges` mapped where the title has memory now and unmapped where + /// it has none (their video memory idle, reused if the title maps there again within + /// `IDLE`): one UpdateTileMappings per texture and heap; caller flushes the batched signal. + unsafe fn apply_backing(&mut self, dev: &ID3D12Device, ranges: &[(usize, usize)]) { + let mut addrs: Vec = Vec::new(); + for &(a, n) in ranges { + let mut p = a & !(PAGE - 1); + let end = a.saturating_add(n); + while p < end { + if self.follow.contains_key(&p) { + addrs.push(p); + } + match p.checked_add(PAGE) { + Some(next) => p = next, + None => break, + } + } + } + if addrs.is_empty() { + return; + } + addrs.sort_unstable(); + addrs.dedup(); + let now = std::time::Instant::now(); + let mut backed_run = BackedRun::default(); + // texture → (tile, its new page or None: unmapped) + let mut changes: std::collections::HashMap)>> = std::collections::HashMap::new(); + for a in addrs { + let Some(mapped) = self.follow.get(&a).map(|f| f.mapped) else { continue }; + let backed = title_backed_in(a, &mut backed_run); + if backed == mapped { + continue; + } + let users = self.follow[&a].users.clone(); + if backed { + if !users.iter().any(|&(k, _)| self.targets.get(&k).is_some_and(|t| t.mapped)) { + continue; + } + let tile = match self.pages.get_mut(&a) { Some(p) => { - p.users += 1; p.idle_since = None; p.tile } None => { - let t = fresh_iter.next().unwrap(); - self.extra_pages.insert(k, Page { tile: t, users: 1, idle_since: None }); + let pools = &mut self.pools; + let pool = &mut self.pool; + let Some(mut fresh) = pool.take_batch(1, None, now, POOL_PAGES, || { + let _timer = step(Step::Heap); + let heap = alloc_pool_heap(dev)?; + Some(pools.push_heap(heap)) + }) else { + continue; + }; + let t = fresh.pop().unwrap(); + self.pages.insert(a, Page { tile: t, users: 0, idle_since: None }); t } }; - used_extra.push(k); - t - }; - tiles.push(tile); + for &(k, i) in &users { + if let Some(t) = self.targets.get_mut(&k).filter(|t| t.mapped) { + t.used.push(a); + self.pages.get_mut(&a).unwrap().users += 1; + changes.entry(k).or_default().push((i, Some(tile))); + } + } + } else { + for &(k, i) in &users { + if let Some(t) = self.targets.get_mut(&k).filter(|t| t.mapped) { + if let Some(at) = t.used.iter().position(|&u| u == a) { + t.used.swap_remove(at); + self.release_tiles(vec![a], Vec::new(), now, false); + } + changes.entry(k).or_default().push((i, None)); + } + } + } + if let Some(f) = self.follow.get_mut(&a) { + f.mapped = backed; + } } - self.map(res, sub, &tiles); - Some((used, used_extra)) + if changes.is_empty() { + return; + } + for (k, tiles) in changes { + let Some(total) = self.targets.get(&k).map(|t| t.total) else { continue }; + let raw = k as *mut c_void; + let Some(res) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; + let at: std::collections::HashMap> = tiles.into_iter().collect(); + let mut heaps: Vec = at.values().flatten().map(|t| t.0).collect(); + heaps.sort_unstable(); + heaps.dedup(); + let mut calls: Vec<(Option, Vec<(D3D12_TILE_RANGE_FLAGS, u32, u32)>)> = heaps + .into_iter() + .map(|h| (Some(h), update_ranges(total, D3D12_TILE_RANGE_FLAG_NONE, |i| at.get(&i).copied().flatten().filter(|t| t.0 == h).map(|t| t.1)))) + .collect(); + if at.values().any(|t| t.is_none()) { + calls.push((None, update_ranges(total, D3D12_TILE_RANGE_FLAG_NULL, |i| at.get(&i).filter(|t| t.is_none()).map(|_| 0)))); + } + for (h, ranges) in calls { + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; + let flags: Vec = ranges.iter().map(|r| r.0).collect(); + let offsets: Vec = ranges.iter().map(|r| r.1).collect(); + let counts: Vec = ranges.iter().map(|r| r.2).collect(); + self.queue.UpdateTileMappings( + res, + 1, + Some(&coord), + Some(®ion), + h.map(|h| &self.pools[h as usize]), + ranges.len() as u32, + Some(flags.as_ptr()), + Some(offsets.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + } + self.dirty_signal = true; } } @@ -1036,10 +1324,10 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), follows: Vec::new(), levels }); true - } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None }); + } else if let Some((used, used_extra, follows)) = pages.bind(dev, res, raw as usize, va, console_bytes, total) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, follows, levels: None }); true } else { false @@ -1071,6 +1359,7 @@ pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { let total = t.total; let used = std::mem::take(&mut t.used); let used_extra = std::mem::take(&mut t.used_extra); + let follows = std::mem::take(&mut t.follows); t.mapped = false; if let Some(l) = t.levels.as_mut() { LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); @@ -1078,6 +1367,7 @@ pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { } pages.unmap(res, total); pages.release_tiles(used, used_extra, now, true); + pages.unfollow(key, &follows); return; } } @@ -1103,12 +1393,13 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.mapped = true; return true; } - let Some((used, used_extra)) = pages.bind(&dev, res, va, console_bytes, total) else { + let Some((used, used_extra, follows)) = pages.bind(&dev, res, key, va, console_bytes, total) else { return false; }; if let Some(t) = pages.targets.get_mut(&key) { t.used = used; t.used_extra = used_extra; + t.follows = follows; t.mapped = true; } true @@ -1128,6 +1419,7 @@ fn forget_pages(resource: usize) { if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); } + pages.unfollow(resource, &t.follows); return; } } @@ -1232,6 +1524,10 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { + let changed = std::mem::take(&mut *BACKING.lock().unwrap()); + if !changed.is_empty() && !pages.follow.is_empty() { + pages.apply_backing(&dev, &changed); + } pages.flush_signal(); let key = queue.as_raw() as usize; if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { @@ -1335,7 +1631,7 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return Vec::new() }; let mut fresh = Vec::new(); for (k, sub, first, n, levels) in todo { - let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize) else { continue }; + let Some((used, used_extra, _)) = pages.bind_range(dev, res, None, va, console_bytes, total, sub, first as usize..(first + n) as usize) else { continue }; let Some(t) = pages.targets.get_mut(&key) else { return fresh }; t.used.extend(used); t.used_extra.extend(used_extra); @@ -1759,6 +2055,21 @@ mod tests { } } + /// A followed page's tiles change alone: the rest of the resource is skipped, consecutive + /// heap tiles merge into one range, unmapped ones into a NULL range. + #[test] + fn update_ranges_set_only_the_changed_tiles() { + let (none, null, skip) = (D3D12_TILE_RANGE_FLAG_NONE, D3D12_TILE_RANGE_FLAG_NULL, D3D12_TILE_RANGE_FLAG_SKIP); + let map = |i: u32| match i { + 2 => Some(7), + 3 => Some(8), + 5 => Some(1), + _ => None, + }; + assert_eq!(update_ranges(7, none, map), [(skip, 0, 2), (none, 7, 2), (skip, 0, 1), (none, 1, 1), (skip, 0, 1)]); + assert_eq!(update_ranges(5, null, |i| [0, 1, 4].contains(&i).then_some(0)), [(null, 0, 2), (skip, 0, 2), (null, 0, 1)]); + } + /// Idle pages go back after `IDLE`, and a sweep looks at the queue of idle pages alone: one /// used again stays, one idle again later goes when that is `IDLE` ago, and the sweeps of /// 20 000 placements beside 200 000 pages in use take no time to speak of (a look at every diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 1711afb104..8496a4b175 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -159,9 +159,49 @@ pub fn graphics_reservations() -> Vec<(usize, usize)> { /// Whether `p` lies in one of the title's graphics reservations. pub fn in_graphics_reservation(p: usize) -> bool { - GRAPHICS_RESERVATIONS.lock().unwrap().range(..=p).next_back().is_some_and(|(&b, &s)| p < b + s) + graphics_reservation_bounds(p).is_some() +} + +/// The `[start, end)` bounds of the graphics reservation containing `p`, if any. +pub fn graphics_reservation_bounds(p: usize) -> Option<(usize, usize)> { + GRAPHICS_RESERVATIONS + .lock() + .unwrap() + .range(..=p) + .next_back() + .and_then(|(&b, &s)| { + let end = b.saturating_add(s); + (p < end).then_some((b, end)) + }) +} + +/// Whether `[start, start + len)` overlaps any graphics reservation. +pub fn overlaps_graphics_reservation(start: usize, len: usize) -> bool { + if len == 0 { + return false; + } + let end = start.saturating_add(len); + let g = GRAPHICS_RESERVATIONS.lock().unwrap(); + if let Some((&b, &s)) = g.range(..=start).next_back() { + if start < b.saturating_add(s) { + return true; + } + } + g.range(start..end).next().is_some() } +/// Notify `d3d12x::vram` when a range in a graphics reservation (or a CPU view with GPU views) +/// gains or loses title memory so placed textures there follow it before the next submit. +fn notify_vram_backing(a: usize, n: usize) { + if n > 0 && (overlaps_graphics_reservation(a, n) || !mirrors::gpu_views_of(a).is_empty()) { + crate::hle::d3d12x::vram::title_memory_changed(a, n); + } +} + +/// Coherent UMA headroom kept for XCL itself (readback heaps; per-draw arguments have their own +/// pool) so title graphics heaps or non-sparse physical-page fallbacks never starve XCL. +const COHERENT_KEEP: usize = 96 << 20; + const MEM_WRITE_WATCH: u32 = 0x20_0000; /// GPU views of the title's CPU memory. A retail game reserves 24 GB of 64 KiB pages twice @@ -495,8 +535,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: let align = if t & 0x2000_0000 != 0 && t & 0x0040_0000 == 0 { 2 << 20 } else { crate::gpu::uma::GRAIN }; // what XCL keeps of the window for itself (readback heaps; its per-draw arguments have // a pool of their own) - const KEEP: usize = 96 << 20; - let fits = u.size().saturating_sub(u.used()) >= size + KEEP; + let fits = u.size().saturating_sub(u.used()) >= size + COHERENT_KEEP; if let Some(q) = fits.then(|| u.alloc(size, align)).flatten() { trace_mem("VirtualAlloc (graphics, coherent window)", 0, size, t as u64, p, q as usize); return q as *mut c_void; @@ -519,6 +558,9 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: } let q = mem::VirtualAlloc(addr, size, sanitize_alloc_type(t), sanitize_protect(p)); trace_mem("VirtualAlloc", addr as usize, size, t as u64, p, q as usize); + if !q.is_null() && t & mem::MEM_COMMIT != 0 { + notify_vram_backing(q as usize, size); + } q } @@ -636,7 +678,16 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 } return 1; } + let gone = if t & 0x8000 != 0 { + GRAPHICS_RESERVATIONS.lock().unwrap().get(&(addr as usize)).copied().unwrap_or(0) + } else { + size + }; + let notify = gone > 0 && (overlaps_graphics_reservation(addr as usize, gone) || !mirrors::gpu_views_of(addr as usize).is_empty()); let ok = mem::VirtualFree(addr, size, t); + if ok != 0 && notify { + crate::hle::d3d12x::vram::title_memory_changed(addr as usize, gone); + } if ok != 0 && t & 0x8000 != 0 { let released = GRAPHICS_RESERVATIONS.lock().unwrap().remove(&(addr as usize)); if let Some(len) = released { @@ -1539,7 +1590,8 @@ unsafe fn alloc_physical_home(u: &crate::gpu::uma::Uma, bytes: usize) -> Option< return Some(p); } if !u.has_sparse() { - if let Some(p) = u.alloc(bytes, PHYS_PAGE) { + let fits = u.size().saturating_sub(u.used()) >= bytes.saturating_add(COHERENT_KEEP); + if let Some(p) = fits.then(|| u.alloc(bytes, PHYS_PAGE)).flatten() { return Some(p as usize); } } @@ -1655,12 +1707,18 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _ if alias::enabled() { return map_aliased(va, n, arr); } - let mut g = AWAY.lock().unwrap(); - let away = g.get_or_insert_with(Away::default); - let mut sparse_batch = SparseCommitBatch::default(); - let r = map_pages(away, va, n, arr, &mut sparse_batch); - sparse_batch.flush(); - give_back_homes(away); + let r = { + let mut g = AWAY.lock().unwrap(); + let away = g.get_or_insert_with(Away::default); + let mut sparse_batch = SparseCommitBatch::default(); + let r = map_pages(away, va, n, arr, &mut sparse_batch); + sparse_batch.flush(); + give_back_homes(away); + r + }; + if !r.is_null() { + notify_vram_backing(r as usize, n.saturating_mul(PHYS_PAGE)); + } r } @@ -1673,7 +1731,12 @@ unsafe fn map_aliased(va: *mut c_void, n: usize, arr: *mut usize) -> *mut c_void } note_mapping_at(va as usize); let pages: Vec = if arr.is_null() { vec![0; n] } else { std::slice::from_raw_parts(arr, n).to_vec() }; - if alias::map(va as usize, &pages) { va } else { std::ptr::null_mut() } + if alias::map(va as usize, &pages) { + notify_vram_backing(va as usize, n.saturating_mul(PHYS_PAGE)); + va + } else { + std::ptr::null_mut() + } } /// `MapTitlePhysicalPages` with `AWAY` held; the homes it moves away are given back by the @@ -1818,12 +1881,28 @@ pub unsafe extern "system" fn XMemMapPhysicalPagesScatter(addresses: *const *mut fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); return 0; } - let mut g = AWAY.lock().unwrap(); - let away = g.get_or_insert_with(Away::default); - let mut sparse_batch = SparseCommitBatch::default(); - let ok = (0..n).all(|i| !map_pages(away, *addresses.add(i), 1, page(i), &mut sparse_batch).is_null()); - sparse_batch.flush(); - give_back_homes(away); + let mut mapped: Vec = Vec::new(); + let ok = { + let mut g = AWAY.lock().unwrap(); + let away = g.get_or_insert_with(Away::default); + let mut sparse_batch = SparseCommitBatch::default(); + let ok = (0..n).all(|i| { + let addr = *addresses.add(i); + let r = map_pages(away, addr, 1, page(i), &mut sparse_batch); + if !r.is_null() { + mapped.push(r as usize); + true + } else { + false + } + }); + sparse_batch.flush(); + give_back_homes(away); + ok + }; + for a in mapped { + notify_vram_backing(a, PHYS_PAGE); + } ok as BOOL } From ac2938d29936384965bd0ca7cd6dad88185d4683 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:35:12 +0100 Subject: [PATCH 067/258] D3D12.X: state-diff ABI bindings, keep indirect scratch state, skip max=0 Cut per-draw/dispatch CPU and GPU overhead in bind.rs: 1. Short-circuit ExecuteIndirect immediately when max == 0 before taking locks, barriers, or ABI binds. 2. Track indirect argument scratch state per recording (COMMON on first use, kept in INDIRECT_ARGUMENT across consecutive guard_dispatch_args / make_scaled_args_buffer calls) instead of transitioning back to COMMON after every ExecuteIndirect; D3D12 decays buffers back to COMMON after ExecuteCommandLists. 3. State-diff bind_abi and bind_two_pass_stage: cache UMA window VAs per recording, reuse one zeroed 256-byte u1 (res) slot in bind_abi, track root-arg/heap generations (skipping no-op writes in put_in/set_heaps) to reuse uploaded io/table buffers, and emit Set*RootSignature / Set*RootUnorderedAccessView only when changed. Invalidate cached PC ABI state on reset, clear_state, inherit_for_split, internal argument passes, PC fallback binds, and tracked_root_sigs (after internal sync passes). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 504 ++++++++++++++++++++++++------ 1 file changed, 400 insertions(+), 104 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index c73cc552fb..e132755c43 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -18,6 +18,60 @@ use windows::Win32::Graphics::Direct3D12::*; use super::console_list::{self, Layout, Param}; +#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)] +struct AbiBound { + /// PC root signature currently bound on this list for this stage (0 = unknown/clobbered). + rs: usize, + /// Root UAV GPU VAs currently bound at slots 0..6 for `rs`. + uavs: [u64; 6], +} + +/// Diff `target_rs` and `target_uavs` against `bound`, updating `bound` and returning +/// `(need_set_rs, uav_mask)` where bit `k` of `uav_mask` means slot `k` must be bound. +/// Changing the root signature invalidates all 6 root UAV slots per D3D12 semantics. +fn diff_abi_bindings(bound: &mut AbiBound, target_rs: usize, target_uavs: [u64; 6]) -> (bool, u8) { + if bound.rs != target_rs { + bound.rs = target_rs; + bound.uavs = target_uavs; + return (true, 0b0011_1111); + } + let mut mask = 0u8; + for k in 0..6 { + if bound.uavs[k] != target_uavs[k] { + bound.uavs[k] = target_uavs[k]; + mask |= 1u8 << k; + } + } + (false, mask) +} + +unsafe fn emit_abi_bindings(list: &ID3D12GraphicsCommandList, gfx: bool, rs: &ID3D12RootSignature, set_rs: bool, uav_mask: u8, uavs: [u64; 6]) { + if gfx { + if set_rs { + list.SetGraphicsRootSignature(rs); + } + for (k, &v) in uavs.iter().enumerate() { + if uav_mask & (1u8 << k) != 0 { + list.SetGraphicsRootUnorderedAccessView(k as u32, v); + } + } + } else { + if set_rs { + list.SetComputeRootSignature(rs); + } + for (k, &v) in uavs.iter().enumerate() { + if uav_mask & (1u8 << k) != 0 { + list.SetComputeRootUnorderedAccessView(k as u32, v); + } + } + } +} + +fn uma_va_in(u: &crate::gpu::uma::Uma, windows: &[u64], p: usize) -> Option { + let k = u.window_of(p)?; + Some(*windows.get(k)? + (p - u.window(k).0) as u64) +} + #[derive(Default)] struct State { layout: Option>, @@ -47,6 +101,25 @@ struct State { scratch: Option<(ID3D12Resource, u64, usize)>, scratch_used: u64, scratch_taken: u64, + /// D3D12 state of the current `scratch` block on this list (`COMMON` initially, kept in + /// `INDIRECT_ARGUMENT` between consecutive argument-rewrite passes; buffers decay to `COMMON` + /// after `ExecuteCommandLists`) + scratch_state: D3D12_RESOURCE_STATES, + /// cached UMA window GPU VAs for this recording (avoids locking `UMA_BUFFER` every draw) + uma_windows: Option>, + /// reusable zeroed 256-byte `u1` (`res`) slot in this recording's UMA arena + dummy_res_va: u64, + /// tracked PC ABI root bindings for state-diffing + pc_abi_gfx: AbiBound, + pc_abi_cs: AbiBound, + /// monotonic generations incremented when root args, layout, or descriptor heaps change + args_gen_gfx: u64, + args_gen_cs: u64, + /// cached `io` GPU VAs keyed on `args_gen_*` (and compute `user_sgprs`) + io_cache_gfx: Option<(u64, u64)>, + io_cache_cs: Option<(u64, Option, u64)>, + io_cache_tp_cs: Option<(u64, u64)>, + io_cache_tp_ms: Option<(u64, u64)>, } /// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its @@ -132,6 +205,17 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.shared_records = false; // (the scratch blocks are in `res_retired` already) (s.scratch, s.scratch_used, s.scratch_taken) = (None, 0, 0); + s.scratch_state = D3D12_RESOURCE_STATE_COMMON; + s.uma_windows = None; + s.dummy_res_va = 0; + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; let mut res_bufs = std::mem::take(&mut s.res_retired); if let Some(b) = s.res_buf.take() { res_bufs.push(b); @@ -155,6 +239,14 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { s.rs_gfx = 0; s.heaps = [0; 2]; s.rs_cs = 0; + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; }); } @@ -176,6 +268,18 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.rs_cs = rs_cs; s.pso = pso; s.heaps = heaps; + (s.scratch, s.scratch_used, s.scratch_taken) = (None, 0, 0); + s.scratch_state = D3D12_RESOURCE_STATE_COMMON; + s.uma_windows = None; + s.dummy_res_va = 0; + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; (old, std::mem::take(&mut s.uma)) }); console_list::hold_until_reset(old, blocks); @@ -222,7 +326,17 @@ pub(super) fn set_heaps(list: *mut c_void, heaps: &[usize]) { for (sampler, base) in heaps.iter().filter_map(|&h| super::console_heap::base(h)) { bases[sampler as usize] = base; } - with(list, |s| s.heaps = bases); + with(list, |s| { + if s.heaps != bases { + s.heaps = bases; + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; + } + }); } /// bytes of parameter `i` at constant `offset` (of the compute or the graphics arguments) @@ -236,7 +350,18 @@ fn put_in(list: *mut c_void, gfx: bool, i: u32, offset: u32, bytes: &[u8]) { return; }; if let Some(t) = args.get_mut(at..at + bytes.len()) { - t.copy_from_slice(bytes); + if t != bytes { + t.copy_from_slice(bytes); + if gfx { + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; + } else { + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_cs = None; + } + } } }) } @@ -252,6 +377,10 @@ pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_vo s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; s.layout_gfx = layout; s.rs_gfx = rs as usize; + s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); + s.io_cache_gfx = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; }); } @@ -556,42 +685,68 @@ unsafe fn bind_two_pass_stage( // the pair is translated with heap windows when they are on (`pso::mem_windows`): as `bind_abi` super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; - let windows = super::real::uma_window_vas(); - let first = *windows.first().ok_or("unified memory is not open on the GPU")?; - let (layout, args, heaps) = with(this, |s| (s.layout_gfx.clone(), s.args_gfx.clone(), s.heaps)); - let copy = |bytes: &[u8]| -> Result { - let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); - Ok(p as usize) - }; - let inline = layout - .as_ref() - .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) - .min(args.len()); - let table_at = copy(&args[inline..])?; - let io = two_pass_io(layout.as_deref(), &args, table_at as u64, compute_pass, u.base(), heaps); - let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; - let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); - let rs_raw = if compute_pass { tp.compute_rs } else { tp.mesh_rs } as *mut c_void; + let rs_usize = if compute_pass { tp.compute_rs } else { tp.mesh_rs }; + let rs_raw = rs_usize as *mut c_void; let rs = ID3D12RootSignature::from_raw_borrowed(&rs_raw).ok_or("two-pass root signature")?; - let views = [va(io_at), res_va].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); - if compute_pass { - list.SetComputeRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetComputeRootUnorderedAccessView(k as u32, v); - } - let pso_raw = tp.compute as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass compute pipeline")?; - list.SetPipelineState(pc); - } else { - list.SetGraphicsRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetGraphicsRootUnorderedAccessView(k as u32, v); - } - let pso_raw = real_mesh_pso as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or("two-pass mesh pipeline")?; - list.SetPipelineState(pc); - } + let pso_raw = if compute_pass { tp.compute } else { real_mesh_pso } as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or(if compute_pass { "two-pass compute pipeline" } else { "two-pass mesh pipeline" })?; + + let (set_rs, uav_mask, views) = with(this, |s| -> Result<(bool, u8, [u64; 6]), String> { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + let w = super::real::uma_window_vas(); + if w.is_empty() { + return Err("unified memory is not open on the GPU".into()); + } + s.uma_windows = Some(w); + } + let windows = s.uma_windows.as_deref().unwrap(); + let first = windows[0]; + let win_vas = [ + first, + windows.get(1).copied().unwrap_or(first), + windows.get(2).copied().unwrap_or(first), + windows.get(3).copied().unwrap_or(first), + ]; + + let cached_io = if compute_pass { + s.io_cache_tp_cs.filter(|&(gen, _)| gen == s.args_gen_gfx).map(|(_, va)| va) + } else { + s.io_cache_tp_ms.filter(|&(gen, _)| gen == s.args_gen_gfx).map(|(_, va)| va) + }; + let io_va = if let Some(va) = cached_io { + va + } else { + let layout = s.layout_gfx.as_deref(); + let args = s.args_gfx.as_slice(); + let inline = layout + .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) + .min(args.len()); + let tail = &args[inline..]; + let table_p = s.arena.take(u, tail.len().max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + if !tail.is_empty() { + std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); + } + let io = two_pass_io(layout, args, table_p as u64, compute_pass, u.base(), s.heaps); + let io_bytes = io.len() * 4; + let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(io.as_ptr().cast::(), io_p, io_bytes); + let va = uma_va_in(u, windows, io_p as usize).unwrap_or(first); + if compute_pass { + s.io_cache_tp_cs = Some((s.args_gen_gfx, va)); + } else { + s.io_cache_tp_ms = Some((s.args_gen_gfx, va)); + } + va + }; + + let views = [io_va, res_va, win_vas[0], win_vas[1], win_vas[2], win_vas[3]]; + let bound = if compute_pass { &mut s.pc_abi_cs } else { &mut s.pc_abi_gfx }; + let (set_rs, uav_mask) = diff_abi_bindings(bound, rs_usize, views); + Ok((set_rs, uav_mask, views)) + })?; + + emit_abi_bindings(list, !compute_pass, rs, set_rs, uav_mask, views); + list.SetPipelineState(pc); Ok(()) } @@ -729,8 +884,9 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; // the title's writes of the arguments before this (`fresh_indirect_arguments`) + let prev_state = with(this, |s| s.scratch_state); emit_uav_barrier(list, None); - emit_transition(list, &dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); list.SetComputeRootUnorderedAccessView(0, consts_va); @@ -738,6 +894,10 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress() + dst_off); list.Dispatch(1, 1, 1); emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + with(this, |s| { + s.scratch_state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.pc_abi_cs = AbiBound::default(); + }); Ok((dst, dst_off)) } @@ -839,6 +999,7 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res s.scratch_taken += block.1; s.scratch_used = bytes; s.scratch = Some(block.clone()); + s.scratch_state = D3D12_RESOURCE_STATE_COMMON; s.res_retired.push(block); }); Ok((b, 0)) @@ -886,8 +1047,9 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman // `SCALE_ARGS_HLSL` statically references `cnt : register(u4)`. let cnt_base = count_bound.map_or(consts_va, |(base, _)| base); // the title's writes of the arguments before this (`fresh_indirect_arguments`) + let prev_state = with(this, |s| s.scratch_state); emit_uav_barrier(list, None); - emit_transition(list, &dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); list.SetComputeRootUnorderedAccessView(0, consts_va); @@ -896,6 +1058,10 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman list.SetComputeRootUnorderedAccessView(3, cnt_base); list.Dispatch(max.div_ceil(64), 1, 1); emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + with(this, |s| { + s.scratch_state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.pc_abi_cs = AbiBound::default(); + }); Ok((dst, dst_off)) } @@ -973,6 +1139,7 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: let rs = with(this, |s| s.rs_gfx) as *mut c_void; if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { list.SetGraphicsRootSignature(r); + with(this, |s| s.pc_abi_gfx = AbiBound::default()); } count(DRAWS_PC); pc_dm(this, x, y, z); @@ -982,6 +1149,9 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: /// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root /// arguments themselves cannot be – skipped, logged) pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) { + if max == 0 { + return; + } type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let raw_pso = with(this, |s| s.pso); @@ -1026,19 +1196,15 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // the groups past the record buffer, and the commands past the count, are dropped // on the GPU (`SCALE_ARGS_HLSL`) let (scaled, at) = make_scaled_args_buffer(this, list, src, count, max, msig.byte_stride, msig.mesh_offset, tp.mesh_groups_per_record, cap)?; - let passes = (|| -> Result<(), String> { - for (k, compute) in two_pass_steps(max) { - bind_two_pass_stage(this, list, pso, &tp, res_va, compute)?; - let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; - let mark = super::culprit::before_dispatch(list, raw_pso, pso, [0, 0, if compute { 1 } else { 0x3e2 }]); - pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); - super::culprit::after_dispatch(list, mark); - emit_uav_barrier(list, Some(&res_buf)); - } - Ok(()) - })(); - emit_transition(list, &scaled, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); - passes + for (k, compute) in two_pass_steps(max) { + bind_two_pass_stage(this, list, pso, &tp, res_va, compute)?; + let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; + let mark = super::culprit::before_dispatch(list, raw_pso, pso, [0, 0, if compute { 1 } else { 0x3e2 }]); + pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); + super::culprit::after_dispatch(list, mark); + emit_uav_barrier(list, Some(&res_buf)); + } + Ok(()) })(); match run { Ok(()) => { @@ -1108,6 +1274,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let rs = with(this, |s| s.rs_gfx) as *mut c_void; if let (Some(list), Some(r)) = (ID3D12GraphicsCommandList::from_raw_borrowed(&this), ID3D12RootSignature::from_raw_borrowed(&rs)) { list.SetGraphicsRootSignature(r); + with(this, |s| s.pc_abi_gfx = AbiBound::default()); } return fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); } @@ -1140,11 +1307,6 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } let (args, args_off) = guarded.as_ref().map_or((args, args_off), |(b, o)| (b.as_raw() as usize, *o)); - let unguard = || { - if let Some((b, _)) = &guarded { - emit_transition(list, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); - } - }; match bind_abi(this, list, pso, gfx) { Ok(()) => { if compute { @@ -1154,7 +1316,6 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us Err(e) => { crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); count(DISPATCHES_SKIPPED); - unguard(); return; } } @@ -1168,10 +1329,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) } super::culprit::after_dispatch(list, mark); - unguard(); } Err(e) => { - unguard(); count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1416,6 +1575,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option let rs = with(this, |s| s.rs_gfx) as *mut c_void; if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) { list.SetGraphicsRootSignature(r); + with(this, |s| s.pc_abi_gfx = AbiBound::default()); } return Some(list); } @@ -1664,6 +1824,8 @@ pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_voi s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; s.layout = layout; s.rs_cs = rs as usize; + s.args_gen_cs = s.args_gen_cs.wrapping_add(1); + s.io_cache_cs = None; }); } @@ -1847,51 +2009,85 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; - let windows = super::real::uma_window_vas(); - let first = *windows.first().ok_or("unified memory is not open on the GPU")?; - let (layout, args, heaps) = with(this, |s| { - let (layout, args) = if gfx { (&s.layout_gfx, &s.args_gfx) } else { (&s.layout, &s.args) }; - (layout.clone(), args.clone(), s.heaps) - }); - // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) - let copy = |bytes: &[u8]| -> Result { - let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len()); - Ok(p as usize) - }; // a pipeline still being built in the background is waited for let real = super::pso_async::resolve_wait(pso); // a compute shader takes no more arguments from registers than it has (`inline_for`) let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; - let inline = layout.as_ref().map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); - let table_at = copy(&args[inline..])?; - let mut io = match layout.as_ref() { - Some(l) if gfx => console_list::with_heaps(l, None, console_list::user_data_gfx(l, &args, table_at as u64), heaps), - Some(l) => console_list::with_heaps(l, user_sgprs, console_list::user_data_for(l, user_sgprs, &args, table_at as u64), heaps), - None => vec![table_at as u32, (table_at >> 32) as u32], - }; - io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); - io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; - let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; - let res_at = copy(&[0u8; 256])?; - let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); - let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; - let rs = rs as *mut c_void; - let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; - let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().unwrap_or(first))); - if gfx { - list.SetGraphicsRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetGraphicsRootUnorderedAccessView(k as u32, v); - } - } else { - list.SetComputeRootSignature(rs); - for (k, v) in views.enumerate() { - list.SetComputeRootUnorderedAccessView(k as u32, v); + let rs_raw = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; + let rs_ptr = rs_raw as *mut c_void; + let rs = ID3D12RootSignature::from_raw_borrowed(&rs_ptr).ok_or("root signature")?; + let real_ptr = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&real_ptr).ok_or("pipeline")?; + + let (set_rs, uav_mask, views) = with(this, |s| -> Result<(bool, u8, [u64; 6]), String> { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + let w = super::real::uma_window_vas(); + if w.is_empty() { + return Err("unified memory is not open on the GPU".into()); + } + s.uma_windows = Some(w); + } + let windows = s.uma_windows.as_deref().unwrap(); + let first = windows[0]; + let win_vas = [ + first, + windows.get(1).copied().unwrap_or(first), + windows.get(2).copied().unwrap_or(first), + windows.get(3).copied().unwrap_or(first), + ]; + + // Runtime VS/PS/CS shaders never write to `u1` (`res`), so one zeroed 256-byte slot + // per recording suffices across all `bind_abi` draws and dispatches. + if s.dummy_res_va == 0 { + let p = s.arena.take(u, 256, 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::write_bytes(p, 0, 256); + s.dummy_res_va = uma_va_in(u, windows, p as usize).unwrap_or(first); } - } - let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; + let res_va = s.dummy_res_va; + + let cached_io = if gfx { + s.io_cache_gfx.filter(|&(gen, _)| gen == s.args_gen_gfx).map(|(_, va)| va) + } else { + s.io_cache_cs.filter(|&(gen, sgprs, _)| gen == s.args_gen_cs && sgprs == user_sgprs).map(|(_, _, va)| va) + }; + let io_va = if let Some(va) = cached_io { + va + } else { + let (layout, args) = if gfx { (s.layout_gfx.as_deref(), s.args_gfx.as_slice()) } else { (s.layout.as_deref(), s.args.as_slice()) }; + let inline = layout.map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); + let tail = &args[inline..]; + // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) + let table_p = s.arena.take(u, tail.len().max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + if !tail.is_empty() { + std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); + } + let table_at = table_p as u64; + let mut io = match layout { + Some(l) if gfx => console_list::with_heaps(l, None, console_list::user_data_gfx(l, args, table_at), s.heaps), + Some(l) => console_list::with_heaps(l, user_sgprs, console_list::user_data_for(l, user_sgprs, args, table_at), s.heaps), + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + let io_bytes = io.len() * 4; + let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(io.as_ptr().cast::(), io_p, io_bytes); + let va = uma_va_in(u, windows, io_p as usize).unwrap_or(first); + if gfx { + s.io_cache_gfx = Some((s.args_gen_gfx, va)); + } else { + s.io_cache_cs = Some((s.args_gen_cs, user_sgprs, va)); + } + va + }; + + let views = [io_va, res_va, win_vas[0], win_vas[1], win_vas[2], win_vas[3]]; + let bound = if gfx { &mut s.pc_abi_gfx } else { &mut s.pc_abi_cs }; + let (set_rs, uav_mask) = diff_abi_bindings(bound, rs_raw, views); + Ok((set_rs, uav_mask, views)) + })?; + + emit_abi_bindings(list, gfx, rs, set_rs, uav_mask, views); list.SetPipelineState(pc); Ok(()) } @@ -1917,14 +2113,19 @@ pub(super) fn tracked_pso(list: *mut c_void) -> usize { } /// Tracked console `(graphics_root_signature, compute_root_signature)` on `list` for restoring -/// PC root signatures after an internal graphics/compute sync pass. +/// PC root signatures after an internal graphics/compute sync pass (invalidating cached PC ABI +/// root bindings since the internal pass clobbered them). pub(super) fn tracked_root_sigs(list: *mut c_void) -> (usize, usize) { STATES .lock() .unwrap() - .as_ref() - .and_then(|m| m.get(&(list as usize))) - .map_or((0, 0), |s| (s.rs_gfx, s.rs_cs)) + .as_mut() + .and_then(|m| m.get_mut(&(list as usize))) + .map_or((0, 0), |s| { + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + (s.rs_gfx, s.rs_cs) + }) } #[cfg(test)] @@ -3243,4 +3444,99 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) dst_buf.Unmap(0, None); } } + + #[test] + fn abi_binding_state_diff_only_rebinds_changed_slots_and_resets_on_rs_change() { + let mut bound = AbiBound::default(); + let uavs1 = [0x100, 0x200, 0x1000, 0x2000, 0x3000, 0x4000]; + assert_eq!(diff_abi_bindings(&mut bound, 0xA000, uavs1), (true, 0b0011_1111)); + assert_eq!(diff_abi_bindings(&mut bound, 0xA000, uavs1), (false, 0)); + + // Only io (slot 0) changed with same RS -> rebind slot 0 only. + let mut uavs2 = uavs1; + uavs2[0] = 0x180; + assert_eq!(diff_abi_bindings(&mut bound, 0xA000, uavs2), (false, 0b0000_0001)); + + // io + res changed with same RS -> rebind slots 0 and 1 only. + let mut uavs3 = uavs2; + uavs3[0] = 0x280; + uavs3[1] = 0x300; + assert_eq!(diff_abi_bindings(&mut bound, 0xA000, uavs3), (false, 0b0000_0011)); + + // Root signature changed -> must rebind RS and all 6 UAV slots even if VAs are unchanged. + assert_eq!(diff_abi_bindings(&mut bound, 0xB000, uavs3), (true, 0b0011_1111)); + assert_eq!(diff_abi_bindings(&mut bound, 0xB000, uavs3), (false, 0)); + } + + #[test] + fn root_arg_caching_and_invalidation_track_changes_and_internal_passes() { + let list = 0x7600_0001usize as *mut c_void; + let rs_key = 0x7600_0010usize; + console_list::note_root_signature(rs_key, &test_rts0_blob()); + reset(list, 0x7600_0100, 0); + unsafe { + set_graphics_root_signature(list, rs_key as *mut c_void); + set_graphics_root_constant(list, 0, 0x1234, 0); + } + let gen1 = with(list, |s| { + s.io_cache_gfx = Some((s.args_gen_gfx, 0x5555_0000)); + s.pc_abi_gfx = AbiBound { rs: 0xAAAA, uavs: [1, 2, 3, 4, 5, 6] }; + s.pc_abi_cs = AbiBound { rs: 0xBBBB, uavs: [7, 8, 9, 10, 11, 12] }; + s.scratch_state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.args_gen_gfx + }); + // Writing the exact same value leaves generation and cached io intact. + unsafe { set_graphics_root_constant(list, 0, 0x1234, 0); } + with(list, |s| { + assert_eq!(s.args_gen_gfx, gen1); + assert_eq!(s.io_cache_gfx, Some((gen1, 0x5555_0000))); + }); + // Writing a different value bumps generation and invalidates cached io. + unsafe { set_graphics_root_constant(list, 0, 0x5678, 0); } + with(list, |s| { + assert_ne!(s.args_gen_gfx, gen1); + assert_eq!(s.io_cache_gfx, None); + }); + // tracked_root_sigs invalidates cached PC ABI bindings after internal sync passes. + assert_eq!(tracked_root_sigs(list), (rs_key, 0)); + with(list, |s| { + assert_eq!(s.pc_abi_gfx, AbiBound::default()); + assert_eq!(s.pc_abi_cs, AbiBound::default()); + }); + // reset resets scratch_state back to COMMON. + reset(list, 0x7600_0200, 0); + with(list, |s| assert_eq!(s.scratch_state, D3D12_RESOURCE_STATE_COMMON)); + forget(list); + } + + #[test] + fn execute_indirect_with_zero_max_count_short_circuits() { + let mut orig_vt = [0usize; 64]; + orig_vt[1] = fake_add_ref as usize; + orig_vt[2] = fake_release as usize; + orig_vt[29] = fake_set_compute_rs as usize; + orig_vt[41] = fake_set_compute_uav as usize; + orig_vt[59] = fake_execute_indirect as usize; + let mut ext_vt = vec![0usize; 65]; + ext_vt[0] = orig_vt.as_ptr() as usize; + ext_vt[1..].copy_from_slice(&orig_vt); + let fake = Box::new(FakeAdoptedList { + vt: unsafe { ext_vt.as_ptr().add(1) }, + refs: AtomicUsize::new(1), + dispatch_calls: AtomicUsize::new(0), + set_compute_rs_calls: AtomicUsize::new(0), + set_compute_uav_calls: AtomicUsize::new(0), + set_pso_calls: AtomicUsize::new(0), + execute_indirect_calls: AtomicUsize::new(0), + }); + let list_ptr = &*fake as *const FakeAdoptedList as *mut c_void; + let before = counts_snapshot(); + unsafe { + execute_indirect(list_ptr, 0x7700_0001, 0, 0, 0, 0, 0); + } + assert_eq!(fake.execute_indirect_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_compute_rs_calls.load(Ordering::Relaxed), 0); + assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); + assert_eq!(counts_snapshot(), before); + } } From 593e9cd6edd05fecd3b790ca958cc71e512d02ea Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:38:59 +0100 Subject: [PATCH 068/258] D3D12.X: map exhausted hosted view-heap slots to null slot 0 (#2380) When a view heap is hosted in the shared shader-visible heap (GLOBAL) and GLOBAL runs out of free pages, console_heap::slot fell back to local index 2 * k. Because command lists bind GLOBAL, 2 * k aliased MEM_HEAP_BASE raw-buffer memory window UAVs (or unrelated heaps), causing texture reads on raw-buffer UAVs to hang the GPU. Mirror sampler_unmapped_index with view_unmapped_index(hosted, k): hosted view heaps map unmapped/exhausted slots to reserved null-view slot 0 (SRV 0 / UAV 1) with pc_gpu_uav = 0, while unhosted heaps preserve local 2 * k. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/console_heap.rs | 24 ++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index ca14e8fc34..b9ef5b6c2e 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -105,6 +105,14 @@ pub const PAGE_SLOTS: u32 = 256; /// a page with no place in the shared heap yet const UNMAPPED: u32 = u32::MAX; +/// Fallback index for a view slot when no `GLOBAL` page is mapped: +/// hosted heaps (`hosted == true`, whose lists bind `GLOBAL`) map overflowed slots to reserved +/// null-view slot `0` (SRV at 0, UAV at 1) so exhaustion never aliases `MEM_HEAP_BASE` window +/// UAVs or unrelated descriptors; unhosted heaps keep local `2 * k`. +fn view_unmapped_index(hosted: bool, k: u32) -> u32 { + if hosted { 0 } else { 2 * k } +} + /// PC descriptors of page `p` of a heap of `n` slots: 2 per slot, and the last page only as /// long as the heap (a heap of a few slots takes a few descriptors, not a whole page's). fn page_descriptors(n: u32, p: u32) -> u32 { @@ -462,7 +470,10 @@ pub fn slot(cpu: u64) -> Option { let i = first + 2 * (k - k0); Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) }); - let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or((2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0)); + let hosted = !h.pages.is_empty(); + let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or_else(|| { + (view_unmapped_index(hosted, k), if hosted || h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0) + }); Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k }) } @@ -1181,4 +1192,15 @@ mod tests { assert_eq!(sampler_own_index(&[], 0), 0); assert_eq!(sampler_own_index(&[], 42), 42); } + + #[test] + fn exhausted_hosted_view_slots_map_to_null_slot_zero() { + // Hosted view heaps must never fall back to `2 * k`, which aliases `MEM_HEAP_BASE` window UAVs. + assert_eq!(view_unmapped_index(true, 0), 0); + assert_eq!(view_unmapped_index(true, crate::gpu::recomp::MEM_HEAP_BASE / 2), 0); + assert_eq!(view_unmapped_index(true, 42), 0); + // Unhosted heaps (no shared heap) keep their own local 2 * k layout. + assert_eq!(view_unmapped_index(false, 0), 0); + assert_eq!(view_unmapped_index(false, 42), 84); + } } From b1a142cb86707e1381a109bb7619a54172011c6d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:39:07 +0100 Subject: [PATCH 069/258] D3D12.X: retain RTV resource under RTVS lock in note_execute (#2381) present::note_execute dropped RTVS.lock() before calling backbuffer_like(res) (which invokes GetDesc()) and add_ref(res). A concurrent note_rtv overwrite or clear on another thread could release the last COM reference in between, causing a use-after-free. Add retain_rtv_resource(handle) to AddRef the resource while still holding RTVS.lock(), call backbuffer_like safely on the owned reference, transfer ownership directly into CANDIDATE if selected, and release outside the locks otherwise. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/present.rs | 68 +++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index c41e3bfea0..5505830282 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -251,6 +251,15 @@ pub fn is_presented(res: usize) -> bool { PRESENTED.lock().unwrap().contains(&res) } +/// Look up the resource behind RTV `handle` and retain a COM reference while holding `RTVS`, +/// preventing a concurrent `note_rtv` overwrite/removal from freeing it before use. +unsafe fn retain_rtv_resource(handle: usize) -> Option { + let g = RTVS.lock().unwrap(); + let res = g.as_ref()?.get(&handle).copied()?; + add_ref(res); + Some(res) +} + /// the resource an RTV handle names (render-target binds) pub fn rtv_resource(handle: usize) -> Option { RTVS.lock().unwrap().as_ref()?.get(&handle).copied() @@ -328,19 +337,21 @@ pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { lists.iter().rev().find_map(|l| m.get(&(*l as usize)).copied()) }; let Some(h) = handle else { return }; - let res = RTVS.lock().unwrap().as_ref().and_then(|m| m.get(&h).copied()); - let Some(res) = res else { return }; + let Some(res) = retain_rtv_resource(h) else { return }; if backbuffer_like(res).is_none() { + release(res); return; } - { + let to_release = { let mut c = CANDIDATE.lock().unwrap(); if c.map(|(_, r)| r) != Some(res) { - add_ref(res); - if let Some((_, old)) = c.replace((queue as usize, res)) { - release(old); - } + c.replace((queue as usize, res)).map(|(_, old)| old) + } else { + Some(res) } + }; + if let Some(old) = to_release { + release(old); } // no console present call seen recently → present on submissions (rate limited) if now_ms().saturating_sub(LAST_BOUNDARY_MS.load(Ordering::Relaxed)) > 500 { @@ -1940,4 +1951,47 @@ mod frame_dump_tests { rb.Unmap(0, None); } } + + #[test] + fn retain_rtv_resource_keeps_com_ref_alive_across_rtv_removal() { + use std::sync::atomic::AtomicU32; + #[repr(C)] + struct FakeCom { + vt: *const usize, + refs: AtomicU32, + } + unsafe extern "system" fn fake_add_ref(p: usize) -> u32 { + (*(p as *const FakeCom)).refs.fetch_add(1, Ordering::AcqRel) + 1 + } + unsafe extern "system" fn fake_release(p: usize) -> u32 { + (*(p as *const FakeCom)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + let mut vt = [0usize; 3]; + vt[1] = fake_add_ref as usize; + vt[2] = fake_release as usize; + let obj = Box::new(FakeCom { vt: vt.as_ptr(), refs: AtomicU32::new(1) }); + let raw = &*obj as *const FakeCom as usize; + let handle = 0x7900_0001usize; + unsafe { + { + let mut g = RTVS.lock().unwrap(); + add_ref(raw); + g.get_or_insert_with(HashMap::new).insert(handle, raw); + } + assert_eq!(obj.refs.load(Ordering::Acquire), 2); + let retained = retain_rtv_resource(handle).expect("retained RTV resource"); + assert_eq!(retained, raw); + assert_eq!(obj.refs.load(Ordering::Acquire), 3); + // Simulate concurrent RTV slot clear releasing the table's ref while caller holds its own. + { + let mut g = RTVS.lock().unwrap(); + if let Some(old) = g.as_mut().and_then(|m| m.remove(&handle)) { + release(old); + } + } + assert_eq!(obj.refs.load(Ordering::Acquire), 2, "caller ref must keep object alive"); + release(retained); + assert_eq!(obj.refs.load(Ordering::Acquire), 1); + } + } } From bc12d07a75700eec2281c65d293c6abeb34b4862 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:41:22 +0100 Subject: [PATCH 070/258] D3D12.X: build split ExecuteIndirect whole PSO off the title thread (#505) ExecuteIndirect of a split compute pipeline previously called dispatch_chain::whole synchronously on the recording thread under build_whole.lock(), blocking the title thread for 15-60 s on huge unsplit DXIL blobs and tripping the 30 s watchdog. Add dispatch_chain::whole_nonblocking(pso): when async PSO builds are enabled and the whole form is not yet built, spawn a background worker thread once to build it and return WholeStatus::Pending so ExecuteIndirect skips that dispatch immediately (before guard_dispatch_args / bind_abi) instead of stalling the title thread. Once ready, subsequent indirect dispatches bind the whole PSO without blocking; sync mode (!pso_async::enabled()) retains synchronous builds. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 38 +++++++--- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 73 ++++++++++++++++++- 2 files changed, 97 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e132755c43..89846f9c28 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1286,6 +1286,32 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + // For split compute pipelines, resolve the whole form without stalling the title thread + // (kicking off background compilation on first indirect use instead of blocking 15-60s). + let whole_pso = if compute { + match super::real::dispatch_chain::whole_nonblocking(pso) { + super::real::dispatch_chain::WholeStatus::NotSplit => None, + super::real::dispatch_chain::WholeStatus::Ready(whole) => Some(whole), + super::real::dispatch_chain::WholeStatus::Pending => { + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!("D3D12.X: ExecuteIndirect of split compute PSO ({pso:#x}) skipped while whole form builds in background"); + } + return; + } + super::real::dispatch_chain::WholeStatus::Failed => { + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO ({pso:#x}) failed – skipped"); + } + return; + } + } + } else { + None + }; // (before the dispatch's own root signature and pipeline are bound) let mut guarded = None; if compute && max == 1 && indirect_guard() && signature_dispatches(sig) { @@ -1309,16 +1335,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let (args, args_off) = guarded.as_ref().map_or((args, args_off), |(b, o)| (b.as_raw() as usize, *o)); match bind_abi(this, list, pso, gfx) { Ok(()) => { - if compute { - match super::real::dispatch_chain::whole(pso) { - Ok(Some(whole)) => list.SetPipelineState(&whole), - Ok(None) => {} - Err(e) => { - crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); - count(DISPATCHES_SKIPPED); - return; - } - } + if let Some(whole) = whole_pso { + list.SetPipelineState(&whole); } count(if gfx { DRAWS } else { DISPATCHES }); // an indirect dispatch: its groups are in the argument buffer (`max` of them) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 0578506179..7cf8f5a012 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -54,9 +54,23 @@ struct Chain { words: u32, whole_code: Vec, whole: OnceLock, + whole_started: AtomicBool, + whole_failed: AtomicBool, build_whole: Mutex<()>, } +pub(in crate::hle::d3d12x) enum WholeStatus { + /// Not a split compute pipeline. + NotSplit, + /// Whole pipeline is built and ready to bind without blocking. + Ready(ID3D12PipelineState), + /// Whole pipeline is compiling on a background thread; skip this indirect dispatch to avoid + /// stalling the title thread past its watchdog. + Pending, + /// Background compilation of the whole pipeline failed. + Failed, +} + impl Chain { unsafe fn whole(&self) -> Result { if let Some(p) = self.whole.get() { return Ok(p.clone()); } @@ -67,6 +81,29 @@ impl Chain { let _ = self.whole.set(p.clone()); Ok(p) } + + fn start_whole_async(self: &Arc) { + if self.whole.get().is_some() || self.whole_failed.load(Ordering::Acquire) { + return; + } + if self.whole_started.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + return; + } + let chain = Arc::clone(self); + let record = chain.builder.record; + if std::thread::Builder::new() + .name(format!("xcl-whole-{record:016x}")) + .spawn(move || { + if let Err(e) = unsafe { chain.whole() } { + chain.whole_failed.store(true, Ordering::Release); + crate::xlog_warn!("D3D12.X: background whole compute PSO for cs {record:016x} failed: {e}"); + } + }) + .is_err() + { + self.whole_started.store(false, Ordering::Release); + } + } } static CHAINS: LazyLock>>> = LazyLock::new(Default::default); @@ -96,7 +133,8 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let mut pieces = all.into_iter(); let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()) }); + whole_code: whole.to_vec(), whole: OnceLock::new(), whole_started: AtomicBool::new(false), + whole_failed: AtomicBool::new(false), build_whole: Mutex::new(()) }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -109,9 +147,30 @@ pub(super) fn forget(pso: usize) { drop(gone); // releasing a tail PSO also goes through forget_pso } -pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result, String> { - let chain = CHAINS.lock().unwrap().get(&pso).cloned(); - chain.map(|c| c.whole()).transpose() +/// Resolve the whole compute pipeline for an `ExecuteIndirect` without stalling the recording +/// thread: when async PSO builds are enabled and the whole form is not compiled yet, kick off +/// its build once on a background thread and return `Pending`. +pub(in crate::hle::d3d12x) unsafe fn whole_nonblocking(pso: usize) -> WholeStatus { + let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { + return WholeStatus::NotSplit; + }; + if let Some(p) = chain.whole.get() { + return WholeStatus::Ready(p.clone()); + } + if chain.whole_failed.load(Ordering::Acquire) { + return WholeStatus::Failed; + } + if !super::super::pso_async::enabled() { + return match chain.whole() { + Ok(p) => WholeStatus::Ready(p), + Err(_) => { + chain.whole_failed.store(true, Ordering::Release); + WholeStatus::Failed + } + }; + } + chain.start_whole_async(); + WholeStatus::Pending } struct Scratch { @@ -254,4 +313,10 @@ mod tests { assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, None, 400 * MB, 384 * MB), (9 * MB, true)); assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true)); } + + #[test] + fn whole_nonblocking_returns_not_split_for_unknown_pso() { + assert!(matches!(unsafe { super::whole_nonblocking(0) }, super::WholeStatus::NotSplit)); + assert!(matches!(unsafe { super::whole_nonblocking(0x7800_0001) }, super::WholeStatus::NotSplit)); + } } From 613fd4a92b070ebf09ce34516dc6fc5afecce09e Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:48:23 +0100 Subject: [PATCH 071/258] D3D12.X: fold compute dispatches over 65,535 groups in X into Y (#1428) Port #1428's >65,535 X->Y compute dispatch folding onto amd-dev and integrate it directly into bind.rs's guard_dispatch_args pass (avoiding a second indirect compute pass): - Add IO_GROUP_LIMIT (slot 113) and FOLD_X (65,535) in gpu/recomp/mod.rs and unfold gid.x + gid.y * 65535 with early group exit past the count in HLSL (recomp/emit.rs), per-lane IR (recomp/lower.rs), and Direct DXIL (dxil/kernel.rs). - Fold direct Dispatch and console_list dispatches via bind::fold(x, y, z) so 1D grids like 2560x1440 final gather's 115,200 groups run as 65,535 x 2 instead of being clamped to 65,535. - Extend GUARD_ARGS_HLSL / guard_dispatch_args to fold >65,535 x 1 x z indirect dispatches and write IO_GROUP_LIMIT into a dedicated compute io buffer (u4), batching [UAV, transition] and [transition, UAV] into single ResourceBarrier calls. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/kernel.rs | 39 ++- crates/xcl/src/gpu/recomp/emit.rs | 10 +- crates/xcl/src/gpu/recomp/lower.rs | 25 +- crates/xcl/src/gpu/recomp/mod.rs | 8 + crates/xcl/src/hle/d3d12x/bind.rs | 294 +++++++++++++++++----- crates/xcl/src/hle/d3d12x/console_list.rs | 3 + 6 files changed, 309 insertions(+), 70 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index e7066a713a..48e34d4827 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -205,6 +205,8 @@ fn translate_on_this_thread( let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); let mut split_tid = None; + // a compute program: whether this group runs (`compute_init`: not past a folded dispatch's count) + let mut group_runs = None; let numthreads = match &entry { Entry::Kernel => { lw.setup_lanes(); @@ -218,7 +220,7 @@ fn translate_on_this_thread( Entry::Compute(cs) => { let (tid, gtid) = lw.setup_lanes_compute(cs.threads, uses_lds); if split && !uses_lds && cs.threads == [64, 1, 1] { split_tid = Some(tid); } - compute_init(&mut lw, cs, tid, gtid); + group_runs = Some(compute_init(&mut lw, cs, tid, gtid)); cs.threads } Entry::Mesh(ms) => { @@ -310,6 +312,8 @@ fn translate_on_this_thread( } let h0 = if plan.is_some() { lw.block(None) } else { head(&mut lw, entry) }; let exit = lw.block(None); + // where `Block(0)` goes + let mut first = h0; if gs_only { // the GS alone: in the lower hardware wave only let gate = lw.block(Some(1)); @@ -317,6 +321,15 @@ fn translate_on_this_thread( lw.s.m.set_block(gate); let up = lw.upper; lw.cond_br(up, exit, h0); + first = gate; + } else if let Some(runs) = group_runs { + // a folded dispatch's groups past the console's count leave at once (the whole group: + // no barrier waits on them) + let gate = lw.block(Some(1)); + lw.edge(Block(0), gate); + lw.s.m.set_block(gate); + lw.cond_br(runs, h0, exit); + first = gate; } else { lw.edge(Block(0), h0); } @@ -429,7 +442,7 @@ fn translate_on_this_thread( } lw.s.m.ret(); lw.s.m.set_block(Block(0)); - lw.s.m.br(h0); + lw.s.m.br(first); let hw = if split || !o.wave64 { 32 } else { 64 }; let limit = if compute && (!split || split_tid.is_some()) { dispatch_piece_limit() } else { 0 }; lw.finish_dispatch(numthreads, hw, limit, split_tid) @@ -717,12 +730,28 @@ fn store_registers(lw: &mut Lw, res: super::shader::RawUav) { /// The compute entry's fixed registers (the HLSL compute mode's prologue): group ids /// after the user SGPRs, TG_SIZE, SCC = 0, EXEC = the wave's threads, v0..v2 = thread id. -pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) { +/// Returns whether this group runs: a dispatch folded into Y (`recomp::IO_GROUP_LIMIT` in `io` +/// not 0, the console's group count in X) takes its group in X from both ids, and the groups +/// past that count do not run. +pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) -> Value { + let io = lw.init.io.expect("the I/O buffer"); + let o = lw.c((crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32); + let limit = lw.s.raw_load(io, o, 1)[0]; + let (gx, gy) = (lw.s.group_id(0), lw.s.group_id(1)); + let k = lw.c(crate::gpu::recomp::FOLD_X); + let rows = lw.mul(gy, k); + let flat = lw.add(gx, rows); + let folded = lw.cmpc(Pred::Ne, limit, 0); + let zero = lw.c(0); + let ids = [lw.sel(folded, flat, gx), lw.sel(folded, zero, gy)]; + let inside = lw.cmp(Pred::ULt, flat, limit); + let t = lw.b(true); + let runs = lw.sel(folded, inside, t); let mut sgpr = HashMap::new(); let mut next = cs.user_sgprs; for k in 0..3 { if cs.tgid[k] { - let g = lw.s.group_id(k as u32); + let g = if k < 2 { ids[k] } else { lw.s.group_id(2) }; sgpr.insert(next, g); next += 1; } @@ -738,7 +767,6 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) let v = lw.or(w, i); sgpr.insert(next, v); } - let zero = lw.c(0); sgpr.insert(VAR_SCC, zero); let (lo, hi) = entry_exec(lw, total, tid); sgpr.insert(126, lo); @@ -750,6 +778,7 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) } } lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); + runs } /// The mesh entry's registers (the HLSL mesh mode's prologue): SGPRs from `io` with the diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index c8dc7e228b..3b54d0dbb6 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5062,12 +5062,20 @@ impl Em { h.push_str(" lane_id = WaveGetLaneIndex();\n"); } load_sgprs(&mut h); + // a folded dispatch (`IO_GROUP_LIMIT`): the console's group in X, the groups + // past its count left out (the whole group returns) + let _ = writeln!( + h, + " uint3 xcl_gid = gid;\n {{\n uint xcl_gl = io.Load({}u);\n if (xcl_gl != 0u) {{\n uint xcl_f = gid.x + gid.y * {}u;\n if (xcl_f >= xcl_gl) return;\n xcl_gid = uint3(xcl_f, 0u, gid.z);\n }}\n }}", + super::IO_GROUP_LIMIT * 4, + super::FOLD_X + ); // system SGPRs after the user data: enabled group ids, then TG_SIZE let mut next = cs.user_sgprs as u64; for (k, c) in ["x", "y", "z"].iter().enumerate() { if cs.tgid[k] { if sg.contains(&next) { - let _ = writeln!(h, " {} = gid.{c};", sname(next).unwrap()); + let _ = writeln!(h, " {} = xcl_gid.{c};", sname(next).unwrap()); } next += 1; } diff --git a/crates/xcl/src/gpu/recomp/lower.rs b/crates/xcl/src/gpu/recomp/lower.rs index 0d86a1607e..54df58357a 100644 --- a/crates/xcl/src/gpu/recomp/lower.rs +++ b/crates/xcl/src/gpu/recomp/lower.rs @@ -1304,12 +1304,15 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s prev = c; } } - // compute: every lane that runs is in EXEC, and nothing is stored at the end – the skip and - // store blocks are left unreachable (a bare `ret`) + // compute: every lane that runs is in EXEC, and nothing is stored at the end – the store + // blocks are left unreachable, and the skip block (a bare `ret`) takes the groups past a + // folded dispatch's count if kernel { preds[skip] = vec![0]; preds[sstore] = vec![exit]; preds[vstore] = vec![exit, sstore]; + } else if matches!(stage, Stage::Compute(_)) { + preds[skip] = vec![0]; } preds[exit] = kernel.then_some(skip).into_iter().chain(ends.iter().map(|&b| tail[b])).collect(); for i in 0..count { @@ -1402,11 +1405,25 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s } Stage::Compute(cs) => { let (flat, tid) = l.ir.compute_ids(cs.threads); + // a dispatch folded into Y (`IO_GROUP_LIMIT` not 0: the console's group count in X): + // the group in X from both ids, the groups past the count leave at once + let a = l.ir.int(super::IO_GROUP_LIMIT as u32); + let limit = l.ir.io_load(a); + let (gx, gy) = (l.ir.group_id(0), l.ir.group_id(1)); + let k = l.ir.int(super::FOLD_X); + let rows = l.ir.bin(Bin::Mul, gy, k); + let group = l.ir.bin(Bin::Add, gx, rows); + let z = l.ir.int(0); + let folded = l.ir.icmp(Cmp::Ne, limit, z); + let ids = [l.ir.select(folded, group, gx), l.ir.select(folded, z, gy)]; + let inside = l.ir.icmp(Cmp::Ult, group, limit); + let t = l.ir.boolean(true); + let runs = l.ir.select(folded, inside, t); // system SGPRs after the user data: the enabled group ids, then TG_SIZE let mut next = cs.user_sgprs as u8; for k in 0..3 { if cs.tgid[k as usize] { - let g = l.ir.group_id(k); + let g = if k < 2 { ids[k as usize] } else { l.ir.group_id(k) }; l.write_num(0, next, g); next += 1; } @@ -1436,7 +1453,7 @@ fn lower_with(insts: &[Decoded], stage: Stage, wave64: bool, mut ir: I, s // every lane that runs is in EXEC let t = l.ir.boolean(true); l.write_bit(0, EXEC, t); - l.ir.br(blk(0)); + l.ir.br_if(runs, blk(0), skip); l.ir.at(skip); l.ssa.seal(&mut l.ir, skip); l.ir.ret(); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 680ae9e9c3..94f41e1ddc 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -205,6 +205,14 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21; pub const IO_GS_PRIMS: usize = 110; pub const IO_GS_VERTICES: usize = 111; pub const IO_UMA_BASE_HI: usize = 112; +/// io slot (trap-temp range) of a compute dispatch whose groups were folded: the console's group +/// count in X, 0 when not folded. The console takes up to 2^32 - 1 groups a dimension, D3D12 +/// 65 535 - a dispatch of more in X (and 1 in Y) runs as 65 535 x ceil(n / 65 535) groups, and +/// the translated program takes `gid.x + gid.y * 65 535` as its group in X, leaving out the +/// groups at or past `n`. +pub const IO_GROUP_LIMIT: usize = 113; +/// Groups a folded dispatch has in X. +pub const FOLD_X: u32 = 65_535; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 89846f9c28..a9fa30d958 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -498,6 +498,62 @@ unsafe fn emit_uav_barrier(list: &ID3D12GraphicsCommandList, res: Option<&ID3D12 std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.UAV).pResource); } +unsafe fn emit_uav_and_transition(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = [ + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }, + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }, + ]; + list.ResourceBarrier(&b); + std::mem::ManuallyDrop::drop(&mut (*b[1].Anonymous.Transition).pResource); +} + +unsafe fn emit_transition_and_uav(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { + let mut b = [ + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(res.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: before, + StateAfter: after, + }), + }, + }, + D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }, + ]; + list.ResourceBarrier(&b); + std::mem::ManuallyDrop::drop(&mut (*b[0].Anonymous.Transition).pResource); +} + unsafe fn emit_transition(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) { let mut b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, @@ -791,23 +847,40 @@ void main(uint tid : SV_DispatchThreadID) { /// 0 x 0 x 0 when they are more than `io` dword 1 in all, or a count alone is (`MOST_GROUPS`). The /// counts come from memory the GPU wrote; where that is not what the title meant they can be /// anything, and billions of groups hold the GPU for seconds or until Windows resets the driver. -/// A count over D3D12's 65 535 that is not one of those is cut to it. +/// More than 65 535 groups in X with 1 in Y are folded into `65 535 x ceil(x / 65 535)` with the +/// console count written to `u4` at `io` dword 3 (`IO_GROUP_LIMIT * 4`, when non-zero); any other +/// count over D3D12's 65 535 is cut to it. pub(super) const GUARD_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); RWByteAddressBuffer src : register(u2); RWByteAddressBuffer dst : register(u3); +RWByteAddressBuffer lim : register(u4); [numthreads(1, 1, 1)] void main() { - uint at = io.Load(0), most = io.Load(4), to = io.Load(8); + uint at = io.Load(0), most = io.Load(4), to = io.Load(8), lim_at = io.Load(12); uint3 g = src.Load3(at); uint3 out_g = uint3(0u, 0u, 0u); + uint limit = 0u; if (g.x != 0u && g.y != 0u && g.z != 0u && all(g <= most)) { if (g.x <= most / g.y) { if (g.x * g.y <= most / g.z) { - out_g = min(g, 65535u.xxx); + if (g.x > 65535u && g.y == 1u && g.z <= 65535u) { + uint rows = (g.x - 1u) / 65535u + 1u; + if (rows <= 65535u) { + out_g = uint3(65535u, rows, g.z); + limit = g.x; + } else { + out_g = min(g, 65535u.xxx); + } + } else { + out_g = min(g, 65535u.xxx); + } } } } dst.Store3(to, out_g); + if (lim_at != 0u) { + lim.Store(lim_at, limit); + } } "#; @@ -856,7 +929,7 @@ fn validate_scale_args_layout(max: u32, stride: u32, mesh_offset: u32) -> Result unsafe fn guard_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { static CACHE: Mutex>> = Mutex::new(None); - args_pipeline(dev, GUARD_ARGS_HLSL, GUARD_ARGS_DRED_LABEL, false, &CACHE) + args_pipeline(dev, GUARD_ARGS_HLSL, GUARD_ARGS_DRED_LABEL, true, &CACHE) } /// `XCL_INDIRECT_GUARD=0`: indirect dispatches run the groups memory holds, whatever they are. @@ -865,10 +938,11 @@ fn indirect_guard() -> bool { *ON.get_or_init(|| std::env::var("XCL_INDIRECT_GUARD").map_or(true, |v| v.trim() != "0")) } -/// The arguments of one indirect dispatch at UMA address `src`, checked (`GUARD_ARGS_HLSL`): the -/// scratch block (INDIRECT_ARGUMENT until the caller puts it back to COMMON) and their offset. The -/// list's compute root signature and pipeline are the guard's after this. -unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize) -> Result<(ID3D12Resource, u64), String> { +/// The arguments of one indirect dispatch at UMA address `src`, checked and >65 535 X-folded +/// (`GUARD_ARGS_HLSL`): writes the guarded/folded `(x, y, z)` to scratch (`INDIRECT_ARGUMENT`) +/// and writes `IO_GROUP_LIMIT` into `dispatch_io_va`. The list's compute root signature and +/// pipeline are the guard's after this. +unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, dispatch_io_va: u64) -> Result<(ID3D12Resource, u64), String> { if super::list_x::tracked_list_type(this) == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) { return Err("command bundles cannot record indirect argument barriers".into()); } @@ -879,21 +953,23 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; let (src_base, src_off) = align_root_uav(src_va)?; let (dst, dst_off) = scratch_args(this, &dev, 256)?; - let consts: Vec = [src_off, most_groups(), 0].iter().flat_map(|w| w.to_le_bytes()).collect(); - let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); + let lim_off = (crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32; + let consts = [src_off, most_groups(), 0, lim_off]; + let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; // the title's writes of the arguments before this (`fresh_indirect_arguments`) let prev_state = with(this, |s| s.scratch_state); - emit_uav_barrier(list, None); - emit_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); list.SetComputeRootUnorderedAccessView(0, consts_va); list.SetComputeRootUnorderedAccessView(1, src_base); list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress() + dst_off); + list.SetComputeRootUnorderedAccessView(3, dispatch_io_va); list.Dispatch(1, 1, 1); - emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + // Transition scratch to INDIRECT_ARGUMENT and flush the `IO_GROUP_LIMIT` store in `dispatch_io_va`. + emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); with(this, |s| { s.scratch_state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; s.pc_abi_cs = AbiBound::default(); @@ -1048,8 +1124,7 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman let cnt_base = count_bound.map_or(consts_va, |(base, _)| base); // the title's writes of the arguments before this (`fresh_indirect_arguments`) let prev_state = with(this, |s| s.scratch_state); - emit_uav_barrier(list, None); - emit_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); list.SetComputeRootUnorderedAccessView(0, consts_va); @@ -1314,13 +1389,22 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us }; // (before the dispatch's own root signature and pipeline are bound) let mut guarded = None; + let mut preset_io = None; if compute && max == 1 && indirect_guard() && signature_dispatches(sig) { if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { - match guard_dispatch_args(this, list, p) { - Ok(g) => { - guarded = Some(g); - if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { - list.SetPipelineState(real); + // Allocate a dedicated `io` buffer for this dispatch so `guard_dispatch_args` can + // write `IO_GROUP_LIMIT` on the GPU without racing against cached `io` slots. + match alloc_fresh_compute_io(this, pso) { + Ok(io_va) => { + preset_io = Some(io_va); + match guard_dispatch_args(this, list, p, io_va) { + Ok(g) => guarded = Some(g), + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect's group counts are not checked: {e}"); + } + } } } Err(e) => { @@ -1333,7 +1417,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } let (args, args_off) = guarded.as_ref().map_or((args, args_off), |(b, o)| (b.as_raw() as usize, *o)); - match bind_abi(this, list, pso, gfx) { + match bind_abi(this, list, pso, gfx, 0, preset_io) { Ok(()) => { if let Some(whole) = whole_pso { list.SetPipelineState(&whole); @@ -1349,6 +1433,11 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us super::culprit::after_dispatch(list, mark); } Err(e) => { + if guarded.is_some() { + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + } count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED }); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1600,7 +1689,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option if super::present::trace_frame() { trace_ui_draw(this, pso); } - match bind_abi(this, &list, pso, true) { + match bind_abi(this, &list, pso, true, 0, None) { Ok(()) => { count(DRAWS); Some(list) @@ -2014,17 +2103,77 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis if super::present::trace_frame() { trace_fullscreen(this, pso, [x, y, z]); } - bind_abi(this, list, pso, false)?; + // more groups in X than D3D12 takes: folded (`recomp::IO_GROUP_LIMIT`) + let (limit, [x, y, z]) = fold(x, y, z); + bind_abi(this, list, pso, false, limit, None)?; let mark = super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [x, y, z]); let r = super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]); super::culprit::after_dispatch(list, mark); r } +/// A dispatch of `x` x `y` x `z` groups as D3D12 takes it: (the count for +/// `recomp::IO_GROUP_LIMIT` - 0: not folded -, the groups to dispatch). More than 65 535 in X +/// with 1 in Y is folded into Y; any other count past 65 535 is clamped (logged once). +pub(super) fn fold(x: u32, y: u32, z: u32) -> (u32, [u32; 3]) { + use crate::gpu::recomp::FOLD_X; + if x <= FOLD_X && y <= 65_535 && z <= 65_535 { + return (0, [x, y, z]); + } + if y == 1 && z <= 65_535 && x.div_ceil(FOLD_X) <= 65_535 { + return (x, [FOLD_X, x.div_ceil(FOLD_X), z]); + } + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: a dispatch of {x}x{y}x{z} groups cannot be folded – clamped to 65535 a dimension"); + } + (0, [x.min(65_535), y.min(65_535), z.min(65_535)]) +} + +/// Allocate a dedicated compute `io` buffer in UMA for an indirect dispatch whose `IO_GROUP_LIMIT` +/// slot will be written on the GPU by `guard_dispatch_args`. +unsafe fn alloc_fresh_compute_io(this: *mut c_void, pso: usize) -> Result { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let real = super::pso_async::resolve_wait(pso); + let user_sgprs = super::real::pso_user_sgprs(real); + with(this, |s| -> Result { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + let w = super::real::uma_window_vas(); + if w.is_empty() { + return Err("unified memory is not open on the GPU".into()); + } + s.uma_windows = Some(w); + } + let windows = s.uma_windows.as_deref().unwrap(); + let first = windows[0]; + let layout = s.layout.as_deref(); + let args = s.args.as_slice(); + let inline = layout.map_or(0, |l| console_list::inline_for(l, user_sgprs) as usize).min(args.len()); + let tail = &args[inline..]; + let table_p = s.arena.take(u, tail.len().max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + if !tail.is_empty() { + std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); + } + let table_at = table_p as u64; + let mut io = match layout { + Some(l) => console_list::with_heaps(l, user_sgprs, console_list::user_data_for(l, user_sgprs, args, table_at), s.heaps), + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + io[crate::gpu::recomp::IO_GROUP_LIMIT] = 0; + let io_bytes = io.len() * 4; + let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(io.as_ptr().cast::(), io_p, io_bytes); + Ok(uma_va_in(u, windows, io_p as usize).unwrap_or(first)) + }) +} + /// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept /// arguments the console's way – compute or graphics) and the argument table in unified -/// memory, u1 res, u2… the memory windows; then the pipeline. -unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { +/// memory, u1 res, u2… the memory windows; then the pipeline. `group_limit`: a folded +/// dispatch's group count in X (`recomp::IO_GROUP_LIMIT`), 0 for any other. +unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, group_limit: u32, preset_io_va: Option) -> Result<(), String> { super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; // a pipeline still being built in the background is waited for @@ -2063,40 +2212,49 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi } let res_va = s.dummy_res_va; - let cached_io = if gfx { - s.io_cache_gfx.filter(|&(gen, _)| gen == s.args_gen_gfx).map(|(_, va)| va) - } else { - s.io_cache_cs.filter(|&(gen, sgprs, _)| gen == s.args_gen_cs && sgprs == user_sgprs).map(|(_, _, va)| va) - }; - let io_va = if let Some(va) = cached_io { + let io_va = if let Some(va) = preset_io_va { va } else { - let (layout, args) = if gfx { (s.layout_gfx.as_deref(), s.args_gfx.as_slice()) } else { (s.layout.as_deref(), s.args.as_slice()) }; - let inline = layout.map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); - let tail = &args[inline..]; - // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) - let table_p = s.arena.take(u, tail.len().max(16), 256, &mut s.uma).ok_or("unified memory is full")?; - if !tail.is_empty() { - std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); - } - let table_at = table_p as u64; - let mut io = match layout { - Some(l) if gfx => console_list::with_heaps(l, None, console_list::user_data_gfx(l, args, table_at), s.heaps), - Some(l) => console_list::with_heaps(l, user_sgprs, console_list::user_data_for(l, user_sgprs, args, table_at), s.heaps), - None => vec![table_at as u32, (table_at >> 32) as u32], + let cached_io = if group_limit != 0 { + None + } else if gfx { + s.io_cache_gfx.filter(|&(gen, _)| gen == s.args_gen_gfx).map(|(_, va)| va) + } else { + s.io_cache_cs.filter(|&(gen, sgprs, _)| gen == s.args_gen_cs && sgprs == user_sgprs).map(|(_, _, va)| va) }; - io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); - io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; - let io_bytes = io.len() * 4; - let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(io.as_ptr().cast::(), io_p, io_bytes); - let va = uma_va_in(u, windows, io_p as usize).unwrap_or(first); - if gfx { - s.io_cache_gfx = Some((s.args_gen_gfx, va)); + if let Some(va) = cached_io { + va } else { - s.io_cache_cs = Some((s.args_gen_cs, user_sgprs, va)); + let (layout, args) = if gfx { (s.layout_gfx.as_deref(), s.args_gfx.as_slice()) } else { (s.layout.as_deref(), s.args.as_slice()) }; + let inline = layout.map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); + let tail = &args[inline..]; + // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) + let table_p = s.arena.take(u, tail.len().max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + if !tail.is_empty() { + std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); + } + let table_at = table_p as u64; + let mut io = match layout { + Some(l) if gfx => console_list::with_heaps(l, None, console_list::user_data_gfx(l, args, table_at), s.heaps), + Some(l) => console_list::with_heaps(l, user_sgprs, console_list::user_data_for(l, user_sgprs, args, table_at), s.heaps), + None => vec![table_at as u32, (table_at >> 32) as u32], + }; + io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + io[crate::gpu::recomp::IO_GROUP_LIMIT] = group_limit; + let io_bytes = io.len() * 4; + let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(io.as_ptr().cast::(), io_p, io_bytes); + let va = uma_va_in(u, windows, io_p as usize).unwrap_or(first); + if group_limit == 0 { + if gfx { + s.io_cache_gfx = Some((s.args_gen_gfx, va)); + } else { + s.io_cache_cs = Some((s.args_gen_cs, user_sgprs, va)); + } + } + va } - va }; let views = [io_va, res_va, win_vas[0], win_vas[1], win_vas[2], win_vas[3]]; @@ -2992,7 +3150,7 @@ void main(uint t : SV_GroupIndex) { let cases: [([u32; 3], [u32; 3]); 10] = [ ([1, 1, 1], [1, 1, 1]), ([2560 / 8, 1440 / 4, 1], [320, 360, 1]), - ([115_200, 1, 1], [65_535, 1, 1]), + ([115_200, 1, 1], [65_535, 2, 1]), ([0, 5, 5], [0, 0, 0]), ([0xFF00_0000, 0xE3, 0xFF7F_0000], [0, 0, 0]), ([65_535, 65_535, 65_535], [0, 0, 0]), @@ -3415,11 +3573,11 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) std::ptr::write_bytes(src_p, 0, 128); std::ptr::write_bytes(dst_p, 0xCC, 128); - // Guard pass reading from 12-byte offset (dword 3, not 16-byte aligned). + // Guard pass reading 115 200 x 1 x 1 from 12-byte offset (not 16-byte aligned), folding into 65 535 x 2 x 1 and writing IO_GROUP_LIMIT. let (guard_src_base, guard_src_off) = align_root_uav(src_buf.GetGPUVirtualAddress() + 12).unwrap(); assert_eq!(guard_src_off, 12); - std::ptr::copy_nonoverlapping([70_000u32, 2, 1].as_ptr(), src_p.add(3), 3); - std::ptr::copy_nonoverlapping([guard_src_off, MOST_GROUPS, 0].as_ptr(), io_p, 3); + std::ptr::copy_nonoverlapping([115_200u32, 1, 1].as_ptr(), src_p.add(3), 3); + std::ptr::copy_nonoverlapping([guard_src_off, MOST_GROUPS, 0, 16].as_ptr(), io_p, 4); // Scale pass reading 2 commands at 12-byte offset (stride 16, mesh_offset 4) with no count buffer (u4 bound to io). let (scale_src_base, scale_src_off) = align_root_uav(src_buf.GetGPUVirtualAddress() + 64 + 12).unwrap(); @@ -3437,6 +3595,7 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); list.SetComputeRootUnorderedAccessView(1, guard_src_base); list.SetComputeRootUnorderedAccessView(2, dst_buf.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView(3, dst_buf.GetGPUVirtualAddress()); list.Dispatch(1, 1, 1); list.SetComputeRootSignature(&scale_rs); @@ -3453,7 +3612,7 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) queue.Signal(&fence, 1).unwrap(); crate::gpu::fence::wait(&fence, 1, &dev, None, 10_000).unwrap(); - assert_eq!(std::slice::from_raw_parts(dst_p, 3), &[65_535, 2, 1]); + assert_eq!(std::slice::from_raw_parts(dst_p, 5), &[65_535, 2, 1, 0xCCCC_CCCC, 115_200]); assert_eq!(std::slice::from_raw_parts(dst_p.add(64), 8), &[11, 10, 1, 1, 22, 6, 1, 1]); assert_eq!(std::slice::from_raw_parts(dst_p.add(72), 8), &[11, 20, 1, 1, 22, 12, 1, 1]); @@ -3463,6 +3622,21 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) } } + #[test] + fn dispatches_past_the_d3d12_limit_are_folded_or_clamped() { + assert_eq!(fold(64, 2, 1), (0, [64, 2, 1])); + assert_eq!(fold(65_535, 1, 1), (0, [65_535, 1, 1])); + assert_eq!(fold(72_512, 1, 1), (72_512, [65_535, 2, 1])); + assert_eq!(fold(115_200, 1, 1), (115_200, [65_535, 2, 1])); + assert_eq!(fold(131_071, 1, 3), (131_071, [65_535, 3, 3])); + assert_eq!(fold(70_000, 2, 1), (0, [65_535, 2, 1])); + for n in [65_536u32, 72_512, 75_072, 115_200, 200_000] { + let (limit, [x, y, _]) = fold(n, 1, 1); + assert_eq!(limit, n); + assert!(x * y >= n && x * y - n < x, "{n}: {x}x{y}"); + } + } + #[test] fn abi_binding_state_diff_only_rebinds_changed_slots_and_resets_on_rs_change() { let mut bound = AbiBound::default(); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 93db4a9fc1..e5969e4615 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -968,6 +968,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + // more groups in X than D3D12 takes: folded (`recomp::IO_GROUP_LIMIT`) + let (limit, [x, y, z]) = super::bind::fold(x, y, z); + io[crate::gpu::recomp::IO_GROUP_LIMIT] = limit; let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?; let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?; // the pipeline's own root signature when it has static samplers From 3b6d008413bbade5f31f56f9961aabae8dd20151 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:53:58 +0100 Subject: [PATCH 072/258] D3D12.X: ping-pong indirect scratch and dedup arg-order barriers Consecutive guarded or two-pass ExecuteIndirect passes previously reused the same single indirect scratch buffer, forcing serialized INDIRECT_ARGUMENT <-> UNORDERED_ACCESS state transitions and WAR stalls on the GPU. Consecutive unguarded indirect graphics draws also repeated COMMON <-> INDIRECT_ARGUMENT transitions on every ExecuteIndirect call even when no compute or two-pass write intervened. Add two ping-pong indirect scratch slots in bind::State so adjacent argument-pass dispatches alternate buffers (falling back to the alternate slot under SCRATCH_CAP), track an arg_order_clean flag cleared on compute/two-pass writes so redundant fresh_indirect_arguments barriers are skipped between adjacent unguarded indirect draws, and stack-allocate the 36-byte constants payload in make_scaled_args_buffer. Verified with cargo check -p xcl --tests (exit 0, 0 new warnings), including regression unit tests for ping-pong slot alternation, cap fallback, and arg_order_clean invalidation. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 153 ++++++++++++++++++++++-------- 1 file changed, 115 insertions(+), 38 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index a9fa30d958..cfab7708ee 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -72,6 +72,15 @@ fn uma_va_in(u: &crate::gpu::uma::Uma, windows: &[u64], p: usize) -> Option Some(*windows.get(k)? + (p - u.window(k).0) as u64) } +#[derive(Default)] +struct ScratchSlot { + buf: Option<(ID3D12Resource, u64, usize)>, + used: u64, + /// D3D12 state on this list (`COMMON` initially, kept in `INDIRECT_ARGUMENT` between uses; + /// buffers decay to `COMMON` after `ExecuteCommandLists`). + state: D3D12_RESOURCE_STATES, +} + #[derive(Default)] struct State { layout: Option>, @@ -96,15 +105,16 @@ struct State { res_retired: Vec<(ID3D12Resource, u64, usize)>, /// the recording used the shared record buffer (`shared_record_buffer`) shared_records: bool, - /// rewritten indirect arguments (`scratch_args`): the block, its bytes in use, and the - /// bytes of blocks this recording took - scratch: Option<(ID3D12Resource, u64, usize)>, - scratch_used: u64, + /// rewritten indirect arguments (`scratch_args`): two ping-pong scratch slots so consecutive + /// guarded/two-pass ExecuteIndirects avoid false WAR transition stalls on the same buffer, + /// plus total bytes of blocks this recording took (`scratch_taken`). + scratch: [ScratchSlot; 2], + scratch_next: usize, scratch_taken: u64, - /// D3D12 state of the current `scratch` block on this list (`COMMON` initially, kept in - /// `INDIRECT_ARGUMENT` between consecutive argument-rewrite passes; buffers decay to `COMMON` - /// after `ExecuteCommandLists`) - scratch_state: D3D12_RESOURCE_STATES, + /// true after an `INDIRECT_ARGUMENT` transition has ordered prior writes on this list and + /// no compute/mesh dispatch has run since (skips redundant `fresh_indirect_arguments` barriers + /// across runs of consecutive indirect graphics draws). + arg_order_clean: bool, /// cached UMA window GPU VAs for this recording (avoids locking `UMA_BUFFER` every draw) uma_windows: Option>, /// reusable zeroed 256-byte `u1` (`res`) slot in this recording's UMA arena @@ -204,8 +214,10 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.heaps = [0; 2]; s.shared_records = false; // (the scratch blocks are in `res_retired` already) - (s.scratch, s.scratch_used, s.scratch_taken) = (None, 0, 0); - s.scratch_state = D3D12_RESOURCE_STATE_COMMON; + s.scratch = Default::default(); + s.scratch_next = 0; + s.scratch_taken = 0; + s.arg_order_clean = false; s.uma_windows = None; s.dummy_res_va = 0; s.pc_abi_gfx = AbiBound::default(); @@ -268,8 +280,10 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.rs_cs = rs_cs; s.pso = pso; s.heaps = heaps; - (s.scratch, s.scratch_used, s.scratch_taken) = (None, 0, 0); - s.scratch_state = D3D12_RESOURCE_STATE_COMMON; + s.scratch = Default::default(); + s.scratch_next = 0; + s.scratch_taken = 0; + s.arg_order_clean = false; s.uma_windows = None; s.dummy_res_va = 0; s.pc_abi_gfx = AbiBound::default(); @@ -952,14 +966,13 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis super::real::uma_window_buffer(src, 12).ok_or("the indirect arguments are not in one memory window")?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; let (src_base, src_off) = align_root_uav(src_va)?; - let (dst, dst_off) = scratch_args(this, &dev, 256)?; + let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, 256)?; let lim_off = (crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32; let consts = [src_off, most_groups(), 0, lim_off]; let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; // the title's writes of the arguments before this (`fresh_indirect_arguments`) - let prev_state = with(this, |s| s.scratch_state); emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); @@ -971,8 +984,9 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis // Transition scratch to INDIRECT_ARGUMENT and flush the `IO_GROUP_LIMIT` store in `dispatch_io_va`. emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); with(this, |s| { - s.scratch_state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.scratch[slot].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; }); Ok((dst, dst_off)) } @@ -1043,15 +1057,17 @@ unsafe fn args_pipeline(dev: &ID3D12Device, hlsl: &str, label: &str, with_count: Ok((rs, pso)) } -/// `bytes` of this recording's scratch blocks (COMMON between uses): the block and the offset. -/// Past `SCRATCH_CAP` a recording gets no more. -unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64), String> { +/// `bytes` of this recording's scratch slot `slot` (COMMON initially, kept in INDIRECT_ARGUMENT +/// between uses): the block, byte offset, and its prior D3D12 state. Past `SCRATCH_CAP` across +/// all slots a recording gets no more. +unsafe fn scratch_args_in(this: *mut c_void, dev: &ID3D12Device, bytes: u64, slot: usize) -> Result<(ID3D12Resource, u64, D3D12_RESOURCE_STATES), String> { let bytes = bytes.next_multiple_of(256); if let Some(r) = with(this, |s| { - let (b, cap, _) = s.scratch.as_ref()?; - (s.scratch_used + bytes <= *cap).then(|| { - s.scratch_used += bytes; - (b.clone(), s.scratch_used - bytes) + let sl = &mut s.scratch[slot]; + let (b, cap, _) = sl.buf.as_ref()?; + (sl.used + bytes <= *cap).then(|| { + sl.used += bytes; + (b.clone(), sl.used - bytes, sl.state) }) }) { return Ok(r); @@ -1073,12 +1089,51 @@ unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Res let b = block.0.clone(); with(this, |s| { s.scratch_taken += block.1; - s.scratch_used = bytes; - s.scratch = Some(block.clone()); - s.scratch_state = D3D12_RESOURCE_STATE_COMMON; + s.scratch[slot] = ScratchSlot { + buf: Some(block.clone()), + used: bytes, + state: D3D12_RESOURCE_STATE_COMMON, + }; s.res_retired.push(block); }); - Ok((b, 0)) + Ok((b, 0, D3D12_RESOURCE_STATE_COMMON)) +} + +#[cfg(test)] +unsafe fn scratch_args(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64), String> { + let (b, off, _) = scratch_args_in(this, dev, bytes, 0)?; + Ok((b, off)) +} + +/// Choose between the two ping-pong scratch slots (`preferred` vs `preferred ^ 1`): prefer +/// alternating so back-to-back indirect passes avoid WAR stalls on the same buffer, falling +/// back to the other slot when `preferred` would require a new block past `SCRATCH_CAP`. +fn pick_pingpong_slot(preferred: usize, fits: [bool; 2], can_alloc: bool) -> usize { + if fits[preferred] || can_alloc { + preferred + } else if fits[preferred ^ 1] { + preferred ^ 1 + } else { + preferred + } +} + +unsafe fn scratch_args_pingpong(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64, usize, D3D12_RESOURCE_STATES), String> { + let aligned = bytes.next_multiple_of(256); + let size = aligned.max(SCRATCH_BLOCK); + let slot = with(this, |s| { + let preferred = s.scratch_next; + let fits = [ + s.scratch[0].buf.as_ref().is_some_and(|(_, cap, _)| s.scratch[0].used + aligned <= *cap), + s.scratch[1].buf.as_ref().is_some_and(|(_, cap, _)| s.scratch[1].used + aligned <= *cap), + ]; + let can_alloc = SCRATCH_CAP.saturating_sub(s.scratch_taken) >= size; + let chosen = pick_pingpong_slot(preferred, fits, can_alloc); + s.scratch_next = chosen ^ 1; + chosen + }); + let (buf, off, prev_state) = scratch_args_in(this, dev, aligned, slot)?; + Ok((buf, off, slot, prev_state)) } /// The arguments of `max` commands at UMA address `src`, rewritten for the two passes @@ -1111,19 +1166,15 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman } None => None, }; - let (dst, dst_off) = scratch_args(this, &dev, commands.saturating_mul(2))?; - let consts: Vec = [max, stride, mesh_offset, split, cap, src_off, 0, count_bound.is_some() as u32, count_bound.map_or(0, |(_, off)| off)] - .iter() - .flat_map(|w| w.to_le_bytes()) - .collect(); - let p = with(this, |s| s.arena.take(u, consts.len(), 256, &mut s.uma)).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(consts.as_ptr(), p, consts.len()); + let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, commands.saturating_mul(2))?; + let consts = [max, stride, mesh_offset, split, cap, src_off, 0, count_bound.is_some() as u32, count_bound.map_or(0, |(_, off)| off)]; + let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; // Bind u4 unconditionally (to `consts_va` when no count buffer is supplied) because // `SCALE_ARGS_HLSL` statically references `cnt : register(u4)`. let cnt_base = count_bound.map_or(consts_va, |(base, _)| base); // the title's writes of the arguments before this (`fresh_indirect_arguments`) - let prev_state = with(this, |s| s.scratch_state); emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); list.SetPipelineState(&pso); @@ -1134,8 +1185,9 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman list.Dispatch(max.div_ceil(64), 1, 1); emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); with(this, |s| { - s.scratch_state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.scratch[slot].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; }); Ok((dst, dst_off)) } @@ -1186,6 +1238,7 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: pc_dm(this, n * tp.mesh_groups_per_record, 1, 1); super::culprit::after_dispatch(list, m2); emit_uav_barrier(list, Some(&res_buf)); + with(this, |s| s.arg_order_clean = false); Ok(()) })(); match run { @@ -1279,6 +1332,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us super::culprit::after_dispatch(list, mark); emit_uav_barrier(list, Some(&res_buf)); } + with(this, |s| s.arg_order_clean = false); Ok(()) })(); match run { @@ -1431,6 +1485,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) } super::culprit::after_dispatch(list, mark); + if compute { + with(this, |s| s.arg_order_clean = false); + } } Err(e) => { if guarded.is_some() { @@ -1465,11 +1522,15 @@ static ARGUMENT_ORDER: Mutex> = Mutex::new(None) /// INDIRECT_ARGUMENT before and back after. Only on a list XCL made (`list_x::on_create`) and /// not a bundle, which cannot hold barriers; its type comes from XCL's state, not a call to it. unsafe fn fresh_indirect_arguments(list: *mut c_void, op: impl FnOnce()) { + if with(list, |s| s.arg_order_clean) { + return op(); + } let tracked = super::list_x::tracked_list_type(list).is_some_and(|t| t != D3D12_COMMAND_LIST_TYPE_BUNDLE); let buffer = if tracked { ID3D12GraphicsCommandList::from_raw_borrowed(&list).and_then(|l| argument_order_buffer(l)) } else { None }; let Some(buffer) = buffer else { return op() }; let b = buffer.as_raw() as usize; super::list_x::transition(list, b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + with(list, |s| s.arg_order_clean = true); op(); super::list_x::transition(list, b, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COMMON); } @@ -2109,6 +2170,7 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis let mark = super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [x, y, z]); let r = super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]); super::culprit::after_dispatch(list, mark); + with(this, |s| s.arg_order_clean = false); r } @@ -3674,7 +3736,8 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) s.io_cache_gfx = Some((s.args_gen_gfx, 0x5555_0000)); s.pc_abi_gfx = AbiBound { rs: 0xAAAA, uavs: [1, 2, 3, 4, 5, 6] }; s.pc_abi_cs = AbiBound { rs: 0xBBBB, uavs: [7, 8, 9, 10, 11, 12] }; - s.scratch_state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.scratch[0].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.arg_order_clean = true; s.args_gen_gfx }); // Writing the exact same value leaves generation and cached io intact. @@ -3695,12 +3758,26 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) assert_eq!(s.pc_abi_gfx, AbiBound::default()); assert_eq!(s.pc_abi_cs, AbiBound::default()); }); - // reset resets scratch_state back to COMMON. + // reset resets scratch slots back to COMMON and clears arg_order_clean. reset(list, 0x7600_0200, 0); - with(list, |s| assert_eq!(s.scratch_state, D3D12_RESOURCE_STATE_COMMON)); + with(list, |s| { + assert_eq!(s.scratch[0].state, D3D12_RESOURCE_STATE_COMMON); + assert_eq!(s.scratch[1].state, D3D12_RESOURCE_STATE_COMMON); + assert!(!s.arg_order_clean); + }); forget(list); } + #[test] + fn pingpong_scratch_alternates_slots_and_falls_back_under_cap() { + assert_eq!(pick_pingpong_slot(0, [true, true], false), 0); + assert_eq!(pick_pingpong_slot(1, [true, true], false), 1); + assert_eq!(pick_pingpong_slot(1, [true, false], true), 1); + // Under SCRATCH_CAP (cannot allocate a new block for slot 1), fall back to slot 0 if it fits. + assert_eq!(pick_pingpong_slot(1, [true, false], false), 0); + assert_eq!(pick_pingpong_slot(0, [false, true], false), 1); + } + #[test] fn execute_indirect_with_zero_max_count_short_circuits() { let mut orig_vt = [0usize; 64]; From 1286a9486c184ba5d7ed9f2fdad7460557d1a98d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:42:55 +0100 Subject: [PATCH 073/258] D3D12.X: index dirty title textures by src range and single-read hash+detile refresh_once scanned every registered title texture on every submit with a dirty page (O(N log D) over 40k+ textures), and upload_all read each texture's backing memory serially on the submit thread to hash it and then read and copied it a second time inside subresources_of_all to detile it (#2390, #2395-#2397). 1. Maintain Table::by_src_small (<=256 KiB), by_src_large, and pending_res indices so dirty_and_pending merges adjacent dirty pages into spans and resolves hits in O(D log N + P) instead of scanning all active textures, with a focused unit test. 2. Combine title_bytes + content_hash + unchanged skip + detiling into hash_and_detile_all so each texture is read once and hashed/detiled in parallel when a batch reaches PARALLEL_BYTES. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 336 ++++++++++++++++---- 1 file changed, 274 insertions(+), 62 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index be9a745777..be7526f687 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -20,7 +20,7 @@ //! (`note_transitions`) and applied, in submission order, when the list is submitted //! (`submitted`) – per subresource once a transition names one. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; @@ -75,11 +75,22 @@ static PENDING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize: // raw COM pointers of the title's objects; uploads hold a reference while they run unsafe impl Send for Entry {} +/// Textures at or below this size are indexed in `Table::by_src_small` for bounded range queries +/// on dirty page runs; larger textures sit in `Table::by_src_large` so a single huge texture does +/// not widen small dirty-page range scans. +const SMALL_SRC_MAX: usize = 256 << 10; + struct Table { /// Active PC textures (newest at each range) → its place in the title's memory by_res: BTreeMap, /// Active `(va, PC texture)` → end address (`va + size`); entries with different `(va, end)` are disjoint by_va: BTreeMap<(usize, usize), usize>, + /// Active non-`gpu_written` textures with `size <= SMALL_SRC_MAX`, keyed by `(src, res) -> src + size` + by_src_small: BTreeMap<(usize, usize), usize>, + /// Active non-`gpu_written` textures with `size > SMALL_SRC_MAX`: `res -> (src, src + size)` + by_src_large: BTreeMap, + /// Active textures with `pending == true` + pending_res: BTreeSet, /// Older overlapped textures kept dormant until released or uncovered when a newer one is released shadowed: BTreeMap, /// Shadowed `(va, PC texture)` → end address (may overlap) @@ -94,6 +105,9 @@ impl Table { Table { by_res: BTreeMap::new(), by_va: BTreeMap::new(), + by_src_small: BTreeMap::new(), + by_src_large: BTreeMap::new(), + pending_res: BTreeSet::new(), shadowed: BTreeMap::new(), shadowed_by_va: BTreeMap::new(), max_shadowed_size: 0, @@ -101,6 +115,101 @@ impl Table { } } + fn index_active(&mut self, res: usize, src: usize, size: usize, gpu_written: bool, pending: bool) { + if pending { + self.pending_res.insert(res); + } + if !gpu_written && size > 0 { + let end = src.saturating_add(size); + if size <= SMALL_SRC_MAX { + self.by_src_small.insert((src, res), end); + } else { + self.by_src_large.insert(res, (src, end)); + } + } + } + + fn unindex_active(&mut self, res: usize, src: usize) { + self.pending_res.remove(&res); + self.by_src_small.remove(&(src, res)); + self.by_src_large.remove(&res); + } + + fn mark_pending(&mut self, res: usize) -> bool { + if let Some(e) = self.by_res.get_mut(&res) { + if !e.gpu_written && !e.pending { + e.pending = true; + self.pending_res.insert(res); + return true; + } + } + false + } + + fn mark_gpu_written(&mut self, res: usize) -> bool { + if let Some(e) = self.by_res.get_mut(&res) { + if !e.gpu_written { + e.gpu_written = true; + let src = e.src; + self.by_src_small.remove(&(src, res)); + self.by_src_large.remove(&res); + return true; + } + return false; + } + if let Some(e) = self.shadowed.get_mut(&res) { + if !e.gpu_written { + e.gpu_written = true; + return true; + } + } + false + } + + /// Collect active textures that are pending or overlap any sorted dirty page in `dirty`, + /// clearing `pending` on returned entries and returning `(res_list, pending_cleared)`. + fn dirty_and_pending(&mut self, dirty: &[usize], page: usize) -> (Vec, usize) { + let mut hits: Vec = Vec::with_capacity(self.pending_res.len() + 16); + let mut cleared = 0usize; + for res in std::mem::take(&mut self.pending_res) { + if let Some(e) = self.by_res.get_mut(&res) { + if e.pending { + e.pending = false; + cleared += 1; + } + hits.push(res); + } + } + if !dirty.is_empty() && page > 0 { + // Merge contiguous dirty pages into spans so range lookups run once per span. + let mut i = 0; + while i < dirty.len() { + let lo = dirty[i]; + let mut hi = lo.saturating_add(page); + i += 1; + while i < dirty.len() && dirty[i] <= hi { + hi = hi.max(dirty[i].saturating_add(page)); + i += 1; + } + let q_lo = lo.saturating_sub(SMALL_SRC_MAX); + for (&(_, res), &end) in self.by_src_small.range((q_lo, 0)..(hi, 0)) { + if end > lo { + hits.push(res); + } + } + } + for (&res, &(src, end)) in &self.by_src_large { + let idx = dirty.partition_point(|&p| p.saturating_add(page) <= src); + if dirty.get(idx).is_some_and(|&p| p < end) { + hits.push(res); + } + } + } + hits.sort_unstable(); + hits.dedup(); + (hits, cleared) + } + fn has_active_overlap(&self, va: usize, end: usize) -> bool { if let Some((_, &oend)) = self.by_va.range(..(va, 0)).next_back() { if oend > va { @@ -146,6 +255,7 @@ impl Table { for (ova, ores, _) in self.active_overlaps(va, end) { self.by_va.remove(&(ova, ores)); if let Some(old) = self.by_res.remove(&ores) { + self.unindex_active(ores, old.src); if old.pending { pending_delta -= 1; } @@ -182,6 +292,7 @@ impl Table { let mut to_unmap = Vec::new(); if let Some(old) = self.by_res.remove(&res) { self.by_va.remove(&(old.va, res)); + self.unindex_active(res, old.src); if old.pending { pending_delta -= 1; } @@ -195,6 +306,7 @@ impl Table { } self.by_va.remove(&(ova, ores)); if let Some(mut old) = self.by_res.remove(&ores) { + self.unindex_active(ores, old.src); if old.pending { pending_delta -= 1; } @@ -224,8 +336,10 @@ impl Table { if entry.pending { pending_delta += 1; } + let (src, size, gpu_written, pending) = (entry.src, entry.tex.size() as usize, entry.gpu_written, entry.pending); self.by_va.insert((va, res), end); self.by_res.insert(res, entry); + self.index_active(res, src, size, gpu_written, pending); (pending_delta, to_unmap) } @@ -241,6 +355,7 @@ impl Table { } let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new()) }; self.by_va.remove(&(old.va, res)); + self.unindex_active(res, old.src); let mut pending_delta = if old.pending { -1 } else { 0 }; let va = old.va; let end = va.saturating_add(old.tex.size() as usize); @@ -267,8 +382,10 @@ impl Table { if e.pending { pending_delta += 1; } + let (src, size, gpu_written, pending) = (e.src, e.tex.size() as usize, e.gpu_written, e.pending); self.by_va.insert((sva, sres), send); self.by_res.insert(sres, e); + self.index_active(sres, src, size, gpu_written, pending); } } if self.shadowed.is_empty() { @@ -430,7 +547,19 @@ fn recheck_gpu_view_sources() { // (the shadowed textures too: one comes back when the texture over it goes) let mut g = TEXTURES.lock().unwrap(); let t = &mut *g; - for e in t.by_res.values_mut().chain(t.shadowed.values_mut()) { + let mut reindex: Vec<(usize, usize, usize, usize, bool, bool)> = Vec::new(); + for (&res, e) in t.by_res.iter_mut() { + let old_src = e.src; + if recheck_source(e) { + changed = true; + reindex.push((res, old_src, e.src, e.tex.size() as usize, e.gpu_written, e.pending)); + } + } + for (res, old_src, new_src, size, gpu_written, pending) in reindex { + t.unindex_active(res, old_src); + t.index_active(res, new_src, size, gpu_written, pending); + } + for e in t.shadowed.values_mut() { changed |= recheck_source(e); } drop(g); @@ -473,17 +602,15 @@ pub fn note_gpu_write(res: usize) { } } } - let mut marked = false; - { + let marked = { let mut t = TEXTURES.lock().unwrap(); - if let Some(e) = t.get_mut(res) { - if !e.gpu_written { - e.gpu_written = true; - GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); - marked = true; - } + if t.mark_gpu_written(res) { + GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); + true + } else { + false } - } + }; if marked { STREAM_RECHECK.lock().unwrap().remove(&res); } @@ -808,23 +935,13 @@ unsafe fn refresh_once(queue: *mut c_void) { let todo: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let mut t = TEXTURES.lock().unwrap(); - t.by_res - .iter_mut() - .filter(|(_, e)| { - if e.pending { - return true; - } - if e.gpu_written { - return false; - } - let i = dirty.partition_point(|&p| p + page as usize <= e.src); - dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) - }) - .filter_map(|(&res, e)| { - if e.pending { - e.pending = false; - PENDING.fetch_sub(1, Ordering::Relaxed); - } + let (hits, cleared) = t.dirty_and_pending(&dirty, page as usize); + if cleared > 0 { + PENDING.fetch_sub(cleared, Ordering::Relaxed); + } + hits.into_iter() + .filter_map(|res| { + let e = t.by_res.get(&res)?; let p = res as *mut c_void; ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone()))) }) @@ -1056,12 +1173,9 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) { let mut t = TEXTURES.lock().unwrap(); for res in changed { - if let Some(e) = t.by_res.get_mut(&res) { - if !e.gpu_written && !e.pending { - e.pending = true; - PENDING.fetch_add(1, Ordering::Relaxed); - queued += 1; - } + if t.mark_pending(res) { + PENDING.fetch_add(1, Ordering::Relaxed); + queued += 1; } } } @@ -1104,25 +1218,12 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { let mut picked = Vec::new(); let mut bytes = 0usize; let mut device = 0usize; + let skip_unchanged = unchanged_skip(); while let Some((_, (dev, _, tex, _))) = todo.peek() { if !batch_fits(picked.len(), bytes, device, *dev, tex.size() as usize) { break; } let (r, (dev, va, tex, states)) = todo.next().unwrap(); - // The same bytes as at this texture's last upload: nothing to do. The write watch is - // per page and a title writes next to its textures (and rewrites what it wrote): a - // retail title's video planes and UI targets went up again for every submit, ~25 MB - // a presented frame where ~3 MB had changed, and the submits waited here. - if unchanged_skip() { - let h = content_hash(&title_bytes(va, tex.size() as usize)); - if same_as_last_upload(r.as_raw() as usize, h) { - let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; - if n == 1 || (n.is_power_of_two() && n >= 1024) { - crate::xlog_info!("title textures: {n} uploads left out so far – the texture's memory held what it held at its last upload"); - } - continue; - } - } device = dev; bytes += tex.size() as usize; picked.push((r, va, tex, states)); @@ -1130,9 +1231,12 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { if picked.is_empty() { continue; } - let subs = subresources_of_all(&picked, bytes); + let prepared = hash_and_detile_all(&picked, bytes, skip_unchanged); let mut batch = Vec::with_capacity(picked.len()); - for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { + for ((r, va, _, states), subs) in picked.into_iter().zip(prepared) { + let Some(subs) = subs else { + continue; + }; if super::present::trace_frame() { note_content(va, &r, &subs); } @@ -1142,6 +1246,9 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } batch.push((r, subs, states)); } + if batch.is_empty() { + continue; + } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; let queue = match upload_queue(dev, device) { @@ -1417,16 +1524,59 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec { /// Batches of at least this many bytes are detiled on several threads (`subresources_of_all`) const PARALLEL_BYTES: usize = 1 << 20; -/// `subresources` of every texture of a batch (`bytes` of them), in order: on several threads -/// when the batch is big. They were read and detiled one after another in the title's own -/// submit – most of a retail game's render thread while it streamed textures the CPU writes. -unsafe fn subresources_of_all(picked: &[(ID3D12Resource, usize, Arc, Vec)], bytes: usize) -> Vec> { - let picked: Vec<(usize, &xg::Texture)> = picked.iter().map(|(_, va, tex, _)| (*va, &**tex)).collect(); +/// Read each texture once, optionally skip unchanged content (`LAST_CONTENT`), and detile from the +/// same buffer — in parallel across worker threads when the batch reaches `PARALLEL_BYTES`. +unsafe fn hash_and_detile_all( + picked: &[(ID3D12Resource, usize, Arc, Vec)], + bytes: usize, + skip_unchanged: bool, +) -> Vec>> { + let items: Vec<(usize, usize, &xg::Texture)> = picked.iter().map(|(r, va, tex, _)| (r.as_raw() as usize, *va, &**tex)).collect(); let threads = if bytes < PARALLEL_BYTES { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8) }; - subresources_on(&picked, threads) + let threads = threads.min(items.len()); + let work = |res: usize, va: usize, tex: &xg::Texture| -> Option> { + let mem = title_bytes(va, tex.size() as usize); + if skip_unchanged { + let h = content_hash(&mem); + if same_as_last_upload(res, h) { + let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || (n.is_power_of_two() && n >= 1024) { + crate::xlog_info!("title textures: {n} uploads left out so far – the texture's memory held what it held at its last upload"); + } + return None; + } + } + Some(subresources_from_bytes(&mem, tex)) + }; + if threads <= 1 { + return items.iter().map(|&(res, va, tex)| work(res, va, tex)).collect(); + } + let next = std::sync::atomic::AtomicUsize::new(0); + let mut out: Vec>> = (0..items.len()).map(|_| None).collect(); + let done: Vec>)>> = std::thread::scope(|s| { + let workers: Vec<_> = (0..threads) + .map(|_| { + s.spawn(|| { + let mut mine = Vec::new(); + loop { + let k = next.fetch_add(1, Ordering::Relaxed); + let Some(&(res, va, tex)) = items.get(k) else { break }; + mine.push((k, work(res, va, tex))); + } + mine + }) + }) + .collect(); + workers.into_iter().map(|w| w.join().unwrap_or_default()).collect() + }); + for (k, subs) in done.into_iter().flatten() { + out[k] = subs; + } + out } /// `subresources` of each (address, texture), in order, on up to `threads` threads. +#[cfg(test)] unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> Vec> { let threads = threads.min(picked.len()); if threads <= 1 { @@ -1470,25 +1620,31 @@ unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> } } -/// Every subresource (D3D12 order) of a texture from the title's memory at `va`. -unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { +/// Every subresource (D3D12 order) of a texture detiled directly from its already-read bytes `mem`. +fn subresources_from_bytes(mem: &[u8], tex: &xg::Texture) -> Vec { let Some(tex) = tex.texels() else { return Vec::new() }; let c = &tex.chain; let bpe = tex.bpe as usize; if tex.depth > 0 { - let mem = title_bytes(va, tex.size() as usize); - return c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(&mem, i) }).collect(); + return c.levels.iter().enumerate().map(|(i, l)| Subresource { depth: l.depth, rows: l.height, row_bytes: l.width * bpe, data: c.detile_volume(mem, i) }).collect(); } let mut out = Vec::with_capacity(tex.array as usize * c.levels.len()); for s in 0..tex.array as usize { - let slice = title_bytes(va + s * c.slice_bytes, c.slice_bytes); + let start = s * c.slice_bytes; + let Some(slice) = mem.get(start..start + c.slice_bytes) else { break }; for (i, l) in c.levels.iter().enumerate() { - out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(&slice, i, s) }); + out.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * bpe, data: c.detile_level(slice, i, s) }); } } out } +/// Every subresource (D3D12 order) of a texture from the title's memory at `va`. +unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { + let mem = title_bytes(va, tex.size() as usize); + subresources_from_bytes(&mem, tex) +} + #[cfg(test)] mod tests { @@ -2610,4 +2766,60 @@ mod tests { // Different device always starts a new batch. assert!(!batch_fits(1, 4096, 1, 2, 4096)); } + + #[test] + fn dirty_and_pending_uses_src_index_for_small_large_pending_and_gpu_written() { + let mut desc_small = [0u8; 0x38]; + desc_small[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + desc_small[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + desc_small[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + desc_small[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + desc_small[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + desc_small[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); // RGBA8 (16 KiB) + desc_small[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + let tex_small = Arc::new(xg::Texture::new(&desc_small).unwrap()); + assert!((tex_small.size() as usize) <= SMALL_SRC_MAX); + + let mut desc_large = desc_small; + desc_large[0x10..0x18].copy_from_slice(&512u64.to_le_bytes()); + desc_large[0x18..0x1C].copy_from_slice(&512u32.to_le_bytes()); // 1 MiB + let tex_large = Arc::new(xg::Texture::new(&desc_large).unwrap()); + assert!((tex_large.size() as usize) > SMALL_SRC_MAX); + + let mk = |va: usize, src: usize, tex: &Arc, pending: bool, gpu_written: bool| Entry { + device: 1, + va, + src, + in_gpu_view: false, + tex: Arc::clone(tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending, + gpu_written, + placed: false, + unmapped: false, + seq: 0, + }; + + let mut t = Table::new(); + t.insert(0x100, mk(0x1000_0000, 0x2000_0000, &tex_small, false, false)); + t.insert(0x200, mk(0x1010_0000, 0x2010_0000, &tex_small, true, false)); + t.insert(0x300, mk(0x1020_0000, 0x2020_0000, &tex_large, false, false)); + t.insert(0x400, mk(0x1030_0000, 0x2030_0000, &tex_small, false, true)); + + // Only pending entry fires with no dirty pages. + let (hits, cleared) = t.dirty_and_pending(&[], 0x1000); + assert_eq!(hits, vec![0x200]); + assert_eq!(cleared, 1); + + // Dirty pages hitting small, large, and gpu_written return only small + large. + let dirty = [0x2000_1000, 0x2021_0000, 0x2030_0000]; + let (hits, cleared) = t.dirty_and_pending(&dirty, 0x1000); + assert_eq!(hits, vec![0x100, 0x300]); + assert_eq!(cleared, 0); + + // Marking small as gpu_written removes it from dirty scans. + assert!(t.mark_gpu_written(0x100)); + let (hits, _) = t.dirty_and_pending(&dirty, 0x1000); + assert_eq!(hits, vec![0x300]); + } } From bcf3e77126c898fcca393e3cbdb02023f2a9bfaf Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:48:46 +0100 Subject: [PATCH 074/258] D3D12.X: reuse persistent detile worker pool in title_textures hash_and_detile_all spawned and joined fresh OS threads via std::thread::scope on every >=1 MiB texture upload batch, triggering DllMain attach/detach overhead across all loaded modules on the submit thread. Add a lazily initialized persistent DetilePool (with the submit thread participating as worker 0 and panic-safe synchronization) so parallel hashing and detiling reuse persistent helper threads across submissions, plus a focused unit test. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 149 +++++++++++++++++--- 1 file changed, 127 insertions(+), 22 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index be7526f687..900ae54587 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1521,11 +1521,109 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec { out } -/// Batches of at least this many bytes are detiled on several threads (`subresources_of_all`) +/// Batches of at least this many bytes are detiled on several threads (`hash_and_detile_all`) const PARALLEL_BYTES: usize = 1 << 20; +struct DetileState { + gen: u64, + active_helpers: usize, + pending_helpers: usize, + func: Option, + ctx: usize, +} + +/// Reusable persistent worker pool for parallel texture hashing and detiling, avoiding per-submit +/// OS thread creation and DLL attach/detach overhead during streaming bursts. +struct DetilePool { + run_lock: Mutex<()>, + state: Arc<(Mutex, std::sync::Condvar, std::sync::Condvar)>, + helpers: usize, +} + +impl DetilePool { + fn new(max_threads: usize) -> Self { + let helpers = max_threads.saturating_sub(1); + let state = Arc::new(( + Mutex::new(DetileState { gen: 0, active_helpers: 0, pending_helpers: 0, func: None, ctx: 0 }), + std::sync::Condvar::new(), + std::sync::Condvar::new(), + )); + for id in 0..helpers { + let shared = Arc::clone(&state); + let _ = std::thread::Builder::new().name(format!("xcl-detile-{id}")).spawn(move || { + let mut seen = 0u64; + loop { + let job = { + let mut g = shared.0.lock().unwrap(); + while g.gen == seen { + g = shared.1.wait(g).unwrap(); + } + seen = g.gen; + if id < g.active_helpers { + g.func.map(|f| (f, g.ctx)) + } else { + None + } + }; + if let Some((func, ctx)) = job { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { func(ctx as *const c_void) })); + let mut g = shared.0.lock().unwrap(); + g.pending_helpers -= 1; + if g.pending_helpers == 0 { + shared.2.notify_one(); + } + } + } + }); + } + DetilePool { run_lock: Mutex::new(()), state, helpers } + } + + fn run(&self, total_threads: usize, f: &F) { + let helpers = total_threads.saturating_sub(1).min(self.helpers); + if helpers == 0 { + f(); + return; + } + unsafe fn trampoline(ctx: *const c_void) { + (*(ctx as *const F))(); + } + let _serial = self.run_lock.lock().unwrap(); + { + let mut g = self.state.0.lock().unwrap(); + g.func = Some(trampoline::); + g.ctx = (f as *const F) as usize; + g.active_helpers = helpers; + g.pending_helpers = helpers; + g.gen = g.gen.wrapping_add(1); + self.state.1.notify_all(); + } + let caller_res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); + { + let mut g = self.state.0.lock().unwrap(); + while g.pending_helpers > 0 { + g = self.state.2.wait(g).unwrap(); + } + g.func = None; + g.ctx = 0; + g.active_helpers = 0; + } + if let Err(payload) = caller_res { + std::panic::resume_unwind(payload); + } + } +} + +fn detile_pool() -> &'static DetilePool { + static POOL: std::sync::OnceLock = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let max_threads = std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8); + DetilePool::new(max_threads) + }) +} + /// Read each texture once, optionally skip unchanged content (`LAST_CONTENT`), and detile from the -/// same buffer — in parallel across worker threads when the batch reaches `PARALLEL_BYTES`. +/// same buffer — using the persistent detile worker pool when the batch reaches `PARALLEL_BYTES`. unsafe fn hash_and_detile_all( picked: &[(ID3D12Resource, usize, Arc, Vec)], bytes: usize, @@ -1552,27 +1650,15 @@ unsafe fn hash_and_detile_all( return items.iter().map(|&(res, va, tex)| work(res, va, tex)).collect(); } let next = std::sync::atomic::AtomicUsize::new(0); - let mut out: Vec>> = (0..items.len()).map(|_| None).collect(); - let done: Vec>)>> = std::thread::scope(|s| { - let workers: Vec<_> = (0..threads) - .map(|_| { - s.spawn(|| { - let mut mine = Vec::new(); - loop { - let k = next.fetch_add(1, Ordering::Relaxed); - let Some(&(res, va, tex)) = items.get(k) else { break }; - mine.push((k, work(res, va, tex))); - } - mine - }) - }) - .collect(); - workers.into_iter().map(|w| w.join().unwrap_or_default()).collect() + let out: Vec>>> = (0..items.len()).map(|_| Mutex::new(None)).collect(); + detile_pool().run(threads, &|| loop { + let k = next.fetch_add(1, Ordering::Relaxed); + let Some(&(res, va, tex)) = items.get(k) else { break }; + if let Some(subs) = work(res, va, tex) { + *out[k].lock().unwrap() = Some(subs); + } }); - for (k, subs) in done.into_iter().flatten() { - out[k] = subs; - } - out + out.into_iter().map(|m| m.into_inner().unwrap()).collect() } /// `subresources` of each (address, texture), in order, on up to `threads` threads. @@ -2822,4 +2908,23 @@ mod tests { let (hits, _) = t.dirty_and_pending(&dirty, 0x1000); assert_eq!(hits, vec![0x300]); } + + #[test] + fn detile_pool_reuses_workers_across_multiple_batches() { + let pool = DetilePool::new(4); + for round in 0..4usize { + let next = std::sync::atomic::AtomicUsize::new(0); + let slots: Vec = (0..64).map(|_| std::sync::atomic::AtomicUsize::new(0)).collect(); + pool.run(4, &|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= slots.len() { + break; + } + slots[i].store((i + 1) * (round + 1), Ordering::Relaxed); + }); + for (i, s) in slots.iter().enumerate() { + assert_eq!(s.load(Ordering::Relaxed), (i + 1) * (round + 1)); + } + } + } } From 5c8384759cc895b778fba7a6096b773a67095d20 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:48:46 +0100 Subject: [PATCH 075/258] D3D12.X: use RwLock for hot read-mostly PSO and UMA lookup tables Multi-threaded command-list recording hits PENDING (pso_async), BASES (device_x), and UMA_BUFFER / UMA_BUFFERS / EXTS / BUFFER_DELTA / TITLE_ADDRESS / TWO_PASS (real) on every bind, draw, dispatch, view creation, and resource VA lookup, contending on exclusive Mutex locks. Switch these read-mostly lookup tables to std::sync::RwLock so concurrent recording threads take shared read locks without blocking each other. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/device_x.rs | 16 +++--- crates/xcl/src/hle/d3d12x/pso_async.rs | 10 ++-- crates/xcl/src/hle/d3d12x/real.rs | 80 +++++++++++++------------- 3 files changed, 53 insertions(+), 53 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index e429bab64e..047b7449ed 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -328,7 +328,7 @@ struct Base { unsafe impl Send for Base {} unsafe impl Sync for Base {} -static BASES: Mutex>>> = Mutex::new(None); +static BASES: std::sync::RwLock>>> = std::sync::RwLock::new(None); /// Cached derived PSOs for `RSSetDepthBiasX`: (base PSO, override) → owned derived PSO. /// Released when the base PSO is released in `forget_base`. static DEPTH_BIAS_PSOS: Mutex>> = Mutex::new(None); @@ -387,7 +387,7 @@ unsafe fn note_base(pso: *mut c_void, desc: *const c_void, dynamic_depth_bias: b d.0[INPUT_LAYOUT..INPUT_LAYOUT + 8].copy_from_slice(&at.to_le_bytes()); d.0[CACHED_PSO..CACHED_PSO + 16].fill(0); let base = Arc::new(Base { desc: d, shaders, dynamic_depth_bias, static_bias, _elems: elems, _names: names }); - BASES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, base); + BASES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, base); } /// Depth-bias metadata for a tracked graphics PSO: `(created_with_dynamic_depth_bias, static_bias)`. @@ -395,7 +395,7 @@ pub(super) fn base_depth_bias_info(pso: usize) -> Option<(bool, DepthBias)> { if pso == 0 { return None; } - BASES.lock().unwrap().as_ref()?.get(&pso).map(|b| (b.dynamic_depth_bias, b.static_bias)) + BASES.read().unwrap().as_ref()?.get(&pso).map(|b| (b.dynamic_depth_bias, b.static_bias)) } #[cfg(test)] @@ -413,12 +413,12 @@ pub(super) fn register_test_base(pso: usize, dynamic_depth_bias: bool, static_bi _elems: Vec::new(), _names: Vec::new(), }); - BASES.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, base); + BASES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, base); } /// A pipeline released for good is no longer a base; its cached depth-bias variants go with it. pub(super) fn forget_base(pso: usize) { - if let Some(m) = BASES.lock().unwrap().as_mut() { + if let Some(m) = BASES.write().unwrap().as_mut() { m.remove(&pso); } let gone: Vec = { @@ -456,7 +456,7 @@ pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBi if let Some(&cached) = DEPTH_BIAS_PSOS.lock().unwrap().as_ref().and_then(|m| m.get(&(base, bias))) { return Some(cached); } - let b = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&base).cloned())?; + let b = BASES.read().unwrap().as_ref().and_then(|m| m.get(&base).cloned())?; if stage_hashes(&b.desc.0) != Some(b.shaders) { if once(&N, 4) { crate::xlog_warn!("D3D12.X: RSSetDepthBiasX – shaders of base pipeline {base:#x} are gone"); @@ -478,7 +478,7 @@ pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBi let mut release_extra = 0usize; let result = { // re-check base liveness so we never leak a derived PSO for a concurrently released base - let alive = BASES.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&base)); + let alive = BASES.read().unwrap().as_ref().is_some_and(|m| m.contains_key(&base)); let mut g = DEPTH_BIAS_PSOS.lock().unwrap(); let map = g.get_or_insert_with(HashMap::new); if !alive { @@ -530,7 +530,7 @@ pub(super) unsafe extern "system" fn create_derived_pso_x(this: *mut c_void, bas return E_INVALIDARG; } *ppv = std::ptr::null_mut(); - let found = BASES.lock().unwrap().as_ref().and_then(|m| m.get(&(base as usize)).cloned()); + let found = BASES.read().unwrap().as_ref().and_then(|m| m.get(&(base as usize)).cloned()); let Some(b) = found else { if once(&N, 4) { crate::xlog_warn!("D3D12.X: CreateDerivedPipelineStateX – base pipeline {base:?} unknown (its creation failed, or it has stream output)"); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 89340392c2..d4003f79ef 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -117,7 +117,7 @@ impl Pending { } /// stand-in handed to the title → its real pipeline -static PENDING: Mutex>>> = Mutex::new(None); +static PENDING: std::sync::RwLock>>> = std::sync::RwLock::new(None); /// The build is done (`real`: its pipeline, 0 = failed). fn complete(p: &Pending, real: usize) { @@ -390,7 +390,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { bvh_traversal: Default::default(), demand: Default::default(), }); - PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); + PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); @@ -986,7 +986,7 @@ mod used_tests { } fn entry(pso: usize) -> Option> { - PENDING.lock().unwrap().as_ref()?.get(&pso).cloned() + PENDING.read().unwrap().as_ref()?.get(&pso).cloned() } impl Pending { @@ -1171,7 +1171,7 @@ pub fn resolve_for_bind(pso: usize) -> usize { /// another object) and return its real pipeline to release (0: none, or still being built – /// the worker's result is then released when it arrives). pub fn released(pso: usize) -> usize { - let Some(p) = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; + let Some(p) = PENDING.write().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; { let done = p.done.lock().unwrap(); if *done { @@ -1191,6 +1191,6 @@ pub fn is_pending(pso: usize) -> bool { /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { - let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); + let pending = PENDING.read().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ce04c366e5..5440aa3356 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -172,22 +172,22 @@ pub fn abi_root_signature() -> Option { /// Each UMA window as one D3D12 buffer (placed in a heap opened over the process memory): /// `mem`, `mem1`.. of recompiled shaders. (buffer, GPU VA) per window, kept for the process /// lifetime. -static UMA_BUFFER: Mutex> = Mutex::new(Vec::new()); +static UMA_BUFFER: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); /// the committed UMA windows opened as D3D12 heaps (indexed by window `k`; `None` for sparse windows) static UMA_HEAPS: Mutex>> = Mutex::new(Vec::new()); /// console buffers placed in unified memory: resource → (address, bytes) /// address, bytes, whether XCL allocated the memory (not: the title's own, CreatePlacedResourceX) type UmaBuffer = (usize, usize, bool); -static UMA_BUFFERS: Mutex>> = Mutex::new(None); +static UMA_BUFFERS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Where a console-created buffer lives in unified memory (its console GPU address). pub fn console_buffer(res: usize) -> Option<(usize, usize)> { - UMA_BUFFERS.lock().unwrap().as_ref()?.get(&res).map(|&(p, n, _)| (p, n)) + UMA_BUFFERS.read().unwrap().as_ref()?.get(&res).map(|&(p, n, _)| (p, n)) } /// Number of live console buffers in unified memory. pub fn console_buffers() -> usize { - UMA_BUFFERS.lock().unwrap().as_ref().map_or(0, |m| m.len()) + UMA_BUFFERS.read().unwrap().as_ref().map_or(0, |m| m.len()) } static UMA_ERROR: Mutex = Mutex::new(String::new()); @@ -198,7 +198,7 @@ pub fn uma_gpu_va() -> u64 { /// GPU virtual addresses of the UMA window buffers (`u2`, `u3`.. of the shader ABI). pub fn uma_window_vas() -> Vec { - UMA_BUFFER.lock().map(|g| g.iter().map(|b| b.1).collect()).unwrap_or_default() + UMA_BUFFER.read().map(|g| g.iter().map(|b| b.1).collect()).unwrap_or_default() } /// The window buffer holding `len` bytes at UMA address `p`, and their offset in it. @@ -209,7 +209,7 @@ pub(super) fn uma_window_buffer(p: usize, len: usize) -> Option<(usize, u64)> { if p - base + len > size { return None; } - Some((UMA_BUFFER.lock().ok()?.get(k)?.0, (p - base) as u64)) + Some((UMA_BUFFER.read().ok()?.get(k)?.0, (p - base) as u64)) } /// GPU virtual address of a UMA address (None: not in UMA or not open on the GPU). @@ -377,7 +377,7 @@ unsafe fn open_uma(device: &ID3D12Device) { crate::xlog_info!("D3D12.X: memory windows from the shared descriptor heap (no per-access switch)"); } } - *UMA_BUFFER.lock().unwrap() = bufs; + *UMA_BUFFER.write().unwrap() = bufs; } pub fn stats() -> D3d12Stats { @@ -666,7 +666,7 @@ struct Class { } static CLASSES: Mutex> = Mutex::new(Vec::new()); -static EXTS: Mutex>> = Mutex::new(None); +static EXTS: std::sync::RwLock>> = std::sync::RwLock::new(None); unsafe fn vt(obj: *mut c_void) -> *const usize { *(obj as *const *const usize) @@ -724,7 +724,7 @@ pub(super) unsafe fn this_first(a: *mut c_void, b: *mut c_void) -> bool { } fn is_ext(v: usize) -> bool { - EXTS.lock().map(|g| g.as_ref().map(|s| s.contains(&v)).unwrap_or(false)).unwrap_or(false) + EXTS.read().map(|g| g.as_ref().map(|s| s.contains(&v)).unwrap_or(false)).unwrap_or(false) } fn kind_of(ext: usize) -> Option { @@ -879,7 +879,7 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { } let leaked: &'static [usize] = Box::leak(v.into_boxed_slice()); let ext = leaked.as_ptr() as usize + 8; - EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(ext); + EXTS.write().unwrap().get_or_insert_with(HashSet::new).insert(ext); crate::xlog_info!( "D3D12.X: {} – {public} PC methods, {} internal slots under the guard, +{EXTRA_SLOTS} stubs ({kind:?}, PC vtable {})", iface.name, @@ -1443,7 +1443,7 @@ unsafe fn place_console_texture(this: *mut c_void, desc: usize, state: usize, cl u.free(p); return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, size as usize, true)); + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, size as usize, true)); Some(hr) } @@ -1499,9 +1499,9 @@ fn is_cpu_readback_buffer(props: &D3D12_HEAP_PROPERTIES, state: u32, flags: D3D1 unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC, bytes: usize, state: u32, readback_on_null_map: bool, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let (p, _) = super::sparse::alloc(bytes, 0x1_0000)?; if let Some((hr, delta)) = super::sparse::place_buffer(this, p, d, state, riid, ppv) { - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); if delta != 0 { - BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); + BUFFER_DELTA.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } if readback_on_null_map { note_sparse_readback(*ppv as usize); @@ -1524,7 +1524,7 @@ fn sanitize_coherent_buffer(desc: &D3D12_RESOURCE_DESC, state: usize) -> (D3D12_ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, state: usize, clear: usize, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let u = crate::gpu::uma::get()?; - if UMA_BUFFER.lock().unwrap().is_empty() || ppv.is_null() { + if UMA_BUFFER.read().unwrap().is_empty() || ppv.is_null() { return None; } let d: D3D12_RESOURCE_DESC = std::ptr::read(desc as *const D3D12_RESOURCE_DESC); @@ -1565,7 +1565,7 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta } return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); // Map must hand out the same memory the shaders read (checked once) static CHECKED: AtomicU64 = AtomicU64::new(0); if CHECKED.fetch_add(1, Ordering::Relaxed) == 0 { @@ -1604,9 +1604,9 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: // the title's own memory (a sparse window): a resource over its video-memory tiles if u.is_sparse(va) { let (hr, delta) = super::sparse::place_buffer(this, va, &d, state, riid, ppv)?; - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); if delta != 0 { - BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); + BUFFER_DELTA.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } return Some(hr); } @@ -1619,24 +1619,24 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: if hr < 0 || (*ppv).is_null() { return None; } - UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); if delta != 0 { - BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); + BUFFER_DELTA.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } Some(hr) } /// buffers placed below their console address: resource → bytes before it -static BUFFER_DELTA: Mutex>> = Mutex::new(None); +static BUFFER_DELTA: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Where offset 0 of a console buffer is in its PC resource (0 for most). pub fn buffer_delta(res: usize) -> u64 { - BUFFER_DELTA.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied()).unwrap_or(0) + BUFFER_DELTA.read().unwrap().as_ref().and_then(|m| m.get(&res).copied()).unwrap_or(0) } #[cfg(test)] pub(super) fn set_test_buffer_delta(res: usize, delta: Option) { - let mut g = BUFFER_DELTA.lock().unwrap(); + let mut g = BUFFER_DELTA.write().unwrap(); match delta { Some(d) => { g.get_or_insert_with(HashMap::new).insert(res, d); @@ -1711,7 +1711,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v if hr >= 0 { return hr; } - match super::title_textures::address(this as usize).or_else(|| TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied())) { + match super::title_textures::address(this as usize).or_else(|| TITLE_ADDRESS.read().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied())) { Some(p) => { if !data.is_null() { *data = p as *mut c_void; @@ -1753,15 +1753,15 @@ unsafe extern "system" fn res_write_to_subresource(this: *mut c_void, sub: u32, /// resources the title placed at its own address that got a PC resource of their own: on the /// console Map gives that address (the CPU's view of the resource) -static TITLE_ADDRESS: Mutex>> = Mutex::new(None); +static TITLE_ADDRESS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// The title address a resource stands for (buffers in unified memory, placed resources). pub(super) fn title_address(res: usize) -> Option { - console_buffer(res).map(|b| b.0).or_else(|| TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied())) + console_buffer(res).map(|b| b.0).or_else(|| TITLE_ADDRESS.read().unwrap().as_ref().and_then(|m| m.get(&res).copied())) } pub(super) fn note_title_address(res: usize, va: usize) { - TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, va); + TITLE_ADDRESS.write().unwrap().get_or_insert_with(HashMap::new).insert(res, va); } /// resources whose Map gave their unified-memory address (no PC mapping to undo) @@ -1804,10 +1804,10 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { if let Some(s) = RESERVED.lock().unwrap().as_mut() { s.remove(&(this as usize)); } - if let Some(m) = BUFFER_DELTA.lock().unwrap().as_mut() { + if let Some(m) = BUFFER_DELTA.write().unwrap().as_mut() { m.remove(&(this as usize)); } - if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() { + if let Some(m) = TITLE_ADDRESS.write().unwrap().as_mut() { m.remove(&(this as usize)); } super::sparse::forget_buffer(this as usize); @@ -1815,7 +1815,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::title_textures::forget(this as usize); super::depth_uav::forget(this as usize); super::format_alias::forget(this as usize); - let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); + let gone = UMA_BUFFERS.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { if u.is_sparse(p) { super::sparse::free(p); @@ -2064,7 +2064,7 @@ fn forget_pso(pso: usize) { } super::device_x::forget_base(pso); // the compute pass goes with the last user of its entry (`Drop for TwoPassPso`) - let gone = TWO_PASS.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)); + let gone = TWO_PASS.write().unwrap().as_mut().and_then(|m| m.remove(&pso)); drop(gone); } @@ -2079,7 +2079,7 @@ unsafe extern "system" fn res_gpu_va_x(this: *mut c_void) -> u64 { // through it: with 0 it wrote 256 KB at address 0): the title's address it was placed at match f(this) { 0 => { - let placed = TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()); + let placed = TITLE_ADDRESS.read().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()); placed.or_else(|| texture_memory(this)).unwrap_or(0) as u64 } va => va, @@ -2096,7 +2096,7 @@ unsafe fn texture_memory(res: *mut c_void) -> Option { use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_RESERVE, PAGE_READWRITE}; static LOCK: Mutex<()> = Mutex::new(()); let _g = LOCK.lock().unwrap(); - if let Some(p) = TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()) { + if let Some(p) = TITLE_ADDRESS.read().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()) { return Some(p); } let d = ID3D12Resource::from_raw_borrowed(&res)?.GetDesc(); @@ -3720,7 +3720,7 @@ unsafe fn note_heap_uma(desc: usize, ppv: *mut *mut c_void) { return; } let d: D3D12_HEAP_DESC = std::ptr::read_unaligned(desc as *const D3D12_HEAP_DESC); - if d.Flags.0 & DENY_BUFFERS != 0 || d.SizeInBytes == 0 || UMA_BUFFER.lock().unwrap().is_empty() { + if d.Flags.0 & DENY_BUFFERS != 0 || d.SizeInBytes == 0 || UMA_BUFFER.read().unwrap().is_empty() { return; } let size = d.SizeInBytes as usize; @@ -6120,22 +6120,22 @@ impl Drop for TwoPassPso { } } -static TWO_PASS: Mutex>>> = Mutex::new(None); +static TWO_PASS: std::sync::RwLock>>> = std::sync::RwLock::new(None); /// The compute pass of a pipeline state XCL built from console MS / GS code. pub fn two_pass_of(pso: usize) -> Option> { let pso = super::pso_async::resolve(pso); - TWO_PASS.lock().unwrap().as_ref()?.get(&pso).cloned() + TWO_PASS.read().unwrap().as_ref()?.get(&pso).cloned() } pub fn two_pass_count() -> usize { - TWO_PASS.lock().unwrap().as_ref().map_or(0, |m| m.len()) + TWO_PASS.read().unwrap().as_ref().map_or(0, |m| m.len()) } #[cfg(test)] pub(super) fn register_two_pass_for_test(pso: usize, kind: &'static str) { if pso != 0 { - TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert( + TWO_PASS.write().unwrap().get_or_insert_with(HashMap::new).insert( pso, std::sync::Arc::new(TwoPassPso { compute: 0, @@ -6388,7 +6388,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: return E_INVALIDARG; } note_pso_rs(mesh_pso, mesh_rs); - TWO_PASS.lock().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + TWO_PASS.write().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute {} B + mesh {} B DXIL)", tp.cs.len(), tp.ms.len()); @@ -8135,7 +8135,7 @@ mod this_first_tests { let pc = [0usize; 32]; let ext = [pc.as_ptr() as usize, 0]; let vtbl = ext.as_ptr() as usize + 8; - EXTS.lock().unwrap().get_or_insert_with(HashSet::new).insert(vtbl); + EXTS.write().unwrap().get_or_insert_with(HashSet::new).insert(vtbl); let plain = 0x1234_5678usize; let p = &plain as *const usize as *mut c_void; // an object off the stack (as a real device is), and a stack buffer holding a stale copy @@ -8163,7 +8163,7 @@ mod this_first_tests { assert!(this_first(b, s) && this_first(s, b)); drop(Box::from_raw(obj as *mut [usize; 1])); } - if let Some(g) = EXTS.lock().unwrap().as_mut() { + if let Some(g) = EXTS.write().unwrap().as_mut() { g.remove(&vtbl); } } From d40d027339bf2735f801ee05fa1fd740ddb1a81a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:56:54 +0100 Subject: [PATCH 076/258] D3D12.X: recycle released reserved sampled textures by desc and state Port upstream PR #2436 (by Saintwolf, adapted for #2306 lazy level pages and #2275 multi-queue retirement) onto amd-dev. Streamed sampled textures placed on shared 64 KiB video-memory pages previously called CreateReservedResource and GetResourceTiling on every placement, costing 0.6-1.7 ms per texture on AMD drivers (#1268). Keep a bounded per-device pool (512 idle entries, FIFO eviction, opt-out via XCL_RESERVED_POOL=0) of released reserved sampled textures keyed by exact (D3D12_RESOURCE_DESC, uniform D3D12_RESOURCE_STATES), also caching the #2306 Levels tiling layout so XCL_TEXTURE_LEVEL_PAGES=1 placements skip both CreateReservedResource and GetResourceTiling on reuse. When late_release finishes draining all live GPU queues past a texture's batch, vram::recycle_ready unmaps any still-mapped tiles on the background thread (skipping unmap for lazy textures that had zero mapped levels) and parks the ID3D12Resource for reuse. Fixes #1268. Part of #1833. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/late_release.rs | 3 + crates/xcl/src/hle/d3d12x/real.rs | 9 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 28 +- crates/xcl/src/hle/d3d12x/vram.rs | 394 ++++++++++++++++++-- 4 files changed, 388 insertions(+), 46 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 07e8abb939..8a81aa45ec 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -143,6 +143,9 @@ pub unsafe fn drain_known(seal_now: bool) { }; // (outside the lock: a release may end other objects, whose releases come back here) for res in gone { + if super::vram::recycle_ready(res) { + continue; + } let ptr = res as *mut c_void; let f: unsafe extern "system" fn(*mut c_void) -> u32 = if super::real::is_adopted(ptr) { std::mem::transmute(super::real::orig_fn(ptr, 2)) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5440aa3356..06b807e4ad 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1811,8 +1811,11 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { m.remove(&(this as usize)); } super::sparse::forget_buffer(this as usize); - super::vram::forget(this as usize); - super::title_textures::forget(this as usize); + let recycle = super::vram::forget_for_recycle(this as usize, held); + let final_state = super::title_textures::forget(this as usize); + if let (Some(info), Some(state)) = (recycle, final_state) { + super::vram::park_recyclable(this as usize, info, state.0 as u32); + } super::depth_uav::forget(this as usize); super::format_alias::forget(this as usize); let gone = UMA_BUFFERS.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); @@ -3616,7 +3619,7 @@ unsafe fn desc_of(res: *mut c_void) -> Option { ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()) } -unsafe fn note_reserved(hr: HRESULT, ppv: *mut *mut c_void) -> HRESULT { +pub(super) unsafe fn note_reserved(hr: HRESULT, ppv: *mut *mut c_void) -> HRESULT { if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { if let Some(d) = desc_of(*ppv) { RESERVED.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, d); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 900ae54587..a40387f660 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -344,16 +344,18 @@ impl Table { } /// Remove `res` on COM release, reactivating any shadowed older textures it uncovered (newest - /// first). Returns `(was_present, pending_delta, unmapped_res_to_remap)`. - fn remove(&mut self, res: usize) -> (bool, isize, Vec) { + /// first). Returns `(was_present, pending_delta, unmapped_res_to_remap, uniform_state)`. + fn remove(&mut self, res: usize) -> (bool, isize, Vec, Option) { if let Some(old) = self.shadowed.remove(&res) { self.shadowed_by_va.remove(&(old.va, res)); if self.shadowed.is_empty() { self.max_shadowed_size = 0; } - return (true, 0, Vec::new()); + let st = (old.states.len() == 1).then(|| old.states[0]); + return (true, 0, Vec::new(), st); } - let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new()) }; + let Some(old) = self.by_res.remove(&res) else { return (false, 0, Vec::new(), None) }; + let st = (old.states.len() == 1).then(|| old.states[0]); self.by_va.remove(&(old.va, res)); self.unindex_active(res, old.src); let mut pending_delta = if old.pending { -1 } else { 0 }; @@ -391,7 +393,7 @@ impl Table { if self.shadowed.is_empty() { self.max_shadowed_size = 0; } - (true, pending_delta, to_remap) + (true, pending_delta, to_remap, st) } fn get_mut(&mut self, res: usize) -> Option<&mut Entry> { @@ -662,16 +664,17 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { } } -/// The PC texture was released for good. -pub fn forget(res: usize) { +/// The PC texture was released for good. Returns its last tracked uniform D3D12 resource state +/// when all subresources shared a single state (used by `vram` to recycle reserved textures safely). +pub fn forget(res: usize) -> Option { LAST_CONTENT.lock().unwrap().remove(&res); STREAM_RECHECK.lock().unwrap().remove(&res); - let (removed, to_remap) = { + let (removed, to_remap, state) = { let mut t = TEXTURES.lock().unwrap(); - let (removed, delta, remap_ptrs) = t.remove(res); + let (removed, delta, remap_ptrs, state) = t.remove(res); adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); - (removed, unsafe { clone_resources(&remap_ptrs) }) + (removed, unsafe { clone_resources(&remap_ptrs) }, state) }; for r in &to_remap { unsafe { @@ -685,6 +688,7 @@ pub fn forget(res: usize) { if removed { TEXTURES_GEN.fetch_add(1, Ordering::Release); } + state } /// The title-memory address of a texture kept in step with it. @@ -2189,12 +2193,12 @@ mod tests { assert_eq!((delta, unmap), (0, vec![1, 2, 20])); assert!(tbl.by_res.contains_key(&3) && tbl.by_res.contains_key(&4)); // Releasing 4 uncovers newest non-overlapping shadowed entries (1 and 20) and requests remap. - let (removed, delta, mut remap) = tbl.remove(4); + let (removed, delta, mut remap, _) = tbl.remove(4); remap.sort_unstable(); assert_eq!((removed, delta, remap), (true, 1, vec![1, 20])); assert!(tbl.by_res.contains_key(&1) && tbl.by_res.contains_key(&20) && tbl.shadowed.contains_key(&2)); // Releasing 20 uncovers 2; releasing middle of a 3-chain still uncovers oldest when top goes. - let (removed, _, remap) = tbl.remove(20); + let (removed, _, remap, _) = tbl.remove(20); assert_eq!((removed, remap), (true, vec![2])); assert!(tbl.by_res.contains_key(&2)); assert_eq!(tbl.insert(5, entry(0x10_8000, &tex_64k, true, true)).0, 1); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 2a3a0264d0..5f904b2cbd 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -131,14 +131,174 @@ pub(super) fn is_placed_texture(resource: usize) -> bool { PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } -pub(super) fn forget(resource: usize) { +/// Maximum idle reserved sampled textures kept per device for reuse (#1268). +/// Reserved resources hold no backing memory of their own (tiles are unmapped when parked). +const RESERVED_POOL_MAX: usize = 512; + +fn reserved_pool_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_RESERVED_POOL").ok().as_deref() != Some("0")) +} + +/// Exact description and uniform D3D12 resource state of a recyclable reserved sampled texture. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +struct ReservedKey { + dimension: i32, + alignment: u64, + width: u64, + height: u32, + depth_or_array: u16, + mip_levels: u16, + format: i32, + sample_count: u32, + sample_quality: u32, + flags: i32, + state: u32, +} + +impl ReservedKey { + fn from_desc(desc: &D3D12_RESOURCE_DESC, state: u32) -> Self { + Self { + dimension: desc.Dimension.0, + alignment: desc.Alignment, + width: desc.Width, + height: desc.Height, + depth_or_array: desc.DepthOrArraySize, + mip_levels: desc.MipLevels, + format: desc.Format.0, + sample_count: desc.SampleDesc.Count, + sample_quality: desc.SampleDesc.Quality, + flags: desc.Flags.0, + state, + } + } +} + +/// Bounded per-device pool of idle reserved sampled textures keyed by `(desc, state)`. +/// FIFO eviction caps the number of idle `ID3D12Resource` wrappers; evicted raw pointers are +/// returned to the caller so COM `Release` runs outside `PAGES.lock()`. +struct ReservedPool { + by_key: std::collections::HashMap)>>, + order: std::collections::VecDeque<(ReservedKey, usize)>, + live: usize, + cap: usize, +} + +impl ReservedPool { + fn new(cap: usize) -> Self { + Self { + by_key: std::collections::HashMap::new(), + order: std::collections::VecDeque::new(), + live: 0, + cap, + } + } + + fn take(&mut self, key: &ReservedKey) -> Option<(usize, u32, Option)> { + let bucket = self.by_key.get_mut(key)?; + let item = bucket.pop()?; + if bucket.is_empty() { + self.by_key.remove(key); + } + self.live -= 1; + Some(item) + } + + fn push(&mut self, key: ReservedKey, raw: usize, total: u32, levels: Option) -> Option { + if self.cap == 0 { + return Some(raw); + } + let mut evicted = None; + while self.live >= self.cap { + let Some((old_key, old_raw)) = self.order.pop_front() else { break }; + if let Some(bucket) = self.by_key.get_mut(&old_key) { + if let Some(pos) = bucket.iter().position(|(r, _, _)| *r == old_raw) { + bucket.swap_remove(pos); + if bucket.is_empty() { + self.by_key.remove(&old_key); + } + self.live -= 1; + evicted = Some(old_raw); + break; + } + } + } + self.by_key.entry(key).or_default().push((raw, total, levels)); + self.order.push_back((key, raw)); + self.live += 1; + evicted + } +} + +/// Metadata for a released reserved sampled texture awaiting GPU completion in `late_release`. +pub(super) struct RecycleInfo { + dev_key: usize, + key: ReservedKey, + total: u32, + was_mapped: bool, + levels: Option, +} + +static PARKING: Mutex>> = Mutex::new(None); + +unsafe fn release_raw_com(raw: usize) { + let ptr = raw as *mut c_void; + let f: unsafe extern "system" fn(*mut c_void) -> u32 = if super::real::is_adopted(ptr) { + std::mem::transmute(super::real::orig_fn(ptr, 2)) + } else { + std::mem::transmute(*(*(ptr as *const *const usize)).add(2)) + }; + f(ptr); +} + +pub(super) fn forget_for_recycle(resource: usize, held: bool) -> Option { let placed = PLACED_TEXTURES.lock().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); - if placed { - forget_pages(resource); - if let Some(id) = ARENA_OF.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) { - ARENAS.lock().unwrap().release(id, std::time::Instant::now()); + if !placed { + return None; + } + let info = forget_pages(resource, held); + if let Some(id) = ARENA_OF.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) { + ARENAS.lock().unwrap().release(id, std::time::Instant::now()); + } + info +} + +pub(super) fn park_recyclable(resource: usize, mut info: RecycleInfo, final_state: u32) { + info.key.state = final_state; + PARKING.lock().unwrap().get_or_insert_with(std::collections::HashMap::new).insert(resource, info); +} + +/// Called by `late_release` once every live GPU queue is past the batch containing `resource`. +/// Returns `true` when `resource` was unmapped and parked in the per-device reuse pool (so +/// `late_release` must not call `Release` on it). +pub(super) unsafe fn recycle_ready(resource: usize) -> bool { + let Some(info) = PARKING.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) else { + return false; + }; + if !reserved_pool_enabled() { + return false; + } + let evicted = { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&info.dev_key) else { + return false; + }; + if info.was_mapped { + if let Some(res) = ID3D12Resource::from_raw_borrowed(&(resource as *mut c_void)) { + pages.unmap(res, info.total); + } } + pages.reserved_pool.push(info.key, resource, info.total, info.levels) + }; + if let Some(old) = evicted { + release_raw_com(old); } + true +} + +#[allow(dead_code)] +pub(super) fn forget(resource: usize) { + let _ = forget_for_recycle(resource, false); } /// Whether a console texture with these D3D12_RESOURCE_FLAGS is the GPU's (render target, @@ -236,6 +396,7 @@ struct Target { follows: Vec, /// its levels get their pages one by one (`map_levels`); None: all of it has pages levels: Option, + recycle: Option, } /// An owned page of placed textures in a graphics reservation: mapped only while the title @@ -686,6 +847,8 @@ struct Pages { follow: std::collections::HashMap, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, + /// idle reserved sampled textures kept for reuse by `(desc, state)` (#1268) + reserved_pool: ReservedPool, /// reusable scratch buffers for `map()` scratch_tiles: Vec, scratch_heaps: Vec, @@ -729,6 +892,7 @@ impl Pages { follow: std::collections::HashMap::new(), reservable_cache: std::collections::HashMap::new(), scratch_tiles: Vec::new(), + reserved_pool: ReservedPool::new(RESERVED_POOL_MAX), scratch_heaps: Vec::new(), scratch_flags: Vec::new(), scratch_offsets: Vec::new(), @@ -1282,39 +1446,95 @@ unsafe fn place_on_pages( } }; let dev_key = dev.as_raw() as usize; + let recycle_key = (!require_aligned && clear.is_null() && tiled.Flags.0 == 0 && reserved_pool_enabled()) + .then(|| ReservedKey::from_desc(&tiled, state)); + let mut pooled = None; let is_reservable = { let timer = step(Step::Lock); let mut g = PAGES.lock().unwrap(); drop(timer); let pages = g.entry(dev_key).or_insert_with(|| Pages::new(dev)).as_mut()?; - *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)) + let ok = *pages.reservable_cache.entry((tiled.Format.0, tiled.SampleDesc.Count)).or_insert_with(|| reservable(dev, &tiled)); + if ok { + if let Some(key) = recycle_key { + pooled = pages.reserved_pool.take(&key); + } + } + ok }; if !is_reservable { log("no tiled support for its format or sample count"); return None; } - // CreateReservedResource and GetResourceTiling do not touch `PAGES`; keep them outside the - // lock so concurrent streaming threads, `before_execute`, and `page_bytes` do not serialize. - let timer = step(Step::Reserved); - let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); - drop(timer); - if hr < 0 || (*ppv).is_null() { - log(&format!("{hr:#x}")); - return None; - } + let mut cached_tiling: Option<(u32, Option)> = None; + let hr = if let Some((pooled_raw, cached_total, cached_levels)) = pooled { + type QiFn = unsafe extern "system" fn(*mut c_void, *const windows_sys::core::GUID, *mut *mut c_void) -> HRESULT; + let ptr = pooled_raw as *mut c_void; + let qi: QiFn = if super::real::is_adopted(ptr) { + std::mem::transmute(super::real::orig_fn(ptr, 0)) + } else { + std::mem::transmute(*(*(ptr as *const *const usize))) + }; + let hr = qi(ptr, riid, ppv); + release_raw_com(pooled_raw); + if hr >= 0 && !(*ppv).is_null() { + super::real::note_reserved(hr, ppv); + static REUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let h = REUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if h.is_power_of_two() && h >= 16 { + crate::xlog_info!("D3D12.X: reserved texture pool: {h} reused (skipped CreateReservedResource)"); + } + cached_tiling = Some((cached_total, cached_levels)); + hr + } else { + let timer = step(Step::Reserved); + let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); + drop(timer); + if hr < 0 || (*ppv).is_null() { + log(&format!("{hr:#x}")); + return None; + } + hr + } + } else { + // CreateReservedResource and GetResourceTiling do not touch `PAGES`; keep them outside the + // lock so concurrent streaming threads, `before_execute`, and `page_bytes` do not serialize. + let timer = step(Step::Reserved); + let hr = super::real::dev_create_reserved_resource(this, &tiled as *const _ as usize, state as usize, clear as usize, riid, ppv); + drop(timer); + if hr < 0 || (*ppv).is_null() { + log(&format!("{hr:#x}")); + return None; + } + hr + }; let raw = *ppv; let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; - let timer = step(Step::Tiling); - let levels = if lazy { - let (levels, n) = level_tiling(dev, res, desc.MipLevels as u32); - total = n; - levels.filter(|_| total > 0 && owned_pages(va, console_bytes, total as usize).is_some()) - } else { - dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); - None + let levels = match cached_tiling { + Some((cached_total, _)) if !lazy => { + total = cached_total; + None + } + Some((cached_total, Some(mut cached_levels))) => { + total = cached_total; + cached_levels.groups.iter_mut().for_each(|g| g.3 = false); + Some(cached_levels).filter(|_| total > 0 && owned_pages(va, console_bytes, total as usize).is_some()) + } + _ => { + let timer = step(Step::Tiling); + let lv = if lazy { + let (levels, n) = level_tiling(dev, res, desc.MipLevels as u32); + total = n; + levels.filter(|_| total > 0 && owned_pages(va, console_bytes, total as usize).is_some()) + } else { + dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + None + }; + drop(timer); + lv + } }; - drop(timer); let bound = { let timer = step(Step::Lock); let mut g = PAGES.lock().unwrap(); @@ -1324,10 +1544,10 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), follows: Vec::new(), levels }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), follows: Vec::new(), levels, recycle: recycle_key }); true } else if let Some((used, used_extra, follows)) = pages.bind(dev, res, raw as usize, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, follows, levels: None }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, follows, levels: None, recycle: recycle_key }); true } else { false @@ -1406,22 +1626,36 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { } /// A resource released: its pages are no longer its. -fn forget_pages(resource: usize) { +fn forget_pages(resource: usize, held: bool) -> Option { let mut g = PAGES.lock().unwrap(); let now = std::time::Instant::now(); - for pages in g.values_mut().flatten() { + for (&dev_key, slot) in g.iter_mut() { + let Some(pages) = slot.as_mut() else { continue }; let Some(t) = pages.targets.remove(&resource) else { continue }; - if let Some(l) = &t.levels { + let mapped_level_tiles = t.levels.as_ref().map(|l| l.mapped_tiles()); + if let Some(mapped) = mapped_level_tiles { LEVEL_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_sub(t.total as u64, std::sync::atomic::Ordering::Relaxed); - LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); + LEVEL_STATS[2].fetch_sub(mapped, std::sync::atomic::Ordering::Relaxed); } + let was_mapped = t.mapped && mapped_level_tiles.is_none_or(|m| m > 0); if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); } pages.unfollow(resource, &t.follows); - return; + return (held && reserved_pool_enabled()) + .then(|| { + t.recycle.map(|key| { + let levels = t.levels.map(|mut l| { + l.groups.iter_mut().for_each(|g| g.3 = false); + l + }); + RecycleInfo { dev_key, key, total: t.total, was_mapped, levels } + }) + }) + .flatten(); } + None } /// Reclaimed heaps waiting for `unmap_mark` (if any) and every live queue's fence mark on one device. @@ -2485,4 +2719,102 @@ mod tests { assert!(new_calls < old_calls); } } + + #[test] + fn reserved_pool_reuses_matching_key_isolates_state_and_evicts_fifo() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 9, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_BC1_UNORM, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let k_common = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_COMMON.0 as u32); + let k_srv = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 as u32); + let mut desc2 = desc; + desc2.Width = 512; + let k_512 = ReservedKey::from_desc(&desc2, D3D12_RESOURCE_STATE_COMMON.0 as u32); + let lv = Levels::new(&[(0, 3)], Some((3, 1)), 4, 9); + + let mut pool = ReservedPool::new(2); + assert_eq!(pool.push(k_common, 0x1000, 1, None), None); + assert_eq!(pool.push(k_srv, 0x2000, 1, None), None); + // State mismatch does not cross-hit. + assert_eq!(pool.take(&k_512), None); + // Third push evicts oldest (0x1000) FIFO. + assert_eq!(pool.push(k_512, 0x3000, 4, lv.clone()), Some(0x1000)); + assert_eq!(pool.take(&k_common), None); + assert_eq!(pool.take(&k_srv), Some((0x2000, 1, None))); + assert_eq!(pool.take(&k_512), Some((0x3000, 4, lv))); + assert_eq!(pool.live, 0); + + // Zero-cap pool immediately returns pushed objects for release. + let mut disabled = ReservedPool::new(0); + assert_eq!(disabled.push(k_common, 0x4000, 1, None), Some(0x4000)); + } + + #[test] + fn reserved_resource_recycle_unmaps_reuses_and_remaps_on_gpu() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_BC1_UNORM, DXGI_SAMPLE_DESC}; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Alignment: 0, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 9, + Format: DXGI_FORMAT_BC1_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let res = r.unwrap(); + let raw = res.into_raw() as usize; + let raw_ptr = raw as *mut c_void; + let borrowed = ID3D12Resource::from_raw_borrowed(&raw_ptr).unwrap(); + let mut total = 0u32; + dev.GetResourceTiling(borrowed, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + assert!(total >= 1); + + let key = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_COMMON.0 as u32); + let (used1, extra1) = pages.bind(&dev, borrowed, 0x2000_0000, Some(total as u64 * PAGE as u64), total).expect("initial bind"); + pages.unmap(borrowed, total); + pages.release_tiles(used1, extra1, std::time::Instant::now(), false); + assert_eq!(pages.reserved_pool.push(key, raw, total, None), None); + + // Mismatched state does not reuse it. + let wrong_state = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 as u32); + assert_eq!(pages.reserved_pool.take(&wrong_state), None); + + // Matching desc + state pops the exact same resource and rebinds cleanly to a new VA. + let (reused_raw, reused_total, reused_levels) = pages.reserved_pool.take(&key).expect("recycle hit"); + assert_eq!(reused_raw, raw); + assert_eq!(reused_total, total); + assert_eq!(reused_levels, None); + let reused_ptr = reused_raw as *mut c_void; + let reused = ID3D12Resource::from_raw_borrowed(&reused_ptr).unwrap(); + let (used2, extra2) = pages.bind(&dev, reused, 0x2010_0000, Some(total as u64 * PAGE as u64), reused_total).expect("rebind after recycle"); + pages.unmap(reused, reused_total); + pages.release_tiles(used2, extra2, std::time::Instant::now(), false); + // Wait for unmap on the tile-mapping queue before dropping the resource and heaps. + pages.value += 1; + let _ = pages.queue.Signal(&pages.fence, pages.value); + let _ = pages.fence.SetEventOnCompletion(pages.value, windows::Win32::Foundation::HANDLE::default()); + drop(ID3D12Resource::from_raw(reused_raw as *mut c_void)); + } + } } From 9ff793f24da93b379d978c9cb95708f8012a4455 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:01:02 +0100 Subject: [PATCH 077/258] D3D12.X: batch busy late_release holds and widen RwLock tables Eliminate two remaining CPU hot-path stalls across resource release and multi-threaded recording: 1. late_release::hold previously forced seal_now=true (issuing queue.Signal on every live command queue) and busy-spun for IDLE_WAIT (300 us) on every single Release while GPU work was in flight, burning 300 us per released streaming texture and flooding queues with per-resource signals. When a sealed batch is already in flight on the GPU, queue the release into open and let the background xcl-late-release thread batch it at SEAL_EVERY (10 ms) without spinning; idle-GPU releases still drain synchronously within IDLE_WAIT. Also avoid cloning all live command queues in drain_known when only reaping already-sealed batches (via Held::reap). 2. Convert the remaining read-heavy lookup Mutex tables in real.rs (CLASSES, PSO_RS, TRANSLATED_GRAPHICS, RECT_LIST_GS, CONSOLE_COMPUTE, PSO_SHADERS, PSO_LAYOUTS, RESERVED, UNMAPPABLE, SPARSE_READBACK, HEAP_UMA, ABI_RS_SAMPLERS) and device_x.rs (DEPTH_BIAS_PSOS, UAV_FORMAT_SUPPORT, TYPED_UAV_SUPPORT) to RwLock so concurrent recording and streaming threads stop serializing on read-mostly metadata. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/device_x.rs | 26 ++--- crates/xcl/src/hle/d3d12x/late_release.rs | 112 ++++++++++++++------ crates/xcl/src/hle/d3d12x/real.rs | 119 +++++++++++----------- 3 files changed, 155 insertions(+), 102 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 047b7449ed..718091f05b 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -331,7 +331,7 @@ unsafe impl Sync for Base {} static BASES: std::sync::RwLock>>> = std::sync::RwLock::new(None); /// Cached derived PSOs for `RSSetDepthBiasX`: (base PSO, override) → owned derived PSO. /// Released when the base PSO is released in `forget_base`. -static DEPTH_BIAS_PSOS: Mutex>> = Mutex::new(None); +static DEPTH_BIAS_PSOS: std::sync::RwLock>> = std::sync::RwLock::new(None); fn rd32(d: &[u8], o: usize) -> u32 { u32::from_le_bytes(d[o..o + 4].try_into().unwrap()) @@ -400,7 +400,7 @@ pub(super) fn base_depth_bias_info(pso: usize) -> Option<(bool, DepthBias)> { #[cfg(test)] pub(super) fn depth_bias_cache_len() -> usize { - DEPTH_BIAS_PSOS.lock().unwrap().as_ref().map_or(0, HashMap::len) + DEPTH_BIAS_PSOS.read().unwrap().as_ref().map_or(0, HashMap::len) } #[cfg(test)] @@ -422,7 +422,7 @@ pub(super) fn forget_base(pso: usize) { m.remove(&pso); } let gone: Vec = { - let mut g = DEPTH_BIAS_PSOS.lock().unwrap(); + let mut g = DEPTH_BIAS_PSOS.write().unwrap(); match g.as_mut() { Some(m) => { let mut out = Vec::new(); @@ -453,7 +453,7 @@ pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBi if dev.is_null() || base == 0 { return None; } - if let Some(&cached) = DEPTH_BIAS_PSOS.lock().unwrap().as_ref().and_then(|m| m.get(&(base, bias))) { + if let Some(&cached) = DEPTH_BIAS_PSOS.read().unwrap().as_ref().and_then(|m| m.get(&(base, bias))) { return Some(cached); } let b = BASES.read().unwrap().as_ref().and_then(|m| m.get(&base).cloned())?; @@ -479,7 +479,7 @@ pub(super) unsafe fn depth_bias_pso(dev: *mut c_void, base: usize, bias: DepthBi let result = { // re-check base liveness so we never leak a derived PSO for a concurrently released base let alive = BASES.read().unwrap().as_ref().is_some_and(|m| m.contains_key(&base)); - let mut g = DEPTH_BIAS_PSOS.lock().unwrap(); + let mut g = DEPTH_BIAS_PSOS.write().unwrap(); let map = g.get_or_insert_with(HashMap::new); if !alive { release_extra = derived; @@ -694,7 +694,7 @@ fn uav_format_supported_by_caps(format: u32, support1: u32, support2: u32) -> bo (support2 & typed_rw) != 0 } -static UAV_FORMAT_SUPPORT: Mutex>> = Mutex::new(None); +static UAV_FORMAT_SUPPORT: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Query (and cache per adapter LUID + format) whether the PC device supports `ALLOW_UNORDERED_ACCESS` /// on `format`. Falls back to `texture_format_allows_uav` if the device cannot be queried. @@ -710,7 +710,7 @@ unsafe fn device_format_supports_uav(device: *mut c_void, format: u32) -> bool { }; let luid = dev.GetAdapterLuid(); let key = ((luid.LowPart, luid.HighPart), format); - if let Some(&cached) = UAV_FORMAT_SUPPORT.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { + if let Some(&cached) = UAV_FORMAT_SUPPORT.read().unwrap().as_ref().and_then(|m| m.get(&key)) { return cached; } let mut fs = D3D12_FEATURE_DATA_FORMAT_SUPPORT { @@ -729,7 +729,7 @@ unsafe fn device_format_supports_uav(device: *mut c_void, format: u32) -> bool { } else { true }; - UAV_FORMAT_SUPPORT.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, supported); + UAV_FORMAT_SUPPORT.write().unwrap().get_or_insert_with(HashMap::new).insert(key, supported); supported } @@ -897,7 +897,7 @@ pub fn pc_shader_view_format(resource: u32, view: u32) -> u32 { } /// Cached host `D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW` answers per `(adapter LUID, DXGI_FORMAT)`. -static TYPED_UAV_SUPPORT: Mutex>> = Mutex::new(None); +static TYPED_UAV_SUPPORT: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Map sRGB formats (never valid for PC UAVs) to their linear UAV-capable counterparts. pub fn pc_uav_linear_format(fmt: u32) -> u32 { @@ -920,7 +920,7 @@ pub(super) unsafe fn pc_typed_uav_supported(dev_raw: *mut c_void, fmt: i32) -> b }; let luid = dev.GetAdapterLuid(); let key = ((luid.LowPart, luid.HighPart), fmt); - if let Some(&cached) = TYPED_UAV_SUPPORT.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { + if let Some(&cached) = TYPED_UAV_SUPPORT.read().unwrap().as_ref().and_then(|m| m.get(&key)) { return cached; } let mut data = D3D12_FEATURE_DATA_FORMAT_SUPPORT { @@ -932,7 +932,7 @@ pub(super) unsafe fn pc_typed_uav_supported(dev_raw: *mut c_void, fmt: i32) -> b } else { data.Support1.0 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0 != 0 }; - TYPED_UAV_SUPPORT.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, supported); + TYPED_UAV_SUPPORT.write().unwrap().get_or_insert_with(HashMap::new).insert(key, supported); supported } @@ -1722,7 +1722,7 @@ mod tests { assert!(device_format_supports_uav(ptr, 24) && dev.checks == 2); assert!(device_format_supports_uav(ptr, 24) && dev.checks == 2); } - if let Some(m) = UAV_FORMAT_SUPPORT.lock().unwrap().as_mut() { + if let Some(m) = UAV_FORMAT_SUPPORT.write().unwrap().as_mut() { m.remove(&((luid_a.LowPart, luid_a.HighPart), 24)); m.remove(&((luid_b.LowPart, luid_b.HighPart), 24)); } @@ -1761,7 +1761,7 @@ mod tests { get_copyable_footprints_x(&mut dev as *mut FakeAdoptedDev as *mut c_void, x.as_ptr(), 0, 1, 0, std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut(), &mut total); } assert_eq!((dev.calls, dev.last_flags & 4, total), (2, 0, 65536)); - if let Some(m) = UAV_FORMAT_SUPPORT.lock().unwrap().as_mut() { + if let Some(m) = UAV_FORMAT_SUPPORT.write().unwrap().as_mut() { m.remove(&((luid.LowPart, luid.HighPart), 24)); } } diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 8a81aa45ec..7e8606da25 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -44,10 +44,23 @@ impl Held { self.open.is_empty() && self.sealed.is_empty() } + fn needs_seal(&self, seal_now: bool) -> bool { + !self.open.is_empty() && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) + } + + /// Take out the sealed batches every queue is past without touching `open`. + unsafe fn reap(&mut self) -> Vec { + let mut gone = Vec::new(); + while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { + gone.extend(self.sealed.pop_front().unwrap().dead); + } + gone + } + /// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`, /// and take out the batches every queue is past: the resources to release now. unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { - if !self.open.is_empty() && (seal_now || self.last_seal.is_none_or(|t| t.elapsed() >= SEAL_EVERY)) { + if self.needs_seal(seal_now) { let mut marks = Vec::with_capacity(queues.len()); let mut ok = true; for q in queues { @@ -76,11 +89,7 @@ impl Held { self.sealed.push_back(Batch { dead, marks }); } } - let mut gone = Vec::new(); - while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { - gone.extend(self.sealed.pop_front().unwrap().dead); - } - gone + self.reap() } } @@ -95,12 +104,38 @@ pub fn enabled() -> bool { /// how long a last `Release` itself waits for queues with nothing to do to say so const IDLE_WAIT: Duration = Duration::from_micros(300); +fn ensure_thread() { + // A thread of its own lets the held ones go: the title may release a resource and then + // wait for its memory without another submit (an imported heap pins the pages under its + // resources – unmapping them stood still while one was held "until the next submit"). + static THREAD: std::sync::Once = std::sync::Once::new(); + THREAD.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop { + std::thread::sleep(TICK); + unsafe { drain_known(false) }; + }); + }); +} + /// `res` (an adopted resource) holds one reference that is now this module's. With no work in /// flight it goes before this returns (the queues pass a fence value at once): a title that /// frees the memory under a resource right after its last `Release` finds it unpinned, as /// before. Otherwise the thread here lets it go. pub unsafe fn hold(res: usize) { - HELD.lock().unwrap().get_or_insert_with(Held::default).open.push(res); + let busy = { + let mut g = HELD.lock().unwrap(); + let h = g.get_or_insert_with(Held::default); + let busy = !h.sealed.is_empty(); + h.open.push(res); + busy + }; + if busy { + // A sealed batch is already in flight on the GPU: let the background thread batch + // this release into the next SEAL_EVERY signal instead of issuing a per-release + // Signal on every queue and spinning IDLE_WAIT on the caller's thread. + ensure_thread(); + return; + } let start = Instant::now(); drain_known(true); while start.elapsed() < IDLE_WAIT && HELD.lock().unwrap().as_ref().is_some_and(|h| !h.is_empty()) { @@ -110,36 +145,39 @@ pub unsafe fn hold(res: usize) { if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; } - // A thread of its own lets the held ones go: the title may release a resource and then - // wait for its memory without another submit (an imported heap pins the pages under its - // resources – unmapping them stood still while one was held "until the next submit"). - static THREAD: std::sync::Once = std::sync::Once::new(); - THREAD.call_once(|| { - let _ = std::thread::Builder::new().name("xcl-late-release".into()).spawn(|| loop { - std::thread::sleep(TICK); - unsafe { drain_known(false) }; - }); - }); + ensure_thread(); } /// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the /// upload ones. pub unsafe fn drain_known(seal_now: bool) { - if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { - return; - } - let mut queues: Vec = Vec::new(); - for raw in super::present::known_queues() { - let raw = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { - queues.push(q.clone()); + let need_queues = { + let g = HELD.lock().unwrap(); + let Some(h) = g.as_ref() else { return }; + if h.is_empty() { + return; + } + h.needs_seal(seal_now) + }; + let gone = if need_queues { + let mut queues: Vec = Vec::new(); + for raw in super::present::known_queues() { + let raw = raw as *mut c_void; + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { + queues.push(q.clone()); + } + } + queues.extend(super::sparse::queue()); + queues.extend(super::title_textures::upload_queues()); + match HELD.lock().unwrap().as_mut() { + Some(h) => h.drain(&queues, seal_now), + None => return, + } + } else { + match HELD.lock().unwrap().as_mut() { + Some(h) => h.reap(), + None => return, } - } - queues.extend(super::sparse::queue()); - queues.extend(super::title_textures::upload_queues()); - let gone = match HELD.lock().unwrap().as_mut() { - Some(h) => h.drain(&queues, seal_now), - None => return, }; // (outside the lock: a release may end other objects, whose releases come back here) for res in gone { @@ -216,4 +254,16 @@ mod tests { assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]); assert!(held.is_empty()); } + + /// `reap()` only drains completed sealed batches and never prematurely releases `open` items. + #[test] + fn reap_keeps_open_items_and_respects_seal_interval() { + let mut held = Held::default(); + held.last_seal = Some(Instant::now()); + held.open.push(0x2000); + assert!(!held.needs_seal(false), "within SEAL_EVERY: batching defers sealing"); + assert!(held.needs_seal(true), "explicit seal_now seals immediately"); + assert!(unsafe { held.reap() }.is_empty()); + assert_eq!(held.open, vec![0x2000]); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 06b807e4ad..f5011b7ed2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -382,7 +382,7 @@ unsafe fn open_uma(device: &ID3D12Device) { pub fn stats() -> D3d12Stats { let classes = CLASSES - .lock() + .read() .map(|g| { g.iter() .map(|c| ClassStat { interface: c.iface.name.to_string(), public_methods: c.public, internal_slots: c.scanned - c.public }) @@ -665,7 +665,7 @@ struct Class { scanned: usize, } -static CLASSES: Mutex> = Mutex::new(Vec::new()); +static CLASSES: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); static EXTS: std::sync::RwLock>> = std::sync::RwLock::new(None); unsafe fn vt(obj: *mut c_void) -> *const usize { @@ -728,7 +728,7 @@ fn is_ext(v: usize) -> bool { } fn kind_of(ext: usize) -> Option { - CLASSES.lock().unwrap().iter().find(|c| c.ext == ext).map(|c| c.kind) + CLASSES.read().unwrap().iter().find(|c| c.ext == ext).map(|c| c.kind) } /// If a native D3D12 method (such as `Close` or `Reset` on Agility SDK 1.620+, or copy-list @@ -771,8 +771,8 @@ pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { } unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { - if let Some(c) = CLASSES.lock().unwrap().iter().find(|c| c.orig == orig && c.kind == kind) { - return c.ext; + if let Some(ext) = CLASSES.read().unwrap().iter().find(|c| c.orig == orig && c.kind == kind).map(|c| c.ext) { + return ext; } let ot = orig as *const usize; // most derived PC interface this object implements @@ -886,7 +886,7 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { scanned - public, crate::modules::describe_address(orig) ); - CLASSES.lock().unwrap().push(Class { orig, kind, ext, iface, public, scanned }); + CLASSES.write().unwrap().push(Class { orig, kind, ext, iface, public, scanned }); ext } @@ -1467,10 +1467,10 @@ fn has_coherent_headroom(u: &crate::gpu::uma::Uma, rounded: usize) -> bool { /// Sparse-backed buffers whose `Map(0, NULL, ...)` should read back their full range from VRAM /// (readback buffers that spilled to sparse VRAM or `COPY_DEST` buffers in `CUSTOM + WRITE_BACK`). -static SPARSE_READBACK: Mutex>> = Mutex::new(None); +static SPARSE_READBACK: std::sync::RwLock>> = std::sync::RwLock::new(None); fn note_sparse_readback(res: usize) { - SPARSE_READBACK.lock().unwrap().get_or_insert_with(HashSet::new).insert(res); + SPARSE_READBACK.write().unwrap().get_or_insert_with(HashSet::new).insert(res); } /// Whether `props` asks for CPU-cached readback memory. On Xbox UMA, `D3D12_HEAP_TYPE_CUSTOM` @@ -1690,14 +1690,14 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v super::sparse::readback_now(p + begin, end - begin); } } - } else if SPARSE_READBACK.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { + } else if SPARSE_READBACK.read().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { super::sparse::readback_now(p, bytes); } } if !data.is_null() { *data = p as *mut c_void; } - UNMAPPABLE.lock().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); + UNMAPPABLE.write().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); return S_OK; } // the PC's Map only on a resource it can map: on a reserved one or one without CPU pages it is @@ -1716,7 +1716,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v if !data.is_null() { *data = p as *mut c_void; } - UNMAPPABLE.lock().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); + UNMAPPABLE.write().unwrap().get_or_insert_with(HashSet::new).insert(this as usize); S_OK } None => { @@ -1765,10 +1765,10 @@ pub(super) fn note_title_address(res: usize, va: usize) { } /// resources whose Map gave their unified-memory address (no PC mapping to undo) -static UNMAPPABLE: Mutex>> = Mutex::new(None); +static UNMAPPABLE: std::sync::RwLock>> = std::sync::RwLock::new(None); unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c_void) { - if UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { + if UNMAPPABLE.read().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { return; } let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, slot_of(this, "Unmap"))); @@ -1795,13 +1795,13 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { f(this) }; if n == 0 { - if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { + if let Some(s) = UNMAPPABLE.write().unwrap().as_mut() { s.remove(&(this as usize)); } - if let Some(s) = SPARSE_READBACK.lock().unwrap().as_mut() { + if let Some(s) = SPARSE_READBACK.write().unwrap().as_mut() { s.remove(&(this as usize)); } - if let Some(s) = RESERVED.lock().unwrap().as_mut() { + if let Some(s) = RESERVED.write().unwrap().as_mut() { s.remove(&(this as usize)); } if let Some(m) = BUFFER_DELTA.write().unwrap().as_mut() { @@ -1866,42 +1866,42 @@ unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { static TRANSLATED_COMPUTE: Mutex>> = Mutex::new(None); /// graphics pipelines built from translated console shaders -static TRANSLATED_GRAPHICS: Mutex>> = Mutex::new(None); +static TRANSLATED_GRAPHICS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Whether `pso` is a graphics pipeline of translated console shaders. /// `XCL_TRACE_FRAME`: the console VS and PS (their dump names' hashes) of a translated PSO. -static PSO_SHADERS: Mutex>> = Mutex::new(None); +static PSO_SHADERS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// translated pipeline → its input layout as text (`XCL_TRACE_FRAME`) -static PSO_LAYOUTS: Mutex>> = Mutex::new(None); +static PSO_LAYOUTS: std::sync::RwLock>> = std::sync::RwLock::new(None); pub fn pso_layout(pso: usize) -> Option { - PSO_LAYOUTS.lock().unwrap().as_ref()?.get(&pso).cloned() + PSO_LAYOUTS.read().unwrap().as_ref()?.get(&pso).cloned() } pub fn pso_shaders(pso: usize) -> Option<(u64, u64)> { - PSO_SHADERS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_SHADERS.read().unwrap().as_ref()?.get(&pso).copied() } pub fn is_translated_graphics(pso: usize) -> bool { - pso != 0 && TRANSLATED_GRAPHICS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && TRANSLATED_GRAPHICS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } /// graphics pipelines given the generated rect list GS (`rect_list_gs`) -static RECT_LIST_GS: Mutex>> = Mutex::new(None); +static RECT_LIST_GS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Whether `pso` (as `is_translated_graphics` takes it: a stand-in resolved) draws rect lists /// whole with the generated GS. Its draws must not be expanded to two triangles a rect as well: /// each half is three corners of the rect and the GS would complete both. pub fn has_rect_list_gs(pso: usize) -> bool { - pso != 0 && RECT_LIST_GS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && RECT_LIST_GS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } /// Note `pso`, made from `copy`, if it kept the generated rect list GS (`rect_gs`; a pipeline /// made again without it, `retry_without_rect_gs`, did not). fn note_rect_list_gs(pso: usize, copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool) { if pso != 0 && rect_gs && !copy.GS.pShaderBytecode.is_null() { - RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + RECT_LIST_GS.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } @@ -1991,24 +1991,24 @@ pub fn is_translated_compute(pso: usize) -> bool { /// compute pipelines the title made from a console shader that runs untranslated: a background /// build's stand-in (until it is resolved) and the fallback of a console shader that failed -static CONSOLE_COMPUTE: Mutex>> = Mutex::new(None); +static CONSOLE_COMPUTE: std::sync::RwLock>> = std::sync::RwLock::new(None); unsafe fn note_console_compute(hr: HRESULT, ppv: *mut *mut c_void) { if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - CONSOLE_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + CONSOLE_COMPUTE.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } } /// Whether `pso` was made from a console compute shader (translated or not); a native PC /// compute pipeline is not. pub fn is_console_compute(pso: usize) -> bool { - pso != 0 && CONSOLE_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && CONSOLE_COMPUTE.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } #[cfg(test)] pub(super) fn register_console_compute_for_test(pso: usize) { if pso != 0 { - CONSOLE_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + CONSOLE_COMPUTE.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } @@ -2022,14 +2022,14 @@ pub(super) fn register_translated_compute_for_test(pso: usize) { #[cfg(test)] pub(super) fn register_rect_list_gs_for_test(pso: usize) { if pso != 0 { - RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + RECT_LIST_GS.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } #[cfg(test)] pub(super) fn register_translated_graphics_for_test(pso: usize) { if pso != 0 { - TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } @@ -2044,16 +2044,16 @@ fn forget_pso(pso: usize) { if let Some(s) = TRANSLATED_COMPUTE.lock().unwrap().as_mut() { s.remove(&pso); } - if let Some(s) = CONSOLE_COMPUTE.lock().unwrap().as_mut() { + if let Some(s) = CONSOLE_COMPUTE.write().unwrap().as_mut() { s.remove(&pso); } - if let Some(s) = TRANSLATED_GRAPHICS.lock().unwrap().as_mut() { + if let Some(s) = TRANSLATED_GRAPHICS.write().unwrap().as_mut() { s.remove(&pso); } - if let Some(s) = RECT_LIST_GS.lock().unwrap().as_mut() { + if let Some(s) = RECT_LIST_GS.write().unwrap().as_mut() { s.remove(&pso); } - if let Some(m) = PSO_RS.lock().unwrap().as_mut() { + if let Some(m) = PSO_RS.write().unwrap().as_mut() { m.remove(&pso); } if let Some(m) = PSO_USER_SGPRS.lock().unwrap().as_mut() { @@ -3143,7 +3143,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { /// Slot of `method` in the class of an adopted object. unsafe fn slot_of(this: *mut c_void, method: &str) -> usize { let ext = vt(this) as usize; - let g = CLASSES.lock().unwrap(); + let g = CLASSES.read().unwrap(); let c = g.iter().find(|c| c.ext == ext).expect("adopted class"); layout::slot(c.iface, method).expect("method in layout") } @@ -3613,7 +3613,7 @@ creator!(pc_create_reserved_resource1, "CreateReservedResource1", Kind::Resource /// `res_map` asks none of them (GetHeapProperties on one is an invalid call too, debug layer /// 901). The description guards against an address a later resource reuses without the last /// Release having been seen. -static RESERVED: Mutex>> = Mutex::new(None); +static RESERVED: std::sync::RwLock>> = std::sync::RwLock::new(None); unsafe fn desc_of(res: *mut c_void) -> Option { ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()) @@ -3622,14 +3622,14 @@ unsafe fn desc_of(res: *mut c_void) -> Option { pub(super) unsafe fn note_reserved(hr: HRESULT, ppv: *mut *mut c_void) -> HRESULT { if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { if let Some(d) = desc_of(*ppv) { - RESERVED.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, d); + RESERVED.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, d); } } hr } unsafe fn is_reserved(res: *mut c_void) -> bool { - let kept = RESERVED.lock().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()); + let kept = RESERVED.read().unwrap().as_ref().and_then(|m| m.get(&(res as usize)).copied()); kept.is_some_and(|k| desc_of(res) == Some(k)) } @@ -3706,7 +3706,7 @@ struct HeapUma { /// heap → its backing block (allocated lazily on the first placed buffer; sparse VRAM for /// DEFAULT/UPLOAD/CUSTOM heaps, coherent committed window for small explicit READBACK heaps) -static HEAP_UMA: Mutex>> = Mutex::new(None); +static HEAP_UMA: std::sync::RwLock>> = std::sync::RwLock::new(None); /// A heap the title made that may hold buffers: a block of unified memory as large stands for /// it. On the console every heap is memory the CPU and the GPU address alike, and console code @@ -3729,7 +3729,7 @@ unsafe fn note_heap_uma(desc: usize, ppv: *mut *mut c_void) { let size = d.SizeInBytes as usize; let is_rb = d.Properties.Type == D3D12_HEAP_TYPE_READBACK; let is_custom_wb = d.Properties.Type == D3D12_HEAP_TYPE_CUSTOM && d.Properties.CPUPageProperty == D3D12_CPU_PAGE_PROPERTY_WRITE_BACK; - HEAP_UMA.lock().unwrap().get_or_insert_with(HashMap::new).insert( + HEAP_UMA.write().unwrap().get_or_insert_with(HashMap::new).insert( *ppv as usize, HeapUma { size, @@ -3745,7 +3745,7 @@ unsafe fn note_heap_uma(desc: usize, ppv: *mut *mut c_void) { /// (taken now if it has none yet; None: not a heap that takes one, or unified memory is full). fn heap_block(heap: usize) -> Option<(usize, bool)> { let (size, align, prefer_coherent, cpu_readback) = { - let g = HEAP_UMA.lock().unwrap(); + let g = HEAP_UMA.read().unwrap(); let e = g.as_ref()?.get(&heap)?; if let Some(p) = e.block { return Some((p, e.cpu_readback)); @@ -3775,7 +3775,7 @@ fn heap_block(heap: usize) -> Option<(usize, bool)> { } return None; }; - let mut g = HEAP_UMA.lock().unwrap(); + let mut g = HEAP_UMA.write().unwrap(); let Some(e) = g.as_mut().and_then(|m| m.get_mut(&heap)) else { drop(g); if u.is_sparse(p) { @@ -3810,7 +3810,7 @@ unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); let n = f(this); if n == 0 { - let gone = HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block); + let gone = HEAP_UMA.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block); if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { if u.is_sparse(p) { super::sparse::free(p); @@ -4153,11 +4153,11 @@ unsafe fn shader_bytes<'a>(b: &D3D12_SHADER_BYTECODE) -> Option<&'a [u8]> { /// Root signature of every pipeline built from translated console shaders (static samplers /// make it per pipeline): the draw binds it instead of the title's. -static PSO_RS: Mutex>> = Mutex::new(None); +static PSO_RS: std::sync::RwLock>> = std::sync::RwLock::new(None); fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { if !pso.is_null() { - PSO_RS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, rs as usize); + PSO_RS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso as usize, rs as usize); } } @@ -4174,11 +4174,11 @@ pub fn pso_user_sgprs(pso: usize) -> Option { /// The root signature a translated pipeline state was created with. pub fn pso_root_signature(pso: usize) -> Option { let pso = super::pso_async::resolve(pso); - PSO_RS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_RS.read().unwrap().as_ref()?.get(&pso).copied() } /// ABI root signatures with static samplers, by sampler set (owned here, never released). -static ABI_RS_SAMPLERS: Mutex, usize>>> = Mutex::new(None); +static ABI_RS_SAMPLERS: std::sync::RwLock, usize>>> = std::sync::RwLock::new(None); /// The XCL ABI root signature with a pipeline's static samplers (the plain one without). unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> Option<*mut c_void> { @@ -4186,7 +4186,10 @@ unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::Sta return abi_rs_raw(this); } let key: Vec = samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect(); - let mut g = ABI_RS_SAMPLERS.lock().unwrap(); + if let Some(&rs) = ABI_RS_SAMPLERS.read().unwrap().as_ref().and_then(|m| m.get(&key)) { + return Some(rs as *mut c_void); + } + let mut g = ABI_RS_SAMPLERS.write().unwrap(); let map = g.get_or_insert_with(HashMap::new); if let Some(&rs) = map.get(&key) { return Some(rs as *mut c_void); @@ -5610,11 +5613,11 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); - TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); if super::present::trace_frame() { let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); - PSO_SHADERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); + PSO_SHADERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); // the input layout (semantic index, format, slot, offset) – what the vertices are read as let il = &d.InputLayout; let elems: Vec = if il.NumElements > 0 && !il.pInputElementDescs.is_null() { @@ -5625,7 +5628,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } else { Vec::new() }; - PSO_LAYOUTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, elems.join(", ")); + PSO_LAYOUTS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, elems.join(", ")); static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 400 { let b = &d.BlendState.RenderTarget[0]; @@ -8779,9 +8782,9 @@ mod map_tests { // is not taken for it (its description differs) let upload = buffer(heap(D3D12_HEAP_TYPE_UPLOAD), D3D12_RESOURCE_STATE_GENERIC_READ); let stale = desc_of(r.as_raw()).unwrap(); - RESERVED.lock().unwrap().as_mut().unwrap().insert(upload.as_raw() as usize, stale); + RESERVED.write().unwrap().as_mut().unwrap().insert(upload.as_raw() as usize, stale); assert!(!is_reserved(upload.as_raw()) && mappable(&upload)); - let mut g = RESERVED.lock().unwrap(); + let mut g = RESERVED.write().unwrap(); let m = g.as_mut().unwrap(); m.remove(&(raw as usize)); m.remove(&(upload.as_raw() as usize)); @@ -8958,13 +8961,13 @@ mod mesh_stream_tests { } impl Drop for Cleanup { fn drop(&mut self) { - CLASSES.lock().unwrap().retain(|c| c.ext != self.ext); - if let Some(m) = ABI_RS_SAMPLERS.lock().unwrap().as_mut() { + CLASSES.write().unwrap().retain(|c| c.ext != self.ext); + if let Some(m) = ABI_RS_SAMPLERS.write().unwrap().as_mut() { m.remove(&self.key); } } } - CLASSES.lock().unwrap().push(Class { + CLASSES.write().unwrap().push(Class { orig: pc.as_ptr() as usize, kind: Kind::Device, ext: ext_vtbl, @@ -8972,7 +8975,7 @@ mod mesh_stream_tests { public: iface.methods.len(), scanned: iface.methods.len(), }); - ABI_RS_SAMPLERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(key.clone(), 0x1234_5678); + ABI_RS_SAMPLERS.write().unwrap().get_or_insert_with(HashMap::new).insert(key.clone(), 0x1234_5678); let _cleanup = Cleanup { ext: ext_vtbl, key }; let make_tp = || crate::gpu::recomp::pso::TwoPass { From 6bc17a907b4ae51e2322a14fea0f98de611d3b2a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:04:03 +0100 Subject: [PATCH 078/258] D3D12.X: per-draw mirror sync copies without readable() VirtualQuery Port upstream PR #2437 (by KOLESNiii, commit bb9bea21) onto amd-dev. sync_title_buffers checked every copy's source and scanned indices with gpu::shader::readable. For a range with a non-resident page or over 16 pages, that walked the region with VirtualQuery, stalling the render thread for 1.1-8.8 ms inside draws (#2389 / #2392). Use title_textures::copy_committed_region (ReadProcessMemory, which cannot fault) so freed or protected pages keep what the mirror already holds, and scan indices from the index buffer's mirror once copied (keeping readable() only when an index buffer has no mirror). Includes regression test. Fixes #2392. Part of #2389. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/list_x.rs | 70 ++++++++++++++++++--- crates/xcl/src/hle/d3d12x/title_textures.rs | 2 +- 2 files changed, 64 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 0fa07a2fdd..7273c4fe2b 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3783,11 +3783,14 @@ pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, } v }; + // (no `readable` first – for a range not resident or over 16 pages it walks the region with + // `VirtualQuery`, a 1–9 ms stall of the render thread (#2392): the copy cannot fault, and a + // page the title freed or protected since keeps what the mirror had) let copy = |va: u64, mirror: usize, bytes: u32, from: u64, len: u64| { let from = from.min(bytes as u64); let len = len.min(bytes as u64 - from) as usize; - if len > 0 && crate::gpu::shader::readable(va as usize + from as usize, len) { - std::ptr::copy_nonoverlapping((va + from) as *const u8, (mirror + from as usize) as *mut u8, len); + if len > 0 { + super::title_textures::copy_committed_region((va + from) as usize, (mirror + from as usize) as *mut u8, len); } }; // the vertices read: [lo, hi) @@ -3795,14 +3798,20 @@ pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, (Some((first, count, base)), Some((va, bytes, format))) => { let size: u64 = if format == DXGI_FORMAT_R32_UINT.0 { 4 } else { 2 }; let (from, len) = (first as u64 * size, count as u64 * size); - if let Some(m) = mirrors[vbs.len()] { - copy(va, m, bytes, from, len); - } let n = (len.min((bytes as u64).saturating_sub(from)) / size) as usize; - if n == 0 || !crate::gpu::shader::readable((va + from) as usize, n * size as usize) { + // the indices are read from the mirror once copied there, which is readable whatever + // the title did to its memory; an index buffer without a mirror is checked + let at = match mirrors[vbs.len()] { + Some(m) => { + copy(va, m, bytes, from, len); + Some(m + from as usize) + } + None => (n > 0 && crate::gpu::shader::readable((va + from) as usize, n * size as usize)).then_some((va + from) as usize), + }; + if n == 0 || at.is_none() { (0, u64::MAX) } else { - let at = (va + from) as *const u8; + let at = at.unwrap() as *const u8; let (mut lo, mut hi) = (u32::MAX, 0u32); for k in 0..n { let i = if size == 4 { at.add(4 * k).cast::().read_unaligned() } else { at.add(2 * k).cast::().read_unaligned() as u32 }; @@ -7282,6 +7291,53 @@ mod tests { } } + /// The per-draw sync copies a mirrored vertex buffer without asking `readable` (#2392): with + /// one page of it made unreadable after the mirror was made, the draw's other pages are + /// still brought up to date and the unreadable one keeps what the mirror had, and the + /// vertex range comes from the indices as the title wrote them (read from their mirror). + /// Before, `readable` failed for the whole range and nothing was copied. + #[test] + fn the_mirror_sync_copies_around_a_page_the_title_made_unreadable() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect, MEM_COMMIT, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + if crate::gpu::uma::get().is_none() { + crate::gpu::recomp::runner::skip_test("no unified memory"); + return; + } + unsafe { + let len = 0x1_0000usize; + let vb = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + let ib = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u16; + assert!(!vb.is_null() && !ib.is_null()); + let (vb_bytes, stride) = (0x3000u32, 16u32); + std::ptr::write_bytes(vb, 0x11, vb_bytes as usize); + for (k, i) in [0u16, 1, 2].into_iter().enumerate() { + *ib.add(k) = i; + } + let list = 0x7e57_0000_2392usize as *mut c_void; + assert_ne!(gpu_va(list, vb as u64, vb_bytes as usize, "test vertex buffer", true), vb as u64); + assert_ne!(gpu_va(list, ib as u64, 6, "test index buffer", true), ib as u64); + let vm = mirrored(vb as u64, vb_bytes as usize).unwrap() as *const u8; + with_bindings(list, |b| { + b.vertex_titles.insert(0, (vb as u64, vb_bytes, stride)); + b.index_title = Some((ib as u64, 6, DXGI_FORMAT_R16_UINT.0)); + }); + // the title writes new vertices on all three pages and indices that reach them, then + // makes the middle page unreadable + std::ptr::write_bytes(vb, 0x22, vb_bytes as usize); + for (k, i) in [0u16, 0x1000 / 16, (vb_bytes / stride - 1) as u16].into_iter().enumerate() { + *ib.add(k) = i; + } + let mut old = 0u32; + assert_ne!(VirtualProtect(vb.add(0x1000) as *const _, 0x1000, PAGE_NOACCESS, &mut old), 0); + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 1); + assert!((0..0x1000).all(|k| *vm.add(k) == 0x22), "the first page is copied"); + assert!((0x1000..0x2000).all(|k| *vm.add(k) == 0x11), "the unreadable page keeps the mirror's bytes"); + assert!((0x2000..0x3000).all(|k| *vm.add(k) == 0x22), "the last page, reached by the last index, is copied"); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + // (the ranges stay allocated: the mirror table is never emptied) + } + } + #[test] fn occlusion_tracks_dropped_draws_and_active_counter() { let mut occ = Occlusion::default(); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index a40387f660..cc6c1df8c0 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1464,7 +1464,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 stay 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; From d5012900903fbc0592e80cdc3efc68e5ac808380 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:05:19 +0100 Subject: [PATCH 079/258] D3D12.X: pack sub-64 KiB sampled textures into 4 KiB-aligned VRAM heaps Port upstream PR #1835 (commits 2441d594..5005620c) cleanly onto amd-dev with #2436 reserved-texture recycling and #2306 lazy levels. Small sampled textures (< 64 KiB) previously each consumed a full 64 KiB tile plus CreateReservedResource, GetResourceTiling, and UpdateTileMappings overhead. Pack eligible sub-64 KiB sampled textures (when not aliasing an existing live 64 KiB GPU-owned page) into shared 4 KiB-aligned 4 MiB default heaps via CreatePlacedResource in vram_small.rs, reclaiming their 4 KiB slots on release in vram::forget_for_recycle before falling through to reserved-page recycling. Fixes #1835. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/title_textures.rs | 49 +- crates/xcl/src/hle/d3d12x/vram.rs | 69 ++- crates/xcl/src/hle/d3d12x/vram_small.rs | 601 ++++++++++++++++++++ 4 files changed, 705 insertions(+), 15 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/vram_small.rs diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 17fd7c471a..89f95b8040 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -37,6 +37,7 @@ mod standin; pub mod title_list; pub mod title_textures; pub mod vram; +mod vram_small; use std::ffi::c_void; use std::sync::OnceLock; diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index cc6c1df8c0..36d077e04c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2209,6 +2209,15 @@ mod tests { assert!(tbl.by_res.contains_key(&10) && tbl.by_res.contains_key(&11)); assert_eq!(tbl.insert(12, entry(0x20_0000, &tex_64k, true, false)), (-1, vec![])); assert!(!tbl.by_res.contains_key(&10) && !tbl.by_res.contains_key(&11) && tbl.by_res.contains_key(&12)); + // Unaligned 88 KiB mip-chain siblings at +0x4000 own page +0x1_0000 plus 1 extra_page; + // an aligned 64 KiB cover at +0x1_0000 supersedes both without allocating a new base page. + let tex_88k = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 8, 28, 0x105)).unwrap()); + assert_eq!(tex_88k.size(), 0x1_6000); + assert_eq!(tbl.insert(30, entry(0x30_4000, &tex_88k, true, true)), (1, vec![])); + assert_eq!(tbl.insert(31, entry(0x30_4000, &tex_88k, true, true)), (0, vec![])); + let (_, mut unmap_unaligned) = tbl.insert(32, entry(0x31_0000, &tex_64k, true, true)); + unmap_unaligned.sort_unstable(); + assert_eq!(unmap_unaligned, vec![30, 31]); } /// Real GPU (#248): placed title textures share `vram::Pages` so streaming unreleased @@ -2345,6 +2354,7 @@ mod tests { // 1. Streaming 512 unreleased 1 MiB textures (512 MiB placed) across 16 MiB stays bounded // with zero additional page growth after the 16 MiB working set is covered. let dev_key = dev.as_raw() as usize; + super::super::vram::flush_idle_for(dev_key); let dev_pages = || super::super::vram::page_bytes_for(dev_key).0; let stream_desc = console_desc(3, 512, 512, 1, 1, 28, 0x109); // 64KB_S, 1 MiB let (pages0, vram0, kept0) = (dev_pages(), local_vram(), counts().0); @@ -2414,10 +2424,13 @@ mod tests { assert_eq!(read_sub(&old_res, 0), subresources(base, &xg::Texture::new(&old_desc).unwrap())[0].data, "reactivated unmapped texture remapped cleanly"); drop(old_res); - // 3. 4 KiB-aligned adjacent textures inside one 64 KiB page + straddling page boundary, - // plus reclaiming dead extra_pages when overwritten by a larger placement without Release. + // 3. 4 KiB-aligned adjacent small textures pack into 4 KiB sub-allocated slots (no 64 KiB + // bloat per small texture), reuse the exact slot at the same va without crosstalk, and + // >= 64 KiB unaligned textures reclaim dead extra_pages immediately when overwritten. + super::super::vram::flush_idle_for(dev_key); let d16 = console_desc(3, 64, 64, 1, 1, 28, 0x105); // 4KB_S, 16 KiB let d64 = console_desc(3, 128, 128, 1, 1, 28, 0x105); // 4KB_S, 64 KiB + let adj_base_pages = dev_pages(); let adj_specs = [(0x0000usize, d16, 0x11u8), (0x4000, d16, 0x22), (0x8000, d16, 0x33), (0xC000, d64, 0x44), (0x1_C000, d16, 0x55)]; let adj: Vec<_> = adj_specs.iter().map(|&(off, d, _)| place_tex(base + off, &d)).collect(); for &(off, d, seed) in &adj_specs { @@ -2428,17 +2441,37 @@ mod tests { assert_eq!(read_sub(r, 0), subresources(base + off, &xg::Texture::new(&d).unwrap())[0].data, "4 KiB neighbour at +{off:#x} crosstalk"); } let pages_before_reuse = dev_pages(); + let adj_delta = pages_before_reuse - adj_base_pages; + assert!(adj_delta <= 128 * 1024, "four 16 KiB + one 64 KiB textures should use <= 128 KiB, got {adj_delta} B"); let reused = place_tex(base + 0x4000, &d16); - assert_eq!(dev_pages(), pages_before_reuse, "reusing unaligned va must share extra_pages tile"); - // Overwrite the first 64 KiB (covering +0x0000, +0x4000 (both adj[1] & reused), +0x8000, +0xC000) - // WITHOUT releasing adj/reused: dead extra_pages (+0x4000, +0x8000) must drop immediately! - let cover = place_tex(base, &d64); + assert_eq!(dev_pages(), pages_before_reuse, "reusing unaligned va must share backing slot"); + drop((reused, adj)); + + // Reclaiming dead extra_pages immediately when a >= 64 KiB unaligned tiled texture is + // overwritten by an overlapping placement without Release: + // `unaligned_a`/`b` at `base + 0x4000` (88 KiB, 2 tiles) own page `base + 0x1_0000` + // plus 1 `extra_pages` tile; `cover` at `base + 0x1_0000` reuses that already-live + // owned page (+0 new pages) while superseding both unaligned siblings and reclaiming + // their `extra_pages` tile immediately (-64 KiB). + super::super::vram::flush_idle_for(dev_key); + let d64_mips = console_desc(3, 128, 128, 1, 8, 28, 0x105); // 88 KiB, 2 tiles (mip 0 + packed mips) + let extra_before = super::super::vram::extra_page_bytes_for(dev_key); + let unaligned_a = place_tex(base + 0x4000, &d64_mips); + let extra_after_a = super::super::vram::extra_page_bytes_for(dev_key); + assert!(extra_after_a > extra_before, "unaligned >= 64 KiB tiled texture must allocate extra_pages ({extra_before} -> {extra_after_a})"); + let unaligned_b = place_tex(base + 0x4000, &d64_mips); + assert_eq!(super::super::vram::extra_page_bytes_for(dev_key), extra_after_a, "reusing unaligned va must share extra_pages tile"); + let pages_with_extra = dev_pages(); + let cover = place_tex(base + 0x1_0000, &d64); let pages_after_cover = dev_pages(); - assert!(pages_after_cover < pages_before_reuse, "superseded unaligned extra_pages must be reclaimed immediately ({pages_before_reuse} -> {pages_after_cover})"); - drop((cover, reused, adj)); + let extra_after_cover = super::super::vram::extra_page_bytes_for(dev_key); + assert_eq!(extra_after_cover, extra_before, "superseded unaligned extra_pages must drop back to baseline ({extra_after_a} -> {extra_after_cover})"); + assert!(pages_after_cover < pages_with_extra, "superseded unaligned extra_pages must be reclaimed immediately ({pages_with_extra} -> {pages_after_cover})"); + drop((cover, unaligned_b, unaligned_a)); // 4. Full mip chain (standard + packed mips, RGBA8 & BC7), tiny all-packed mips, // 6-slice cubemap (exercises extra_pages reuse), and 3D volume texture (Tier 3). + super::super::vram::flush_idle_for(dev_key); let shapes = [ ("2D 512x512 RGBA8 10 mips", console_desc(3, 512, 512, 1, 10, 28, 0x109)), ("2D 1024x1024 BC7 11 mips", console_desc(3, 1024, 1024, 1, 11, 98, 0x109)), diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5f904b2cbd..0be8c4affc 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -256,7 +256,11 @@ pub(super) fn forget_for_recycle(resource: usize, held: bool) -> Option = Mutex::new(()); +/// Whether `va` already has a live (or still within `IDLE`) 64 KiB page on `device` (e.g., an +/// existing GPU-owned render target that a sampled view at the same 64 KiB-aligned address should +/// alias). +fn has_live_page(device: usize, va: usize) -> bool { + let g = PAGES.lock().unwrap(); + let now = std::time::Instant::now(); + g.get(&device) + .and_then(|p| p.as_ref()) + .is_some_and(|p| p.pages.get(&va).is_some_and(|pg| pg.idle_since.is_none_or(|s| now.duration_since(s) < IDLE))) +} + #[cfg(test)] pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { - let g = PAGES.lock().unwrap(); - let Some(Some(p)) = g.get(&device) else { return (0, 0) }; - ((p.pages.len() + p.extra_pages.len()) * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) + let (su, sp) = super::vram_small::bytes_for(device); + let mut g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get_mut(&device) else { return (su, sp) }; + p.sweep(std::time::Instant::now()); + ((p.pages.len() + p.extra_pages.len()) * PAGE + su, p.pools.len() * POOL_PAGES as usize * PAGE + sp) +} + +#[cfg(test)] +pub(super) fn extra_page_bytes_for(device: usize) -> usize { + let mut g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get_mut(&device) else { return 0 }; + p.sweep(std::time::Instant::now()); + p.extra_pages.len() * PAGE +} + +/// Immediately evict all unreferenced idle pages and small-pool slots on `device` so GPU tests +/// sharing the process's singleton `ID3D12Device` do not observe stale `IDLE` expiries mid-test. +#[cfg(test)] +pub(super) fn flush_idle_for(device: usize) { + super::vram_small::flush_idle_for(device); + let mut g = PAGES.lock().unwrap(); + if let Some(Some(p)) = g.get_mut(&device) { + let now = std::time::Instant::now(); + while let Some((key, since)) = p.idle.pop_front() { + let still_idle = |pg: &Page| pg.idle_since == Some(since); + let page = match key { + PageKey::Own(a) if p.pages.get(&a).is_some_and(still_idle) => p.pages.remove(&a), + PageKey::Extra(va, i) if p.extra_pages.get(&(va, i)).is_some_and(still_idle) => p.extra_pages.remove(&(va, i)), + _ => None, + }; + if let Some(pg) = page { + p.pool.push_cooling(pg.tile, now); + } + } + } } /// (bytes of pages in use by tiled textures, bytes of pool heaps) – `XCL_ACTIVITY` pub fn page_bytes() -> (usize, usize) { + let (su, sp) = super::vram_small::bytes(); let g = PAGES.lock().unwrap(); - g.values().flatten().fold((0, 0), |(used, pools), p| { + g.values().flatten().fold((su, sp), |(used, pools), p| { (used + (p.pages.len() + p.extra_pages.len()) * PAGE, pools + p.pools.len() * POOL_PAGES as usize * PAGE) }) } @@ -1813,8 +1861,9 @@ fn tier2(dev: &ID3D12Device) -> bool { } /// A sampled texture of the title at `va` (`desc`: the PC description, `console_bytes` its size on -/// the console) backed by shared 64 KiB video-memory pages; None when reserved placement is not -/// available (the caller falls back to a committed resource). +/// the console) backed by shared 4 KiB small-resource heaps (when < 64 KiB and not aliasing an +/// existing 64 KiB GPU page) or shared 64 KiB video-memory pages; None when neither applies (the +/// caller falls back to a committed resource). #[allow(clippy::too_many_arguments)] pub unsafe fn place_pages( this: *mut c_void, @@ -1833,6 +1882,12 @@ pub unsafe fn place_pages( if console_has_packed_3d_mips(desc) { return None; } + if !(va % PAGE == 0 && has_live_page(dev.as_raw() as usize, canonical_va(va))) { + if let Some(hr) = super::vram_small::place(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { + PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + return Some(hr); + } + } // (one slice: the tiles of an array's packed levels are not asked about here) let lazy = level_pages() && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.DepthOrArraySize == 1 && desc.SampleDesc.Count == 1 && desc.Flags == D3D12_RESOURCE_FLAG_NONE; place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, lazy, riid, ppv) diff --git a/crates/xcl/src/hle/d3d12x/vram_small.rs b/crates/xcl/src/hle/d3d12x/vram_small.rs new file mode 100644 index 0000000000..e33ec692bd --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/vram_small.rs @@ -0,0 +1,601 @@ +//! 4 KiB sub-allocated default heaps for small (< 64 KiB) sampled textures. +//! +//! A console title packs thousands of small mip-tails, icons, decals and LUTs at 256 B – 4 KiB +//! offsets inside its texture pools. Backing each one with a 64 KiB reserved resource in +//! `vram::Pages` wastes up to 16× video memory (one full 64 KiB `extra_pages` tile per small +//! texture) and submits a `CreateReservedResource` + `GetResourceTiling` + `UpdateTileMappings` +//! round trip for every placement. +//! +//! Direct3D 12 supports 4 KiB placement (`D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT`) for +//! single-sample non-RT/DS textures whose allocation info fits under 64 KiB. Placing those in +//! shared 16 MiB default heaps packs up to 4 096 textures into one heap with zero tile mappings, +//! shares the exact `(heap, offset)` across repeated placements at the same `(va, size)` so +//! same-address aliases see each other's uploads, and recycles released blocks by size class +//! after `IDLE` + `COOL`. `XCL_VRAM_SMALL=0` disables this path. + +use std::collections::{BTreeMap, HashMap, VecDeque}; +use std::ffi::c_void; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; + +use crate::util::HRESULT; + +/// Allocation unit: 4 KiB (`D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT`). +const UNIT: usize = 0x1000; +/// Largest small-resource size handled here: 60 KiB (`15 * 4 KiB < 64 KiB`). +const MAX_UNITS: u32 = 15; +/// Units per shared default heap: 16 MiB (`4096 * 4 KiB`). +const POOL_UNITS: u32 = 4096; +/// Keep an unreferenced `(va, units)` slot this long so immediate re-placements reuse it. +const IDLE: Duration = Duration::from_secs(2); +/// Wait before reusing a freed block for a different address (in-flight GPU work). +const COOL: Duration = Duration::from_secs(2); + +/// Key identifying a shared small-texture backing slot: `(title_va, size_in_4k_units)`. +type SlotKey = (usize, u32); + +/// Block location inside a device's small pools: `(pool_index, offset_in_4k_units, size_in_4k_units)`. +type Block = (u32, u32, u32); + +struct Pool { + heap: H, + /// Bump pointer in 4 KiB units (`0..=POOL_UNITS`). + next_unit: u32, +} + +struct Slot { + pool: u32, + offset: u32, + users: u32, + idle_since: Option, +} + +struct SmallPools { + pools: Vec>, + /// Per-size-class (`1..=MAX_UNITS`) reusable blocks `(pool, offset)`. + free: [Vec<(u32, u32)>; (MAX_UNITS as usize) + 1], + /// Blocks given back, reusable after `COOL`. + cooling: VecDeque<(Block, Instant)>, + /// Live or idle-kept `(va, units)` → backing block. + slots: HashMap, + /// Idle slots, oldest first (`sweep_idle`). + idle: VecDeque<(SlotKey, Instant)>, + /// Live resource raw pointer → `(va, units)`. + resources: HashMap, + /// Total 4 KiB units currently held by `slots` (live + idle-kept). + used_units: usize, +} + +impl SmallPools { + fn new() -> Self { + SmallPools { + pools: Vec::new(), + free: std::array::from_fn(|_| Vec::new()), + cooling: VecDeque::new(), + slots: HashMap::new(), + idle: VecDeque::new(), + resources: HashMap::new(), + used_units: 0, + } + } + + fn sweep_idle(&mut self, now: Instant) { + while self.idle.front().is_some_and(|&(_, since)| now.duration_since(since) >= IDLE) { + let Some((key, since)) = self.idle.pop_front() else { break }; + if self.slots.get(&key).is_some_and(|s| s.idle_since == Some(since)) { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.cooling.push_back(((s.pool, s.offset, key.1), now)); + } + } + } + } + + fn drain_cooling(&mut self, now: Instant) { + while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + if let Some(((pool, offset, units), _)) = self.cooling.pop_front() { + self.free[units as usize].push((pool, offset)); + } + } + } + + /// Try to acquire an existing shared slot for `(va, units)` or allocate a block from existing + /// pools / free lists without creating a new D3D12 heap. + fn try_acquire(&mut self, key: SlotKey, now: Instant) -> Option<(H, u32)> { + self.sweep_idle(now); + if let Some(s) = self.slots.get_mut(&key) { + s.users += 1; + s.idle_since = None; + return Some((self.pools[s.pool as usize].heap.clone(), s.offset)); + } + let units = key.1; + debug_assert!((1..=MAX_UNITS).contains(&units)); + self.drain_cooling(now); + let (pool, offset) = if let Some(b) = self.free[units as usize].pop() { + b + } else if let Some((idx, p)) = self.pools.iter_mut().enumerate().rev().find(|(_, p)| p.next_unit + units <= POOL_UNITS) { + let off = p.next_unit; + p.next_unit += units; + (idx as u32, off) + } else { + return None; + }; + let heap = self.pools[pool as usize].heap.clone(); + self.slots.insert(key, Slot { pool, offset, users: 1, idle_since: None }); + self.used_units += units as usize; + Some((heap, offset)) + } + + /// Register a newly created pool heap and acquire `(va, units)`. + /// Re-checks `try_acquire` first under the lock so two threads racing to create a new 16 MiB + /// pool do not push a redundant empty heap (the extra `heap` drops cleanly if another thread + /// already added room or created the same slot). + fn add_pool_and_acquire(&mut self, heap: H, key: SlotKey, now: Instant) -> (H, u32) { + if let Some(got) = self.try_acquire(key, now) { + return got; + } + let pool_idx = self.pools.len() as u32; + self.pools.push(Pool { heap, next_unit: 0 }); + if let Some(got) = self.try_acquire(key, now) { + return got; + } + // `pool_idx` has `next_unit == 0` and `units <= MAX_UNITS < POOL_UNITS`, so `try_acquire` + // above always succeeds. + unreachable!("fresh pool {pool_idx} must fit {} units", key.1); + } + + fn note_resource(&mut self, res: usize, key: SlotKey) { + self.resources.insert(res, key); + } + + /// Release one user of `key`. When `rollback` is true (creation failed before the GPU ever saw + /// the resource), the block returns directly to `free` if this was its only user. + fn release_key(&mut self, key: SlotKey, now: Instant, rollback: bool) { + let Some(s) = self.slots.get_mut(&key) else { return }; + s.users = s.users.saturating_sub(1); + if s.users == 0 { + if rollback { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.free[key.1 as usize].push((s.pool, s.offset)); + } + } else { + s.idle_since = Some(now); + self.idle.push_back((key, now)); + } + } + } + + fn forget(&mut self, res: usize, now: Instant) -> bool { + let Some(key) = self.resources.remove(&res) else { + return false; + }; + self.release_key(key, now, false); + true + } + + fn bytes(&self) -> (usize, usize) { + (self.used_units * UNIT, self.pools.len() * POOL_UNITS as usize * UNIT) + } + + #[cfg(test)] + fn flush_idle(&mut self, now: Instant) { + while let Some((key, since)) = self.idle.pop_front() { + if self.slots.get(&key).is_some_and(|s| s.idle_since == Some(since)) { + if let Some(s) = self.slots.remove(&key) { + self.used_units -= key.1 as usize; + self.cooling.push_back(((s.pool, s.offset, key.1), now)); + } + } + } + } +} + +// D3D12 heaps are free-threaded. +unsafe impl Send for SmallPools {} + +static SMALL_POOLS: Mutex>> = Mutex::new(BTreeMap::new()); + +fn enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_VRAM_SMALL").map_or(true, |v| v.trim() != "0")) +} + +/// Whether `desc` and `console_bytes` are eligible for 4 KiB small-resource sub-allocation. +fn candidate(desc: &D3D12_RESOURCE_DESC, console_bytes: Option) -> bool { + const PAGE: u64 = 0x1_0000; + desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN + && desc.SampleDesc.Count <= 1 + && desc.Flags.0 & 0x7 == 0 + && matches!(desc.Dimension, D3D12_RESOURCE_DIMENSION_TEXTURE2D | D3D12_RESOURCE_DIMENSION_TEXTURE3D) + && console_bytes.is_some_and(|b| b > 0 && b < PAGE) +} + +/// Place a sub-64 KiB sampled texture at 4 KiB granularity in a shared default heap. +/// Returns `None` if the texture is not a small resource (the caller falls back to `vram::Pages` +/// or a committed resource). +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn place( + dev: &ID3D12Device, + this: *mut c_void, + va: usize, + desc: &D3D12_RESOURCE_DESC, + state: u32, + clear: *const c_void, + console_bytes: Option, + riid: *const windows_sys::core::GUID, + ppv: *mut *mut c_void, +) -> Option { + if !enabled() || !candidate(desc, console_bytes) { + return None; + } + let small_desc = D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..*desc }; + let info = dev.GetResourceAllocationInfo(0, &[small_desc]); + if info.SizeInBytes == u64::MAX || info.SizeInBytes == 0 || info.Alignment != UNIT as u64 || info.SizeInBytes >= 0x1_0000 { + return None; + } + let units = (info.SizeInBytes as usize).div_ceil(UNIT) as u32; + if !(1..=MAX_UNITS).contains(&units) { + return None; + } + let dev_key = dev.as_raw() as usize; + let key = (va, units); + let now = Instant::now(); + + let (heap, offset_units) = { + let mut g = SMALL_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(SmallPools::new); + pools.try_acquire(key, now) + } + .or_else(|| { + // Create a new 16 MiB default heap outside `SMALL_POOLS.lock()`. + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_UNITS as u64 * UNIT as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + // 64 KiB heap alignment is valid for 4 KiB-aligned small resources at any 4 KiB offset. + Alignment: D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES, + }; + let mut new_heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&heap_desc, &mut new_heap)) { + crate::xlog_warn!("D3D12.X: small texture pool CreateHeap: {e}"); + return None; + } + let new_heap = new_heap?; + let mut g = SMALL_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(SmallPools::new); + Some(pools.add_pool_and_acquire(new_heap, key, Instant::now())) + })?; + + let hr = super::real::dev_create_placed_resource( + this, + heap.as_raw() as usize, + offset_units as usize * UNIT, + &small_desc as *const _ as usize, + state as usize, + clear as usize, + riid, + ppv, + ); + if hr < 0 || (*ppv).is_null() { + let mut g = SMALL_POOLS.lock().unwrap(); + if let Some(pools) = g.get_mut(&dev_key) { + pools.release_key(key, Instant::now(), true); + } + return None; + } + let raw = *ppv as usize; + SMALL_POOLS.lock().unwrap().entry(dev_key).or_insert_with(SmallPools::new).note_resource(raw, key); + Some(hr) +} + +/// Release a small-pool texture on COM release. Returns `true` if `resource` belonged to a small +/// pool (so `vram::forget` can skip locking `PAGES`). +pub(super) fn forget(resource: usize) -> bool { + let mut g = SMALL_POOLS.lock().unwrap(); + let now = Instant::now(); + for pools in g.values_mut() { + if pools.forget(resource, now) { + return true; + } + } + false +} + +/// `(used_bytes, pool_bytes)` across all devices. +pub(super) fn bytes() -> (usize, usize) { + let g = SMALL_POOLS.lock().unwrap(); + g.values().fold((0, 0), |(used, pools), p| { + let (u, t) = p.bytes(); + (used + u, pools + t) + }) +} + +#[cfg(test)] +pub(super) fn bytes_for(device: usize) -> (usize, usize) { + let mut g = SMALL_POOLS.lock().unwrap(); + let Some(p) = g.get_mut(&device) else { return (0, 0) }; + p.sweep_idle(Instant::now()); + p.bytes() +} + +#[cfg(test)] +pub(super) fn flush_idle_for(device: usize) { + let mut g = SMALL_POOLS.lock().unwrap(); + if let Some(p) = g.get_mut(&device) { + p.flush_idle(Instant::now()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn small_pool_packs_shares_and_recycles_by_size_class() { + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + let mut p: SmallPools = SmallPools::new(); + let alloc = |p: &mut SmallPools, va: usize, units: u32, res: usize, now: Instant| -> (u32, u32) { + let got = p.try_acquire((va, units), now).unwrap_or_else(|| { + let id = p.pools.len() as u32; + p.add_pool_and_acquire(id, (va, units), now) + }); + p.note_resource(res, (va, units)); + got + }; + + // Sixteen 4 KiB textures pack into 64 KiB (not 16 * 64 KiB = 1 MiB). + for i in 0..16usize { + let (h, off) = alloc(&mut p, 0x10_0000 + i * UNIT, 1, 100 + i, at(0)); + assert_eq!((h, off), (0, i as u32)); + } + assert_eq!(p.bytes(), (16 * UNIT, POOL_UNITS as usize * UNIT)); + + // Re-placing the exact same (va, units) shares the exact same (heap, offset) with zero growth. + let (h_dup, off_dup) = alloc(&mut p, 0x10_4000, 1, 200, at(10)); + assert_eq!((h_dup, off_dup), (0, 4)); + assert_eq!(p.bytes().0, 16 * UNIT); + + // Releasing one of the two aliases keeps the slot alive; releasing both makes it idle. + assert!(p.forget(200, at(20))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 1); + assert!(p.forget(104, at(30))); + assert_eq!(p.slots[&(0x10_4000, 1)].users, 0); + + // Re-acquiring within IDLE reuses the exact same slot. + let (h_re, off_re) = alloc(&mut p, 0x10_4000, 1, 201, at(1000)); + assert_eq!((h_re, off_re), (0, 4)); + assert!(p.forget(201, at(1100))); + + // After IDLE (2 s) + COOL (2 s), the 4 KiB block is recycled for a new address. + let (h_wait, off_wait) = alloc(&mut p, 0x20_0000, 1, 202, at(3200)); + assert_eq!((h_wait, off_wait), (0, 16), "still cooling at +2.1s, must not reuse yet"); + let (h_rec, off_rec) = alloc(&mut p, 0x20_1000, 1, 203, at(5300)); + assert_eq!((h_rec, off_rec), (0, 4), "block (0, 4) recycled after IDLE + COOL"); + + // Rollback on creation failure immediately returns the block to the free list. + let (h_fail, off_fail) = p.try_acquire((0x30_0000, 4), at(5400)).unwrap(); + assert_eq!((h_fail, off_fail), (0, 17)); + p.release_key((0x30_0000, 4), at(5400), true); + let (h_next, off_next) = alloc(&mut p, 0x30_4000, 4, 204, at(5400)); + assert_eq!((h_next, off_next), (0, 17)); + + // Concurrent CreateHeap race: if room already exists in pool 0, `add_pool_and_acquire` + // must reuse existing room instead of pushing a redundant empty 16 MiB pool. + let pools_before = p.pools.len(); + let (h_raced, _) = p.add_pool_and_acquire(999, (0x40_0000, 1), at(5500)); + assert_eq!(h_raced, 0); + assert_eq!(p.pools.len(), pools_before, "must not push redundant pool when room already exists"); + + // `flush_idle` clears unreferenced idle slots while keeping live (`users > 0`) slots intact. + let used_before_flush = p.bytes().0; + let _ = alloc(&mut p, 0x50_0000, 2, 205, at(5600)); + assert!(p.forget(205, at(5610))); + assert_eq!(p.bytes().0, used_before_flush + 2 * UNIT); + p.flush_idle(at(5620)); + assert_eq!(p.bytes().0, used_before_flush, "flush_idle must reclaim unreferenced slots immediately"); + } + + #[test] + fn candidate_filters_large_gpu_owned_and_msaa_textures() { + let mut d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(candidate(&d, Some(16 * 1024))); + assert!(!candidate(&d, Some(64 * 1024)), "64 KiB stays on vram::Pages"); + assert!(!candidate(&d, None)); + assert!(!candidate(&d, Some(0))); + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + assert!(!candidate(&d, Some(16 * 1024))); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + d.SampleDesc.Count = 4; + assert!(!candidate(&d, Some(16 * 1024))); + d.SampleDesc.Count = 1; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + assert!(!candidate(&d, Some(16 * 1024))); + } + + /// On the GPU: 512 small 4 KiB (64x64 BC1) and 16 KiB (64x64 RGBA8) sampled textures pack at + /// 4 KiB granularity inside a single 16 MiB heap (16x and 4x smaller than 64 KiB tiles), + /// same-address placements alias their pixels on hardware, adjacent 4 KiB textures have zero + /// crosstalk, and a small sampled texture over an existing 64 KiB GPU target falls back to + /// `vram::Pages` so target aliasing is preserved. + #[test] + fn gpu_small_textures_pack_at_4k_granularity_and_preserve_pixels() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory1().expect("DXGI factory"); + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let mut dev: Option = None; + for (adapter, _) in crate::gpu::adapter::candidates(&factory, &sel) { + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() && dev.is_some() { + break; + } + } + let Some(dev) = dev else { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return; + }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.ResourceHeapTier.0 < 2 + { + crate::gpu::recomp::runner::skip_test(&format!("resource heap tier {} < 2", opts.ResourceHeapTier.0)); + return; + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + + let desc_of = |w: u64, h: u32, fmt: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: w, + Height: h, + DepthOrArraySize: 1, + MipLevels: 1, + Format: fmt, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + ..Default::default() + }; + let place_sampled = |va: usize, d: &D3D12_RESOURCE_DESC, cbytes: u64| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::vram::place_pages(dev.as_raw(), va, d, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), Some(cbytes), riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "place_pages at {va:#x} failed: {hr:x?}"); + assert!(super::super::vram::is_placed_texture(p as usize)); + ID3D12Resource::from_raw(p) + }; + + // 1. 512 x 64x64 BC1 (2 KiB on console -> 4 KiB small resource on PC): must pack into + // 2 MiB (16x smaller than 512 x 64 KiB = 32 MiB!) inside a single 16 MiB heap. + super::super::vram::flush_idle_for(dev_key); + let bc1 = desc_of(64, 64, DXGI_FORMAT_BC1_UNORM, D3D12_RESOURCE_FLAG_NONE); + let bc1_info = dev.GetResourceAllocationInfo(0, &[D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..bc1 }]); + if bc1_info.SizeInBytes == u64::MAX || bc1_info.SizeInBytes == 0 || bc1_info.Alignment != UNIT as u64 || bc1_info.SizeInBytes >= 0x1_0000 { + crate::gpu::recomp::runner::skip_test(&format!( + "adapter does not support 4 KiB small-resource placement for 64x64 BC1 (align={}, size={})", + bc1_info.Alignment, bc1_info.SizeInBytes + )); + return; + } + let (small0, _) = bytes_for(dev_key); + let (pages0, _) = super::super::vram::page_bytes_for(dev_key); + let bc1_base = 0x60_0000_0000usize; + let mut bc1_res = Vec::with_capacity(512); + for k in 0..512usize { + bc1_res.push(place_sampled(bc1_base + k * 0x1000, &bc1, 2048)); + } + let (small_after_bc1, small_pool_after_bc1) = bytes_for(dev_key); + let bc1_small_delta = small_after_bc1 - small0; + let bc1_total_delta = super::super::vram::page_bytes_for(dev_key).0 - pages0; + println!("512 x 64x64 BC1: +{bc1_small_delta} B in small pools (pool={small_pool_after_bc1} B), +{bc1_total_delta} B total (vs 33554432 B as 64 KiB tiles)"); + assert_eq!(bc1_small_delta, 512 * UNIT, "each 64x64 BC1 must take 4 KiB in small pool"); + assert_eq!(bc1_total_delta, 512 * UNIT, "zero 64 KiB Pages tiles allocated for 4 KiB BC1 textures"); + drop(bc1_res); + + // 2. Hardware upload + readback: two adjacent 64x64 RGBA8 (16 KiB) textures and a + // same-address alias verify zero crosstalk and exact pixel sharing on the GPU. + super::super::vram::flush_idle_for(dev_key); + let rgba = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_NONE); + let rgba_info = dev.GetResourceAllocationInfo(0, &[D3D12_RESOURCE_DESC { Alignment: D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT as u64, ..rgba }]); + if rgba_info.SizeInBytes != 16384 || rgba_info.Alignment != UNIT as u64 { + crate::gpu::recomp::runner::skip_test(&format!( + "step 2: adapter does not support 4 KiB 16 KiB placement for 64x64 RGBA8 (align={}, size={})", + rgba_info.Alignment, rgba_info.SizeInBytes + )); + return; + } + let va_a = 0x61_0000_1000usize; + let va_b = 0x61_0000_5000usize; + let a1 = place_sampled(va_a, &rgba, 16384); + let (small_after_a1, _) = bytes_for(dev_key); + let a2 = place_sampled(va_a, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_after_a1, "same-va small texture must share slot"); + let b = place_sampled(va_b, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0 - small_after_a1, 16384, "64x64 RGBA8 must take 16 KiB"); + + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let fill_a = vec![0x3Cu8; 64 * 64 * 4]; + let fill_b = vec![0xA5u8; 64 * 64 * 4]; + let sub = |data: Vec| crate::gpu::texture::Subresource { rows: 64, row_bytes: 64 * 4, depth: 1, data }; + let batch = vec![ + (a2.clone(), vec![sub(fill_a.clone())], vec![D3D12_RESOURCE_STATE_COMMON]), + (b.clone(), vec![sub(fill_b.clone())], vec![D3D12_RESOURCE_STATE_COMMON]), + ]; + let failed = crate::gpu::texture::upload_batch(&dev, &queue, &batch).unwrap(); + assert!(failed.is_empty(), "upload failed: {failed:?}"); + + let readback_tex = |r: &ID3D12Resource| -> Vec { + let rd = r.GetDesc(); + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&rd, 0, 1, 0, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut total)); + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb, + ).unwrap(); + let rb = rb.unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&rb), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: fp } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + crate::gpu::texture::wait(&dev, &queue).unwrap(); + let mut p = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p)).unwrap(); + let mut out = Vec::with_capacity(rows as usize * row_bytes as usize); + for y in 0..rows as usize { + out.extend_from_slice(std::slice::from_raw_parts((p as *const u8).add(y * fp.Footprint.RowPitch as usize), row_bytes as usize)); + } + rb.Unmap(0, None); + out + }; + + assert_eq!(readback_tex(&a1), fill_a, "same-va alias a1 must see pixels uploaded to a2"); + assert_eq!(readback_tex(&b), fill_b, "adjacent 4 KiB texture b must not crosstalk with a"); + drop((b, a2, a1)); + + // 3. A small sampled texture at a 64 KiB-aligned va occupied by an existing GPU-owned + // render target must stay on vram::Pages (not vram_small) so it aliases the target. + if opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 { + crate::gpu::recomp::runner::skip_test(&format!("step 3: tiled resources tier {} < 2", opts.TiledResourcesTier.0)); + return; + } + super::super::vram::flush_idle_for(dev_key); + let rt_va = 0x62_0000_0000usize; + let rt_desc = desc_of(64, 64, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + let mut rt_raw = std::ptr::null_mut(); + let hr = super::super::vram::place(dev.as_raw(), rt_va, &rt_desc, D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, std::ptr::null(), Some(16384), riid, &mut rt_raw); + assert!(hr.is_some_and(|h| h >= 0) && !rt_raw.is_null()); + let rt = ID3D12Resource::from_raw(rt_raw); + let small_before_alias = bytes_for(dev_key).0; + let sampled_view = place_sampled(rt_va, &rgba, 16384); + assert_eq!(bytes_for(dev_key).0, small_before_alias, "sampled view over live GPU target must alias vram::Pages, not vram_small"); + drop((sampled_view, rt)); + } + } +} From f4b07062383d7a5bfface34fb07ba14c4d6b469d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:04:51 +0100 Subject: [PATCH 080/258] Recompiler: fold constant CFG terminators and recompute live DXIL flags Port #1818's constant-CFG terminator and path-fact folding onto Direct DXIL and fix the stale shader-flag validation gap that blocked it: 1. Resolve CSE and trivial-PHI replacements before CFG folding, propagate dominating branch/switch path facts (bounded to 16 RPO passes so large shaders stay linear), fold constant CondBr/Switch terminators, drop newly unreachable blocks and obsolete PHI edges (preserving loop backedges), and rerun trivial-PHI simplification (opt-out via XCL_DXIL_NO_OPT=cfg). 2. Reconcile Int64Ops, Doubles, DoubleExtensions (including f64 FMA), ResourceHeapIndexing, SamplerHeapIndexing, AtomicInt64*, and TypedUavLoadAdditionalFormats in Shader::infer_type_features() against surviving reachable instructions after optimize(), preventing stale shader flags when dead branches are pruned. Adds unit tests covering constant branches/switches, dominated branch facts, reconvergence, loop PHI backedges, and pruned i64/heap shader flags. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/module.rs | 39 +++ crates/xcl/src/gpu/dxil/module/opt.rs | 418 +++++++++++++++++++++----- crates/xcl/src/gpu/dxil/shader.rs | 41 ++- 3 files changed, 422 insertions(+), 76 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 6b00340eba..60f4341917 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -1465,6 +1465,45 @@ impl Module { fields.first().and_then(|&p0| self.const_u64(p0)).is_some_and(|w| w & 0x2000 != 0) }) } + /// Scan surviving instructions in reachable blocks for call/atomic features that must stay in + /// sync with DXIL shader flags after optimization/DCE: `(double_fma, res_heap, smp_heap, + /// i64_atomic_gs, i64_atomic_res, uav_tex_load)`. + pub fn live_feature_scan(&self, i64: Option) -> (bool, bool, bool, bool, bool, bool) { + let mut has_double_fma = false; + let mut has_res_heap = false; + let mut has_smp_heap = false; + let mut has_i64_atomic_gs = false; + let mut has_i64_atomic_res = false; + let mut has_uav_tex_load = false; + for &i in self.blocks.iter().flatten() { + let d = &self.insts[i as usize]; + match &d.op { + Op::Call(f, args) => { + let name = self.funcs[*f as usize].name.as_str(); + if name == "dx.op.createHandleFromHeap" && args.len() >= 3 { + if self.const_u64(args[2]) == Some(0) { + has_res_heap = true; + } else { + has_smp_heap = true; + } + } else if name == "dx.op.tertiary.f64" && args.first().and_then(|&a| self.const_u64(a)) == Some(47) { + has_double_fma = true; + } else if matches!(name, "dx.op.atomicBinOp.i64" | "dx.op.atomicCompareExchange.i64") { + has_i64_atomic_res = true; + } else if name.starts_with("dx.op.textureLoad") + && args.get(2).is_some_and(|&mip| matches!(mip, Value::Const(c) if matches!(self.consts[c as usize], ConstDef::Undef(_)))) + { + has_uav_tex_load = true; + } + } + Op::AtomicRmw(..) | Op::CmpXchg(..) if i64 == Some(d.ty) => { + has_i64_atomic_gs = true; + } + _ => {} + } + } + (has_double_fma, has_res_heap, has_smp_heap, has_i64_atomic_gs, has_i64_atomic_res, has_uav_tex_load) + } /// The integer value of a constant (zero-extended from its width). pub fn const_u64(&self, v: Value) -> Option { match v { diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 5e867f55a0..a604fa757c 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -423,14 +423,114 @@ impl Module { idom } + /// Replace phis whose incoming values are only themselves and one other value. Repeat + /// because resolving one phi may make another trivial, including across loop backedges. + fn simplify_phis(&self, order: &[u32], repl: &mut [Option]) { + loop { + let mut changed = false; + for &b in order { + for &i in &self.blocks[b as usize] { + let i = i as usize; + if repl[i].is_some() { + continue; + } + let Op::Phi(inc) = &self.insts[i].op else { break }; + let me = Value::Inst(i as u32); + let mut same: Option = None; + let mut trivial = true; + for &(v, _) in inc { + let v = resolve(repl, v); + if v == me || Some(v) == same { + continue; + } + if same.is_some() { + trivial = false; + break; + } + same = Some(v); + } + if let (true, Some(v)) = (trivial, same) { + repl[i] = Some(v); + changed = true; + } + } + } + if !changed { + break; + } + } + } + + /// Constants established by the control-flow edge that reaches each block. Facts are + /// intersected at joins, so a value is kept only when every incoming edge proves the same + /// value. Bounded to 16 RPO passes so giant shaders stay strictly linear. + fn branch_facts(&self, order: &[u32]) -> Vec> { + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in order { + for s in self.successors(b as usize) { + if !preds[s.0 as usize].contains(&(b as usize)) { + preds[s.0 as usize].push(b as usize); + } + } + } + let mut facts: Vec> = vec![HashMap::new(); self.blocks.len()]; + let max_iters = order.len().min(16); + for _ in 0..=max_iters { + let mut changed = false; + for &b in order.iter().skip(1) { + let b = b as usize; + let mut incoming: Option> = None; + for &p in &preds[b] { + let mut edge = facts[p].clone(); + if let Some(&term) = self.blocks[p].last() { + match &self.insts[term as usize].op { + Op::CondBr(v, t, f) if t != f => { + if t.0 as usize == b { + edge.insert(*v, 1); + } else if f.0 as usize == b { + edge.insert(*v, 0); + } + } + Op::Switch(v, default, cases) if default.0 as usize != b => { + let matching: Vec = cases.iter().filter(|(_, t)| t.0 as usize == b).map(|(c, _)| *c).collect(); + if let [case] = matching.as_slice() { + if let Some(value) = self.const_u64(*case) { + edge.insert(*v, value); + } + } + } + _ => {} + } + } + incoming = Some(match incoming { + None => edge, + Some(mut common) => { + common.retain(|v, value| edge.get(v) == Some(value)); + common + } + }); + } + let next = incoming.unwrap_or_default(); + if facts[b] != next { + facts[b] = next; + changed = true; + } + } + if !changed { + return facts; + } + } + vec![HashMap::new(); self.blocks.len()] + } + /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. + /// `XCL_DXIL_NO_OPT=phi,cse,cfg,dce,merge` (any subset, or `all`) skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); - let order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let mut order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); // malformed IR (a use before its definition or of a void result) is left for the // writer to report, not cleaned away if !self.uses_well_formed(&order) { @@ -458,38 +558,8 @@ impl Module { let mut repl: Vec> = vec![None; self.insts.len()]; // trivial phis (all incoming values the phi itself or one value), to a fixed point - while !skip("phi") { - let mut changed = false; - for &b in &order { - for &i in &self.blocks[b as usize] { - let i = i as usize; - if repl[i].is_some() { - continue; - } - let Op::Phi(inc) = &self.insts[i].op else { break }; - let me = Value::Inst(i as u32); - let mut same: Option = None; - let mut trivial = true; - for &(v, _) in inc { - let v = resolve(&mut repl, v); - if v == me || Some(v) == same { - continue; - } - if same.is_some() { - trivial = false; - break; - } - same = Some(v); - } - if let (true, Some(v)) = (trivial, same) { - repl[i] = Some(v); - changed = true; - } - } - } - if !changed { - break; - } + if !skip("phi") { + self.simplify_phis(&order, &mut repl); } // CSE along the dominator tree (preorder walk with a scoped table) @@ -562,47 +632,77 @@ impl Module { } // second trivial-phi fixed point if CSE/simplification collapsed incoming values if cse_replaced && !skip("phi") { - loop { - let mut changed = false; - for &b in &order { - for &i in &self.blocks[b as usize] { - let i = i as usize; - if repl[i].is_some() { - continue; - } - let Op::Phi(inc) = &self.insts[i].op else { break }; - let me = Value::Inst(i as u32); - let mut same: Option = None; - let mut trivial = true; - for &(v, _) in inc { - let v = resolve(&mut repl, v); - if v == me || Some(v) == same { - continue; - } - if same.is_some() { - trivial = false; - break; - } - same = Some(v); - } - if let (true, Some(v)) = (trivial, same) { - repl[i] = Some(v); - changed = true; - } - } - } - if !changed { - break; - } - } + self.simplify_phis(&order, &mut repl); } - // phis may name values defined later (back edges): resolve once more + // phis may name values defined later (back edges): resolve before CFG folding so + // terminators see constants exposed by both CSE and the second trivial-phi pass. for &b in &order { for k in 0..self.blocks[b as usize].len() { let i = self.blocks[b as usize][k] as usize; self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); } } + // CSE, trivial-phi folding, or dominating branches can prove a terminator constant. Fold + // it before DCE, then rebuild reachability and predecessor edges so unreachable blocks and + // obsolete PHI edges are pruned cleanly while preserving loop backedges. + let mut cfg_folded = false; + if !skip("cfg") { + let facts = self.branch_facts(&order); + for &b in &order { + let Some(&i) = self.blocks[b as usize].last() else { continue }; + let replacement = match self.insts[i as usize].op.clone() { + Op::CondBr(c, t, f) => match self.const_u64(c).or_else(|| facts[b as usize].get(&c).copied()) { + Some(0) => Some(Op::Br(f)), + Some(1) => Some(Op::Br(t)), + _ => None, + }, + Op::Switch(v, default, cases) => self.const_u64(v).or_else(|| facts[b as usize].get(&v).copied()).map(|needle| { + let target = cases.iter().find_map(|(case, target)| (self.const_u64(*case) == Some(needle)).then_some(*target)).unwrap_or(default); + Op::Br(target) + }), + _ => None, + }; + if let Some(op) = replacement { + self.insts[i as usize].op = op; + cfg_folded = true; + } + } + } + if cfg_folded { + order = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let mut reach = vec![false; self.blocks.len()]; + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in &order { + reach[b as usize] = true; + for succ in self.successors(b as usize) { + if let Some(p) = preds.get_mut(succ.0 as usize) { + if !p.contains(&b) { + p.push(b); + } + } + } + } + for (b, r) in reach.iter().enumerate() { + if !r { + self.blocks[b].clear(); + } + } + for &b in &order { + for &i in &self.blocks[b as usize] { + let Op::Phi(inc) = &mut self.insts[i as usize].op else { break }; + inc.retain(|p| preds[b as usize].contains(&p.1 .0)); + } + } + if !skip("phi") { + self.simplify_phis(&order, &mut repl); + for &b in &order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); + } + } + } + } // dead instructions: live = side effects, terminators and their operands, transitively let (i64t, f64t) = self.existing_i64_f64(); @@ -1400,4 +1500,186 @@ mod tests { let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); assert!(m.uses_well_formed(&order)); } + + #[test] + fn constant_conditional_removes_edge_and_trivial_phi() { + let mut m = Module::new(); + let yes = m.new_block(); + let no = m.new_block(); + let join = m.new_block(); + let i32 = m.i32(); + let slot = m.alloca(i32, 4); + let one = m.i32c(1); + let cond = m.cmp(Pred::Eq, one, one); + m.cond_br(cond, yes, no); + m.set_block(yes); + let live = m.i32c(7); + m.br(join); + m.set_block(no); + let dead = m.i32c(9); + m.br(join); + m.set_block(join); + let phi = m.phi(i32); + m.add_incoming(phi, live, yes); + m.add_incoming(phi, dead, no); + m.store(slot, phi, 4); + m.ret(); + + m.optimize(); + + let reachable = m.block_layout().0; + assert!(reachable.iter().all(|&b| !m.blocks[b].iter().any(|&i| matches!(m.insts[i as usize].op, Op::CondBr(..))))); + assert!(m.blocks[no.0 as usize].is_empty()); + assert!(!m.blocks[join.0 as usize].iter().any(|&i| matches!(m.insts[i as usize].op, Op::Phi(_)))); + } + + #[test] + fn constant_switch_keeps_only_the_selected_predecessor() { + let mut m = Module::new(); + let default = m.new_block(); + let selected = m.new_block(); + let join = m.new_block(); + let one = m.i32c(1); + let two = m.i32c(2); + let selector = m.bin(BinOp::Add, one, one); + m.switch(selector, default, &[(two, selected)]); + m.set_block(default); + m.br(join); + m.set_block(selected); + m.br(join); + m.set_block(join); + m.ret(); + + m.optimize(); + + let reachable = m.block_layout().0; + assert!(reachable.iter().all(|&b| !m.blocks[b].iter().any(|&i| matches!(m.insts[i as usize].op, Op::Switch(..))))); + assert!(m.blocks[default.0 as usize].is_empty()); + } + + #[test] + fn branch_condition_folds_a_dominated_branch() { + let mut m = Module::new(); + let yes = m.new_block(); + let no = m.new_block(); + let proven = m.new_block(); + let impossible = m.new_block(); + let i1 = m.i1(); + let condition = m.alloca(i1, 1); + let condition = m.load(condition, 1); + m.cond_br(condition, yes, no); + m.set_block(yes); + m.cond_br(condition, proven, impossible); + m.set_block(no); + m.ret(); + m.set_block(proven); + m.ret(); + m.set_block(impossible); + m.ret(); + + m.optimize(); + + assert!(m.blocks[impossible.0 as usize].is_empty()); + assert!(m.blocks[yes.0 as usize] + .iter() + .all(|&i| !matches!(m.insts[i as usize].op, Op::CondBr(..)))); + } + + #[test] + fn branch_condition_is_dropped_when_paths_reconverge() { + let mut m = Module::new(); + let yes = m.new_block(); + let no = m.new_block(); + let join = m.new_block(); + let a = m.new_block(); + let b = m.new_block(); + let i1 = m.i1(); + let condition = m.alloca(i1, 1); + let condition = m.load(condition, 1); + m.cond_br(condition, yes, no); + m.set_block(yes); + m.br(join); + m.set_block(no); + m.br(join); + m.set_block(join); + m.cond_br(condition, a, b); + m.set_block(a); + m.ret(); + m.set_block(b); + m.ret(); + + m.optimize(); + + let reachable = m.block_layout().0; + assert!(reachable.contains(&(a.0 as usize))); + assert!(reachable.contains(&(b.0 as usize))); + assert!(reachable.iter().any(|&block| m.blocks[block] + .iter() + .any(|&i| matches!(m.insts[i as usize].op, Op::CondBr(..))))); + } + + #[test] + fn edge_trim_keeps_a_loop_phi_backedge() { + let mut m = Module::new(); + let entry = m.entry_block(); + let dead = m.new_block(); + let lp = m.new_block(); + let exit = m.new_block(); + let i32 = m.i32(); + let i1 = m.i1(); + let result = m.alloca(i32, 4); + let loop_cond = m.alloca(i1, 1); + let zero = m.i32c(0); + let one = m.i32c(1); + let always = m.cmp(Pred::Eq, one, one); + m.cond_br(always, lp, dead); + m.set_block(dead); + let discarded = m.i32c(99); + m.br(lp); + m.set_block(lp); + let phi = m.phi(i32); + m.add_incoming(phi, zero, entry); + m.add_incoming(phi, discarded, dead); + let next = m.bin(BinOp::Add, phi, one); + m.add_incoming(phi, next, lp); + let again = m.load(loop_cond, 1); + m.cond_br(again, lp, exit); + m.set_block(exit); + m.store(result, phi, 4); + m.ret(); + + m.optimize(); + + assert!(m.blocks[dead.0 as usize].is_empty()); + let incoming = m.phi_incoming(phi); + assert_eq!(incoming.len(), 2); + assert!(incoming.iter().any(|p| p.1 == entry)); + assert!(incoming.iter().any(|p| p.1 == lp)); + } + + #[test] + fn dead_branch_i64_and_heap_handle_do_not_leave_stale_shader_flags() { + use crate::gpu::dxil::container::Stage; + use crate::gpu::dxil::shader::{Feature, Shader}; + let mut s = Shader::new(Stage::Compute, (6, 6)); + let live = s.m.new_block(); + let dead = s.m.new_block(); + let one = s.m.i32c(1); + let cond = s.m.cmp(Pred::Eq, one, one); + s.m.cond_br(cond, live, dead); + s.m.set_block(dead); + let i64 = s.m.i64(); + let z64 = s.m.cast(CastOp::ZExt, one, i64); + let _ = s.m.bin(BinOp::Add, z64, z64); + s.require(Feature::Int64Ops); + let _ = s.handle_from_heap(one, false, false); + s.m.ret(); + s.m.set_block(live); + s.m.ret(); + + s.m.optimize(); + s.infer_type_features(); + assert!(!s.features.contains(&Feature::Int64Ops), "pruned i64 branch must clear Int64Ops"); + assert!(!s.features.contains(&Feature::ResourceHeapIndexing), "pruned heap handle must clear ResourceHeapIndexing"); + } } diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index a0a970925d..266972f30e 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -497,21 +497,46 @@ impl Shader { (Some(node), [cbv, smp, srv, uav].concat()) } - /// Requires the features implied by instruction types alone (`Int64Ops` - /// for any i64, `Doubles` for any double, `DoubleExtensions` for double - /// division and int ↔ double conversions), which the validator derives - /// from the code and demands in the flags even when the IR was built - /// with [`Module`] methods directly rather than the [`Shader`] helpers. + /// Reconciles shader feature flags against the surviving reachable instructions after + /// `optimize()`: adds features implied by instruction types (`Int64Ops`, `Doubles`, + /// `DoubleExtensions`, `Rovs`) and clears flags whose instructions were dead-code-eliminated + /// or folded away in unreachable CFG arms ("Flags must match usage"). pub(super) fn infer_type_features(&mut self) { let (i64, f64) = self.m.existing_i64_f64(); - if i64.is_some_and(|t| self.m.insts_use_type(t)) { + let has_i64 = i64.is_some_and(|t| self.m.insts_use_type(t)); + let has_f64 = f64.is_some_and(|t| self.m.insts_use_type(t)); + if has_i64 { self.require(Feature::Int64Ops); + } else { + self.features.remove(&Feature::Int64Ops); } - if f64.is_some_and(|t| self.m.insts_use_type(t)) { + if has_f64 { self.require(Feature::Doubles); + } else { + self.features.remove(&Feature::Doubles); } - if self.m.uses_double_extensions() { + + let (has_double_fma, has_res_heap, has_smp_heap, has_i64_atomic_gs, has_i64_atomic_res, has_uav_tex_load) = self.m.live_feature_scan(i64); + if has_f64 && (self.m.uses_double_extensions() || has_double_fma) { self.require(Feature::DoubleExtensions); + } else { + self.features.remove(&Feature::DoubleExtensions); + } + if !has_res_heap { + self.features.remove(&Feature::ResourceHeapIndexing); + } + if !has_smp_heap { + self.features.remove(&Feature::SamplerHeapIndexing); + } + if !has_i64_atomic_gs { + self.features.remove(&Feature::AtomicInt64GroupShared); + } + if !has_i64_atomic_res { + self.features.remove(&Feature::AtomicInt64Typed); + self.features.remove(&Feature::AtomicInt64Heap); + } + if !has_uav_tex_load { + self.features.remove(&Feature::TypedUavLoadAdditionalFormats); } if self.bindings.iter().any(|b| b.rov) || self.m.has_rov_handle() { self.require(Feature::Rovs); From 865b238627a62dd2103e082947b2057ab36a48e5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:04:51 +0100 Subject: [PATCH 081/258] Recompiler: add branchless direct-DXIL heap-window reads (#2427) Port #2427 (XCL_HEAP_FLAT=1, HEAP_FLAT=0x200) for compute stages using XCL_HEAP_WINDOWS=1 so every heap-window read in Lw::with_mem_i32s() lowers to a single clamped ResourceDescriptorHeap[NonUniformResourceIndex(4 + w)] load and select instead of a per-read branch, merge block, and PHI set. Large compute shaders (including 95cc13288a27a96e with 1,316 heap-window reads and a74706fb8f96ade9 with 1,012 reads) eliminate thousands of basic blocks and PHIs on AMD RDNA4 as well as NVIDIA; heap_raw_buffer_uav already sets NonUniformResourceIndex=true and out-of-range/inactive lanes read harmlessly from window 0 and select 0. Includes gpu_heap_flat_reads_match_the_switch_form regression test. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/kernel.rs | 3 +- crates/xcl/src/gpu/dxil/lower.rs | 2 + crates/xcl/src/gpu/dxil/lower_mem.rs | 22 ++++++++ crates/xcl/src/gpu/recomp/mod.rs | 7 ++- crates/xcl/src/gpu/recomp/pso.rs | 9 +++- crates/xcl/src/gpu/recomp/tests.rs | 76 ++++++++++++++++++++++++++++ 6 files changed, 116 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 48e34d4827..b7d0407c41 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -171,7 +171,7 @@ fn translate_entry( fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec, Option) { let heap = mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0; let max = if heap { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; - let n = (mem_windows & !crate::gpu::recomp::HEAP_WINDOWS).clamp(1, max); + let n = (mem_windows & !(crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT)).clamp(1, max); if heap && n > 1 { let z = s.m.i32c(0); return (vec![RawUav { handle: z, binding: None }; n as usize], Some(coherent)); @@ -518,6 +518,7 @@ impl Lw { half: z, mems, heap_mem, + heap_flat: heap_mem.is_some() && !gfx && o.mem_windows & crate::gpu::recomp::HEAP_FLAT != 0, res, fmt_table: None, fmt_desc_cache: HashMap::new(), diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 53b63bdb6a..bdb7bcca67 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -187,6 +187,8 @@ pub struct Lw { /// the windows come from the descriptor heap (`lower_window`; `mems` only counts them): /// Some(globallycoherent) pub heap_mem: Option, + /// heap windows read without a branch (`recomp::HEAP_FLAT`; not in VS / PS) + pub heap_flat: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 78d15e20ad..1a3f5233aa 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -314,12 +314,34 @@ impl Lw { out } + /// `with_mem_many_tys` of `n` dwords for a read (`f` only loads). With `heap_flat`, no branch: + /// `f` reads window `w`, or window 0 when `w` is outside the windows or the lane is not in + /// `guard`, and those lanes then take 0 (a raw buffer read out of the view's range gives 0, + /// so the read of window 0 is harmless). One path per access: no handle phi, no block per read. pub(crate) fn with_mem_i32s( &mut self, guard: Option, n: usize, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, ) -> Vec { + if let (Some(coherent), true) = (self.heap_mem, self.heap_flat) { + let z = self.c(0); + if guard.is_some_and(|g| self.s.m.const_u64(g) == Some(0)) { + 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 ok = match guard { + Some(g) if self.s.m.const_u64(g) != Some(1) => self.and(g, inside), + _ => inside, + }; + let w = self.sel(ok, w, z); + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + debug_assert_eq!(vals.len(), n); + return vals.into_iter().map(|v| self.sel(ok, v, z)).collect(); + } let i32 = self.s.m.i32(); let tys = vec![i32; n]; self.with_mem_many_tys(guard, &tys, f) diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 94f41e1ddc..48d0e599dc 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -83,6 +83,11 @@ pub const MEM_HEAP_BASE: u32 = 4; /// `Options::heap_windows`. `translate` takes it out of `mem_windows`. pub const HEAP_WINDOWS: u32 = 0x100; +/// Flag in a memory-windows count next to `HEAP_WINDOWS` (`pso::mem_windows`, the caches' keys): +/// the direct DXIL translator reads the heap windows of compute stages without a branch +/// (`Lw::with_mem_i32s`). The HLSL path ignores it. +pub const HEAP_FLAT: u32 = 0x200; + pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { windows <= crate::gpu::uma::MAX_WINDOWS || (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS) @@ -1523,7 +1528,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { let program = code; let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { - normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; + normalized = Options { mem_windows: opt.mem_windows & !(HEAP_WINDOWS | HEAP_FLAT), heap_windows: true, ..opt.clone() }; &normalized } else { opt diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 16f6eb13a1..0c8bf2a9c7 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -79,7 +79,7 @@ pub fn fspx(blob: &[u8]) -> Option> { pub fn mem_windows() -> u32 { let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { - n | super::HEAP_WINDOWS + n | super::HEAP_WINDOWS | if heap_flat() { super::HEAP_FLAT } else { 0 } } else { n } @@ -115,6 +115,13 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } +/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap +/// windows without a branch per access (`HEAP_FLAT`). +pub fn heap_flat() -> bool { + static ENV: OnceLock = OnceLock::new(); + *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1")) +} + /// A static sampler of a translated program: (S#, comparison) – see `Translation`. pub type StaticSampler = ([u32; 4], bool); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 534ce151b2..b18a2d3200 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4263,6 +4263,82 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { assert_eq!(*word(w1 + 0x3000), CANARY1, "out-of-UMA global_atomic_inc must not clobber w1"); } +/// Heap windows read without a branch (`HEAP_FLAT`, the direct translator): over 4 windows, the +/// same registers as the switch over root UAVs and as the guarded heap form, for scalar loads, +/// a V# load and per-lane global loads whose lanes pick different windows, some outside UMA +/// (read 0) and some not active (keep their old values). +#[test] +fn gpu_heap_flat_reads_match_the_switch_form() { + use crate::gpu::dxil::kernel::{translate, KernelOptions}; + if !gpu_ready() { + return; + } + let arena = crate::gpu::uma::Uma::with_windows(4, 1 << 20).unwrap(); + let w: Vec = (0..4).map(|k| arena.window(k).0 as u64).collect(); + let base_hi = (w[0] >> 32) as u32; + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for (k, &wk) in w.iter().enumerate() { + *word(wk + 0x40) = 0xA0 + k as u32; + for l in 0..65u64 { + *word(wk + 0x100 + 4 * l) = (k as u32 + 1) * 1000 + l as u32; + } + } + let glbl = |n: &'static str, f: &[(&str, u64)]| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { + (n, "ENC_FLAT_GLBL", f.iter().map(|&(a, b)| (unsafe { std::mem::transmute::<&str, &'static str>(a) }, b)).collect(), None) + }; + let list = vec![ + ("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 30), ("SBASE", 1), ("OFFSET", 0)], None), + ("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 31), ("SBASE", 2), ("OFFSET", 0)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", vec![("SDATA", 24), ("SBASE", 4), ("OFFSET", 4)], None), + ("V_CMPX_LT_U32", "ENC_VOPC", vec![("SRC0", 160), ("VSRC1", 0)], None), + ("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", 7), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + glbl("GLOBAL_LOAD_DWORD", &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 0)]), + glbl("GLOBAL_LOAD_DWORDX2", &[("VDST", 8), ("ADDR", 10), ("SADDR", 16), ("OFFSET", 0)]), + ]; + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let p = prog(&refs); + let mut st = KernelState::default(); + st.sgpr[2..4].copy_from_slice(&[0x40, base_hi + 2]); + st.sgpr[4..6].copy_from_slice(&[0x40, base_hi + 6]); + st.sgpr[8..12].copy_from_slice(&[0x100, (base_hi + 3) & 0xFFFF, 0x400, 0]); + st.sgpr[12..16].copy_from_slice(&[0x100, (base_hi + 1) & 0xFFFF | 4 << 16, 64, 0]); + st.sgpr[16..18].copy_from_slice(&[0x100, base_hi]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l = l as u32; + r[0] = l; + r[4] = 0x100 + 4 * l; + r[5] = if l % 8 == 7 { base_hi + 5 } else { base_hi + l % 4 }; + for k in 6..10 { + r[k] = 0x7777_7777; + } + r[10] = 4 * l; + } + let split = runner::split_wave64(); + let run = |windows: u32| { + let dxil = translate(&p, KernelOptions { wave64: true, split, mem_windows: windows, sampler_base: 0 }).unwrap_or_else(|e| panic!("windows {windows:#x}: {e}")); + runner::run_in_arena(&dxil, &st, &arena).unwrap() + }; + let switch = run(4); + let flat = run(4 | super::HEAP_WINDOWS | super::HEAP_FLAT); + let guarded = run(4 | super::HEAP_WINDOWS); + assert_eq!((switch.sgpr[30], switch.sgpr[31]), (0xA2, 0), "s_load: window 2, outside UMA"); + assert_eq!(switch.sgpr[24..28], [4001, 4002, 4003, 4004], "s_buffer_load_dwordx4 from window 3"); + for l in 0..64u32 { + let v = &switch.vgpr[l as usize]; + let (old, active) = (0x7777_7777, l > 32); + assert_eq!(v[7], if active { 2000 + l } else { old }, "lane {l}: buffer_load from window 1"); + let global = if l % 8 == 7 { 0 } else { (l % 4 + 1) * 1000 + l }; + assert_eq!(v[6], if active { global } else { old }, "lane {l}: global_load from window {}", l % 4); + assert_eq!(v[8..10], if active { [1000 + l, 1001 + l] } else { [old, old] }, "lane {l}: global_load_dwordx2 from window 0"); + } + for (name, r) in [("heap flat", &flat), ("heap guarded", &guarded)] { + assert_eq!(r.sgpr[..32], switch.sgpr[..32], "{name}: SGPRs"); + for l in 0..64 { + assert_eq!(r.vgpr[l][..10], switch.vgpr[l][..10], "{name}: lane {l}"); + } + } +} + #[test] fn gpu_window_at_32bit_carry_edge_cases() { if !gpu_ready() { From 9c4a9217d05948fb323621256c95c79d15e259c5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:05:44 +0100 Subject: [PATCH 082/258] Recompiler: enable compute dispatch splitting for native Wave64 [64,1,1] Previously finish_dispatch() restricted split_compute() to hw == 32 and make_piece() hardcoded WaveSize(32), preventing any native Wave64 compute shader on AMD RDNA4 from splitting into a DispatchChain. For single-wave [64, 1, 1] native Wave64 compute programs (no LDS, barriers, or atomics), WaveGetLaneIndex() uniquely identifies each of the 64 threads across pieces without TGSM exchange state. Pass hw into split_compute() and make_piece() so [64, 1, 1] native Wave64 shaders split into validated WaveSize(64) pieces on AMD RDNA4 just like [32, 1, 1] shaders do on Wave32. Adds dispatch_chain_native_wave64_splits_with_wavesize_64 regression test. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/kernel.rs | 7 ++- crates/xcl/src/gpu/dxil/module/split.rs | 61 ++++++++++++++++++++----- 2 files changed, 55 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index b7d0407c41..5801707707 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -639,9 +639,12 @@ impl Lw { let early_depth_stencil = g.ps.as_ref().is_some_and(|p| p.early_depth); let info = if stage == Stage::Pixel { super::graphics::StageInfo::Pixel { early_depth_stencil } } else { super::graphics::StageInfo::Vertex }; self.s.try_finish_graphics(g.io, info) - } else if limit > 0 && (numthreads == [32, 1, 1] || split_tid.is_some()) && hw == 32 { + } else if limit > 0 + && (((numthreads == [32, 1, 1] || split_tid.is_some()) && hw == 32) + || (numthreads == [64, 1, 1] && hw == 64 && split_tid.is_none())) + { self.s.m.optimize(); - dispatch_chain = self.s.split_compute(numthreads, split_tid, limit).map(std::sync::Arc::new); + dispatch_chain = self.s.split_compute(numthreads, split_tid, hw, limit).map(std::sync::Arc::new); self.s.finish_optimized(numthreads, Some(hw)) } else { self.s.try_finish(numthreads, Some(hw)) diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index f14751b43b..26cb82daea 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -87,10 +87,11 @@ impl Scratch { } impl Shader { - /// Start with full native wave32 groups. A fresh dispatch can assign a - /// different physical wave to a group; wave-lane index identifies the - /// continuation within a full, single-wave group. - pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, limit: usize) -> Option { + /// Split a single-wave compute group (`[32, 1, 1]` on wave32, `[64, 1, 1]` on native wave64, + /// or a split-wave64 `[64, 1, 1]` group with `split_tid`) into a `DispatchChain`. A fresh + /// dispatch can assign a different physical wave to a group; `wave_lane_index` (or `split_tid`) + /// identifies each thread's continuation slot cleanly. + pub(crate) fn split_compute(&self, threads: [u32; 3], split_tid: Option, hw: u32, limit: usize) -> Option { if self.m.globals.iter().any(|g| !g.constant && !(split_tid.is_some() && matches!(g.name.as_str(), "xcl_xw" | "xcl_xs"))) { return None; } @@ -146,11 +147,11 @@ impl Shader { } } stride.checked_mul(threads[0])?.checked_mul(4)?; - let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, &prefix)).collect::>>()?; + let pieces = (0..plan.blocks.len()).map(|i| self.make_piece(&plan, i, stride, &slots, threads, hw, &prefix)).collect::>>()?; Some(DispatchChain { pieces, dwords_per_group: stride.checked_mul(threads[0])? }) } - fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], prefix: &[u32]) -> Option> { + fn make_piece(&self, plan: &Plan, stage: usize, stride: u32, slots: &BTreeMap, threads: [u32; 3], hw: u32, prefix: &[u32]) -> Option> { let src = &self.m; let mut dst = self.dispatch_piece(); let mut values = HashMap::new(); @@ -268,7 +269,7 @@ impl Shader { // a refused piece leaves the whole program unsplit: say so let refused = |e: String| crate::xlog_warn!("compute split: piece {} of {} refused, the program stays whole: {}", stage + 1, plan.blocks.len(), e.lines().next().unwrap_or_default()); - let blob = dst.try_finish(threads, Some(32)).map_err(|e| refused(e.to_string())).ok()?; + let blob = dst.try_finish(threads, Some(hw)).map_err(|e| refused(e.to_string())).ok()?; crate::gpu::dxil::validate::validate(&blob).map_err(refused).ok()?; Some(blob) } @@ -804,7 +805,7 @@ mod tests { let plan = lw.s.m.dispatch_plan(40).expect("partition around oversized loop"); assert!(plan.blocks.iter().any(|piece| piece == &[oversized])); } - let chain = lw.s.split_compute(geometry, split.then_some(tid), 40); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 32, 40); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); let chain = chain.expect("split the synthetic program"); @@ -886,7 +887,7 @@ mod tests { assert_eq!(slot(incoming, saved), slot(outgoing, replacement)); } - let chain = lw.s.split_compute(geometry, None, limit).unwrap(); + let chain = lw.s.split_compute(geometry, None, 32, limit).unwrap(); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); let initial: Vec = (0..32).map(|i| 1009 * i + 77).collect(); let mut expected: Vec<_> = initial.iter().map(|&v| { @@ -936,7 +937,7 @@ mod tests { lw.s.m.ret(); lw.s.m.optimize(); let limit = lw.s.m.blocks.iter().map(Vec::len).max().unwrap(); - let chain = lw.s.split_compute(geometry, None, limit).expect("every piece validates"); + let chain = lw.s.split_compute(geometry, None, 32, limit).expect("every piece validates"); assert!(chain.pieces.len() >= 2); } @@ -1053,7 +1054,7 @@ mod tests { let plan = lw.s.m.dispatch_plan(64).expect("partition branch fixture"); let stage = |b| plan.blocks.iter().position(|blocks| blocks.contains(&b)).unwrap(); assert!(plan.edges.iter().any(|edge| stage(edge.to) > stage(edge.from) + 1), "exercise a forward skip over an intermediate piece"); - let chain = lw.s.split_compute(geometry, split.then_some(tid), 64).expect("split branch fixture"); + let chain = lw.s.split_compute(geometry, split.then_some(tid), 32, 64).expect("split branch fixture"); assert!(chain.pieces.len() >= 3); let whole = lw.s.finish_optimized(geometry, Some(32)).unwrap(); crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); @@ -1081,4 +1082,42 @@ mod tests { } } + #[test] + fn dispatch_chain_native_wave64_splits_with_wavesize_64() { + let geometry = [64, 1, 1]; + let options = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let cs = CsInterface { threads: geometry, ..Default::default() }; + let mut lw = Lw::new(&[], &Default::default(), options, &Entry::Compute(cs)); + let (tid, _) = lw.setup_lanes_compute(geometry, false); + let mem = lw.mems[0]; + let offset = lw.shlc(tid, 2); + let mut val = lw.s.raw_load(mem, offset, 1)[0]; + let k = lw.c(33); + for step in 0..3u32 { + for i in 1..=12u32 { + let c = lw.c(step * 100 + i); + val = lw.xor(val, c); + val = lw.mul(val, k); + } + if step < 2 { + let next = lw.s.m.new_block(); + let alt = lw.s.m.new_block(); + let width = lw.s.wave_lane_count(); + let taken = lw.cmp(Pred::ULt, tid, width); + lw.s.m.cond_br(taken, next, alt); + lw.s.m.set_block(alt); + lw.s.m.br(next); + lw.s.m.set_block(next); + } + } + lw.s.raw_store(mem, offset, &[val]); + lw.s.m.ret(); + lw.s.m.optimize(); + let chain = lw.s.split_compute(geometry, None, 64, 48).expect("native wave64 [64,1,1] splits cleanly"); + assert!(chain.pieces.len() >= 2); + assert_eq!(chain.dwords_per_group % 64, 0); + if let Ok(dis) = crate::gpu::dxil::validate::disassemble(&chain.pieces[0]) { + assert!(dis.contains("WaveSize=64"), "split piece must keep WaveSize=64:\n{dis}"); + } + } } From 7ea5231eb60169abeb1125c1e8844f65cb2b783e Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:08:31 +0100 Subject: [PATCH 083/258] D3D12.X: count only spawned threads in DetilePool::new Prevent DetilePool::run from waiting on an unspawned helper thread if OS thread creation fails. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 58 ++++++++++++--------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 36d077e04c..b42c4abce4 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1552,35 +1552,43 @@ impl DetilePool { std::sync::Condvar::new(), std::sync::Condvar::new(), )); - for id in 0..helpers { + let mut spawned = 0usize; + for _ in 0..helpers { + let id = spawned; let shared = Arc::clone(&state); - let _ = std::thread::Builder::new().name(format!("xcl-detile-{id}")).spawn(move || { - let mut seen = 0u64; - loop { - let job = { - let mut g = shared.0.lock().unwrap(); - while g.gen == seen { - g = shared.1.wait(g).unwrap(); - } - seen = g.gen; - if id < g.active_helpers { - g.func.map(|f| (f, g.ctx)) - } else { - None - } - }; - if let Some((func, ctx)) = job { - let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { func(ctx as *const c_void) })); - let mut g = shared.0.lock().unwrap(); - g.pending_helpers -= 1; - if g.pending_helpers == 0 { - shared.2.notify_one(); + if std::thread::Builder::new() + .name(format!("xcl-detile-{id}")) + .spawn(move || { + let mut seen = 0u64; + loop { + let job = { + let mut g = shared.0.lock().unwrap(); + while g.gen == seen { + g = shared.1.wait(g).unwrap(); + } + seen = g.gen; + if id < g.active_helpers { + g.func.map(|f| (f, g.ctx)) + } else { + None + } + }; + if let Some((func, ctx)) = job { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { func(ctx as *const c_void) })); + let mut g = shared.0.lock().unwrap(); + g.pending_helpers -= 1; + if g.pending_helpers == 0 { + shared.2.notify_one(); + } } } - } - }); + }) + .is_ok() + { + spawned += 1; + } } - DetilePool { run_lock: Mutex::new(()), state, helpers } + DetilePool { run_lock: Mutex::new(()), state, helpers: spawned } } fn run(&self, total_threads: usize, f: &F) { From bb7027cfa45aae213a12b0c60ec4037b504c7a8f Mon Sep 17 00:00:00 2001 From: ChAlanA <88502758+ChalanaGimhanaX@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:42:10 +0530 Subject: [PATCH 084/258] Recompiler: prioritize wanted DXC compiles and reserve worker headroom --- crates/xcl/src/gpu/recomp/dxc.rs | 387 +++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/pso_async.rs | 21 +- 2 files changed, 377 insertions(+), 31 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 4ec7bc9f7f..2b25c05811 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -9,11 +9,11 @@ //! kept for `report.json` ([`toolchain`]). use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, OnceLock, Weak}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak}; use windows::core::{Interface, GUID, HRESULT, PCWSTR}; use windows::Win32::Graphics::Direct3D::Dxc::{DxcBuffer, IDxcBlob, IDxcCompiler3, IDxcResult, CLSID_DxcCompiler, DXC_CP_UTF8}; @@ -387,8 +387,6 @@ struct Job { profile: String, extra: Vec, reply: std::sync::mpsc::Sender, String>>, - /// one of the title's threads waits for it - wanted: Wanted, } /// Whether one of the title's threads waits for a compile (asked again while it is held back). @@ -398,6 +396,136 @@ pub type Wanted = Box bool + Send>; /// 0.1 – 0.7 GB). const WANTED_AT_ONCE: usize = 6; +/// Workers kept free of background compiles while a title is running so a compile that a +/// title thread waits for (`wanted`) starts immediately instead of queueing behind slow +/// background DXC compiles (#1164). Offline tools (`boot().is_none()`) use every worker. +fn wanted_reserve(total: usize) -> usize { + if total <= 1 { + 0 + } else { + (total / 3).clamp(1, 4).min(total - 1) + } +} + +struct Queued { + job: J, + wanted: Wanted, +} + +struct QueueState { + items: VecDeque>, + bg_active: usize, + total_workers: usize, + closed: bool, +} + +/// Priority job queue for the DXC worker pool: wanted jobs are dequeued ahead of background +/// jobs and bypass the background concurrency cap (`bg_limit`), while background jobs leave +/// `wanted_reserve(total_workers)` workers free whenever `reserve_for_wanted()` is true. +struct Queue { + state: Mutex>, + cv: Condvar, + reserve_for_wanted: fn() -> bool, +} + +struct BgSlot<'a, J>(&'a Queue); + +impl Drop for BgSlot<'_, J> { + fn drop(&mut self) { + let mut s = self.0.state.lock().unwrap_or_else(|e| e.into_inner()); + s.bg_active = s.bg_active.saturating_sub(1); + let has_work = !s.items.is_empty(); + let done = s.closed && !has_work; + drop(s); + if done { + self.0.cv.notify_all(); + } else if has_work { + self.0.cv.notify_one(); + } + } +} + +impl Queue { + fn new(total_workers: usize, reserve_for_wanted: fn() -> bool) -> Self { + Self { + state: Mutex::new(QueueState { + items: VecDeque::new(), + bg_active: 0, + total_workers: total_workers.max(1), + closed: false, + }), + cv: Condvar::new(), + reserve_for_wanted, + } + } + + fn bg_limit(&self, total_workers: usize) -> usize { + let reserve = if (self.reserve_for_wanted)() { wanted_reserve(total_workers) } else { 0 }; + total_workers.saturating_sub(reserve).max(1) + } + + fn push(&self, job: J, wanted: Wanted) -> Result<(), &'static str> { + let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if s.closed { + return Err("DXC: no compile threads"); + } + let wake = (wanted)() || s.bg_active < self.bg_limit(s.total_workers); + s.items.push_back(Queued { job, wanted }); + drop(s); + if wake { + self.cv.notify_one(); + } + Ok(()) + } + + /// Wake waiting workers after an already-queued job's `wanted` predicate flips to true. + fn notify_wanted(&self) { + // Acquire and release the mutex so a worker between evaluating `wanted` and entering + // `cv.wait` cannot miss this notification. + let _g = self.state.lock().unwrap_or_else(|e| e.into_inner()); + drop(_g); + self.cv.notify_all(); + } + + /// Wait for the next runnable job. Returns `None` once closed and drained. + fn pop(&self) -> Option<(J, Wanted, Option>)> { + let mut s = self.state.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(pos) = s.items.iter().position(|q| (q.wanted)()) { + let q = s.items.remove(pos).unwrap(); + let notify_close = s.closed && s.items.is_empty(); + drop(s); + if notify_close { + self.cv.notify_all(); + } + return Some((q.job, q.wanted, None)); + } + let limit = self.bg_limit(s.total_workers); + if s.bg_active < limit { + if let Some(q) = s.items.pop_front() { + s.bg_active += 1; + let notify_close = s.closed && s.items.is_empty(); + drop(s); + if notify_close { + self.cv.notify_all(); + } + return Some((q.job, q.wanted, Some(BgSlot(self)))); + } + } + if s.closed && s.items.is_empty() { + return None; + } + s = self.cv.wait(s).unwrap_or_else(|e| e.into_inner()); + } + } + + #[cfg(test)] + fn close(&self) { + self.state.lock().unwrap_or_else(|e| e.into_inner()).closed = true; + self.cv.notify_all(); + } +} + /// Compile threads (DXC workers, and the PSO workers of `pso_async` that feed them): every core /// but one, `XCL_DXC_THREADS` to choose. Memory is what `wait_for_memory` watches: a retail /// pack's biggest translations take ~0.7 GB in DXC (a typical one 0.1–0.3 GB). The cap used @@ -461,36 +589,59 @@ pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot { } } +static POOL: OnceLock>> = OnceLock::new(); + +/// Wake the DXC worker pool after a queued compile becomes wanted by a title thread. +/// Does nothing if the pool has not been started yet. +pub fn notify_wanted() { + if let Some(q) = POOL.get() { + q.notify_wanted(); + } +} + /// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started /// on first use; callers wait for their job. -fn pool() -> &'static std::sync::Mutex> { - static POOL: OnceLock>> = OnceLock::new(); +fn pool() -> &'static Arc> { POOL.get_or_init(|| { - let (tx, rx) = std::sync::mpsc::channel::(); - let rx = std::sync::Arc::new(std::sync::Mutex::new(rx)); - for k in 0..compile_threads() { - let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || loop { - let job = match rx.lock().unwrap().recv() { - Ok(j) => j, - Err(_) => return, - }; - let _slot = wait_for_memory(&job.wanted); - let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect(); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(&job.src, &job.entry, &job.profile, &extra))) - .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); - let _ = job.reply.send(r); - }); + let n = compile_threads(); + let q = Arc::new(Queue::::new(n, || crate::state::boot().is_some())); + let mut spawned = 0usize; + for k in 0..n { + let q = q.clone(); + if std::thread::Builder::new() + .name(format!("xcl-dxc-{k}")) + .stack_size(DXC_STACK) + .spawn(move || { + while let Some((job, wanted, _bg)) = q.pop() { + let _slot = wait_for_memory(&wanted); + let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(&job.src, &job.entry, &job.profile, &extra))) + .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); + let _ = job.reply.send(r); + } + }) + .is_ok() + { + spawned += 1; + } } - std::sync::Mutex::new(tx) + { + let mut s = q.state.lock().unwrap_or_else(|e| e.into_inner()); + if spawned == 0 { + s.closed = true; + } else { + s.total_workers = spawned; + } + } + q }) } /// Compile HLSL to signed DXIL. `profile` e.g. "cs_6_6"; `extra` are dxc arguments. pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { let (reply, rx) = std::sync::mpsc::channel(); - let job = Job { src: src.into(), entry: entry.into(), profile: profile.into(), extra: extra.iter().map(|s| s.to_string()).collect(), reply, wanted: crate::hle::d3d12x::pso_async::wanted_here() }; - pool().lock().unwrap().send(job).map_err(|_| "DXC: no compile threads".to_string())?; + let job = Job { src: src.into(), entry: entry.into(), profile: profile.into(), extra: extra.iter().map(|s| s.to_string()).collect(), reply }; + pool().push(job, crate::hle::d3d12x::pso_async::wanted_here()).map_err(str::to_string)?; rx.recv().map_err(|_| "DXC: the compile thread exited".to_string())? } @@ -1419,3 +1570,191 @@ mod cache_tests { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(test)] +mod pool_tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Barrier; + use std::time::Duration; + + fn run_pool(q: Arc>, workers: usize, work: impl Fn(J) + Send + Sync + 'static) -> Vec> { + let work = Arc::new(work); + (0..workers) + .map(|_| { + let (q, work) = (q.clone(), work.clone()); + std::thread::spawn(move || { + while let Some((job, _wanted, _bg)) = q.pop() { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work(job))); + } + }) + }) + .collect() + } + + #[test] + fn wanted_reserve_scales_with_worker_count() { + assert_eq!(wanted_reserve(1), 0); + assert_eq!(wanted_reserve(2), 1); + assert_eq!(wanted_reserve(3), 1); + assert_eq!(wanted_reserve(4), 1); + assert_eq!(wanted_reserve(6), 2); + assert_eq!(wanted_reserve(11), 3); + assert_eq!(wanted_reserve(15), 4); + assert_eq!(wanted_reserve(24), 4); + for total in 1..=32 { + let r = wanted_reserve(total); + assert!(r < total, "total={total} reserve={r} must leave >=1 background worker"); + if total >= 2 { + assert!((1..=4).contains(&r), "total={total} reserve={r}"); + } + } + } + + #[test] + fn wanted_job_jumps_ahead_of_queued_background_jobs() { + let q = Queue::<&'static str>::new(1, || true); + q.push("bg-1", Box::new(|| false)).unwrap(); + q.push("bg-2", Box::new(|| false)).unwrap(); + q.push("wanted-1", Box::new(|| true)).unwrap(); + q.push("bg-3", Box::new(|| false)).unwrap(); + q.push("wanted-2", Box::new(|| true)).unwrap(); + q.close(); + + let mut order = Vec::new(); + while let Some((name, _w, _bg)) = q.pop() { + order.push(name); + } + assert_eq!(order, ["wanted-1", "wanted-2", "bg-1", "bg-2", "bg-3"]); + } + + #[test] + fn wanted_job_runs_immediately_while_background_workers_are_saturated() { + // 4 workers, title running -> 3 background slots, 1 reserved for wanted jobs. + let q = Arc::new(Queue::>::new(4, || true)); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(Mutex::new(release_rx)); + let handles = run_pool(q.clone(), 4, |f| f()); + + // Saturate all 3 background slots with blocked jobs, plus 2 extra queued background jobs. + for i in 0..5 { + let (stx, rrx) = (started_tx.clone(), release_rx.clone()); + q.push( + Box::new(move || { + let _ = stx.send(i); + let _ = rrx.lock().unwrap().recv(); + }), + Box::new(|| false), + ) + .unwrap(); + } + for _ in 0..3 { + started_rx.recv_timeout(Duration::from_secs(2)).expect("background job started"); + } + // The 4th worker must stay reserved rather than picking up the 4th background job. + assert!(started_rx.recv_timeout(Duration::from_millis(40)).is_err(), "reserved worker took a background job"); + + // A wanted job starts and finishes right away on the reserved worker. + let (done_tx, done_rx) = std::sync::mpsc::channel(); + q.push(Box::new(move || done_tx.send("wanted-ok").unwrap()), Box::new(|| true)).unwrap(); + assert_eq!(done_rx.recv_timeout(Duration::from_secs(2)).expect("wanted job ran immediately"), "wanted-ok"); + + for _ in 0..5 { + release_tx.send(()).unwrap(); + } + q.close(); + for h in handles { + h.join().unwrap(); + } + } + + #[test] + fn queued_background_job_promoted_to_wanted_wakes_reserved_worker() { + let q = Arc::new(Queue::>::new(4, || true)); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(Mutex::new(release_rx)); + let handles = run_pool(q.clone(), 4, |f| f()); + + for i in 0..3 { + let (stx, rrx) = (started_tx.clone(), release_rx.clone()); + q.push( + Box::new(move || { + let _ = stx.send(i); + let _ = rrx.lock().unwrap().recv(); + }), + Box::new(|| false), + ) + .unwrap(); + } + for _ in 0..3 { + started_rx.recv_timeout(Duration::from_secs(2)).expect("background worker saturated"); + } + + // Queue a 4th job initially unwanted; it must wait while all 3 background slots are full. + let promoted = Arc::new(AtomicBool::new(false)); + let p_check = promoted.clone(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + q.push( + Box::new(move || done_tx.send("promoted-ok").unwrap()), + Box::new(move || p_check.load(Ordering::Acquire)), + ) + .unwrap(); + assert!(done_rx.recv_timeout(Duration::from_millis(40)).is_err(), "unwanted job bypassed bg limit"); + + // Title binds the pipeline -> wanted flips true and wakes the reserved worker. + promoted.store(true, Ordering::Release); + q.notify_wanted(); + assert_eq!(done_rx.recv_timeout(Duration::from_secs(2)).expect("promoted job woke reserved worker"), "promoted-ok"); + + for _ in 0..3 { + release_tx.send(()).unwrap(); + } + q.close(); + for h in handles { + h.join().unwrap(); + } + } + + #[test] + fn offline_mode_uses_all_workers_for_background_jobs() { + let q = Arc::new(Queue::>::new(4, || false)); + let all_four = Arc::new(Barrier::new(4)); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let handles = run_pool(q.clone(), 4, |f| f()); + + for i in 0..4 { + let (b, tx) = (all_four.clone(), done_tx.clone()); + q.push( + Box::new(move || { + b.wait(); + tx.send(i).unwrap(); + }), + Box::new(|| false), + ) + .unwrap(); + } + for _ in 0..4 { + done_rx.recv_timeout(Duration::from_secs(2)).expect("all 4 offline workers ran concurrently"); + } + q.close(); + for h in handles { + h.join().unwrap(); + } + } + + #[test] + fn bg_slot_recovers_after_worker_panic() { + let q = Arc::new(Queue::>::new(2, || true)); + let handles = run_pool(q.clone(), 2, |f| f()); + q.push(Box::new(|| panic!("simulated compiler panic")), Box::new(|| false)).unwrap(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + q.push(Box::new(move || done_tx.send("after-panic").unwrap()), Box::new(|| false)).unwrap(); + assert_eq!(done_rx.recv_timeout(Duration::from_secs(2)).expect("bg slot released after panic"), "after-panic"); + q.close(); + for h in handles { + h.join().unwrap(); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index d4003f79ef..11b8312fd9 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -97,15 +97,22 @@ impl Pending { fn want(&self) { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; - let mut d = self.demand.lock().unwrap(); - if !std::mem::replace(&mut d.wanted, true) && d.preload_thread != 0 { - unsafe { - let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); - if !h.is_null() { - SetThreadPriority(h, THREAD_PRIORITY_NORMAL); - CloseHandle(h); + let became_wanted = { + let mut d = self.demand.lock().unwrap(); + let first = !std::mem::replace(&mut d.wanted, true); + if first && d.preload_thread != 0 { + unsafe { + let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); + if !h.is_null() { + SetThreadPriority(h, THREAD_PRIORITY_NORMAL); + CloseHandle(h); + } } } + first + }; + if became_wanted { + crate::gpu::recomp::dxc::notify_wanted(); } } From 3f645385152fe71f63c05b6f24102766fd54d1ad Mon Sep 17 00:00:00 2001 From: crastinator <141459787+crastinator@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:41:41 +0200 Subject: [PATCH 085/258] Recompiler: an empty DXC blob reads as no bytes (#2413) DXC can hand back an empty blob with a null buffer pointer (an empty error buffer when a compile fails, or an empty result). compile_here passed that pointer to slice::from_raw_parts, which requires a non-null pointer even for length 0: undefined behaviour, and a debug build aborts on the precondition check. Both places now read the blob through blob_bytes, which gives an empty slice for a null pointer or a zero size. Part of #2413 (the dxil.dll handle left loaded after a failed candidate is a separate change). --- crates/xcl/src/gpu/recomp/dxc.rs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 2b25c05811..d947e2b3ed 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -203,6 +203,14 @@ pub fn toolchain() -> Toolchain { mod version_tests { use super::*; + #[test] + fn an_empty_blob_with_a_null_pointer_reads_as_no_bytes() { + assert!(unsafe { bytes_at(std::ptr::null(), 0) }.is_empty()); + assert!(unsafe { bytes_at(std::ptr::null(), 16) }.is_empty()); + let data = [1u8, 2, 3]; + assert_eq!(unsafe { bytes_at(data.as_ptr(), data.len()) }, &data); + } + #[test] fn versions_parse_and_compare_as_numbers() { assert_eq!(parse_version("10.0.26100.0"), Some([10, 0, 26100, 0])); @@ -677,8 +685,7 @@ fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result .GetErrorBuffer() .ok() .map(|b| { - let s = std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()); - String::from_utf8_lossy(s).trim_end_matches('\0').to_string() + String::from_utf8_lossy(blob_bytes(&b)).trim_end_matches('\0').to_string() }) .unwrap_or_default(); if status == windows::Win32::Foundation::E_OUTOFMEMORY { @@ -687,7 +694,21 @@ fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result return Err(format!("dxc: {msg}")); } let blob: IDxcBlob = r.GetResult().map_err(|e| format!("{e}"))?; - Ok(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec()) + Ok(blob_bytes(&blob).to_vec()) + } +} + +/// The bytes of a DXC blob. An empty blob may have a null pointer, which `slice::from_raw_parts` +/// does not allow even for length 0. +unsafe fn blob_bytes(b: &IDxcBlob) -> &[u8] { + bytes_at(b.GetBufferPointer() as *const u8, b.GetBufferSize()) +} + +unsafe fn bytes_at<'a>(p: *const u8, n: usize) -> &'a [u8] { + if p.is_null() || n == 0 { + &[] + } else { + std::slice::from_raw_parts(p, n) } } From e654d800a910c84fea54339cf45f01baa9ef9da5 Mon Sep 17 00:00:00 2001 From: GustavoEllwanger <225090786+GustavoEllwanger@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:06:46 -0300 Subject: [PATCH 086/258] D3D12.X: a null ppv validation call does not crash console #14 (#2401) CreateDescriptorHeap with a null out pointer is D3D12's validation call: no heap is made and it returns S_FALSE. dev_create_descriptor_heap_x read *ppv on any success code, so the call crashed for CBV_SRV_UAV and SAMPLER heaps. It now registers the heap only when ppv and *ppv are not null, as dev_create_descriptor_heap already does. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/real.rs | 3 ++- crates/xcl/tests/d3d12_resource_and_sync.rs | 23 ++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index f5011b7ed2..3f69f18195 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1135,7 +1135,8 @@ unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: let flags = if shared { d[2] & !(D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32) } else { d[2] }; let pc = [d[0], pc_n, flags, d[3]]; let hr = dev_create_descriptor_heap(this, pc.as_ptr() as usize, riid, ppv); - if hr >= 0 { + // a null `ppv` is D3D12's validation call: S_FALSE and no heap to register + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { let raw = *ppv; let heap = ID3D12DescriptorHeap::from_raw_borrowed(&raw).unwrap(); let dev = ID3D12Device::from_raw_borrowed(&this).unwrap(); diff --git a/crates/xcl/tests/d3d12_resource_and_sync.rs b/crates/xcl/tests/d3d12_resource_and_sync.rs index ac4e86ffdf..af8db517a9 100644 --- a/crates/xcl/tests/d3d12_resource_and_sync.rs +++ b/crates/xcl/tests/d3d12_resource_and_sync.rs @@ -12,7 +12,7 @@ use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use windows::core::{Interface, GUID}; -use windows::Win32::Foundation::{CloseHandle, E_INVALIDARG, S_OK, WAIT_OBJECT_0}; +use windows::Win32::Foundation::{CloseHandle, E_INVALIDARG, S_FALSE, S_OK, WAIT_OBJECT_0}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject}; @@ -409,6 +409,27 @@ fn descriptor_heap_console_start_handles_match_host_and_console_heap() { } } +/// `CreateDescriptorHeap` with a null out pointer is D3D12's validation call: it makes no heap and +/// returns `S_FALSE` (#2401). The console #14 path for CBV_SRV_UAV and SAMPLER heaps used to read +/// `*ppv` on any success code and crash. +#[test] +fn console_descriptor_heap_validation_call_with_null_out_pointer_returns_s_false() { + let Some(dev) = adopted_device() else { return }; + unsafe { + for (ty, count) in [(4u32, 16u32), (D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32, 8u32)] { + for flags in [D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32, D3D12_DESCRIPTOR_HEAP_FLAG_NONE.0 as u32] { + let desc = [ty, count, flags, 0u32]; + let hr = call_console( + dev.as_raw(), + 14, + &[desc.as_ptr() as usize, &ID3D12DescriptorHeap::IID as *const GUID as usize, 0], + ) as i32; + assert_eq!(hr, S_FALSE.0, "console CreateDescriptorHeap(type={ty}, flags={flags:#x}, ppv=NULL): {hr:#x}"); + } + } + } +} + #[test] fn fence_and_command_queue_sync_timing_and_allocator_reset_match_host_and_console() { let Some(dev) = adopted_device() else { return }; From 8484858160f4149e4a952047b2127ccd3444bebf Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:25:19 +0100 Subject: [PATCH 087/258] Tests: update test struct literals and Pages::bind calls after integration Keep #[cfg(test)] helpers compiling cleanly after #2181 (PsInterface::early_depth), 32f09674 (Effects::bvh_intersect), #2345 (sparse State quarantine/queue_fences), and #1514/#2436 (Pages::bind 6-arg 3-tuple). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/lanes.rs | 2 +- crates/xcl/src/gpu/dxil/prelude.rs | 1 + crates/xcl/src/gpu/effects.rs | 4 ++-- crates/xcl/src/gpu/recomp/tests.rs | 6 +++--- crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 2 ++ crates/xcl/src/hle/d3d12x/vram.rs | 4 ++-- 6 files changed, 11 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 14fc4e56f9..41c85abdf4 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -681,7 +681,7 @@ mod ps_ballot_tests { } fn ps_interface() -> PsInterface { - PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None } + PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false } } /// Pixel shader exercising `s_wqm`, `v_cndmask` + DPP `ddx`, `s_and_saveexec` + DPP `ddy`, diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index 7a5e5b65c4..4871311334 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -731,6 +731,7 @@ mod disable_math_refactoring_tests { outputs: vec![SigElement { name: "SV_Target".into(), index: 0, system_value: 64, component_type: 3, register: 0, mask: 0xF, rw_mask: 0xF, stream: 0 }], input_ena: 0x0F00, attrs: None, + early_depth: false, } } diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index fcce17c284..69d5bfe1cd 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -211,7 +211,7 @@ mod tests { assert_eq!(of(&asm(&[IMAGE_STORE])), None); let mut saved = asm(&[IMAGE_STORE, ("S_ENDPGM_SAVED", "ENC_SOPP", &[])]); saved.extend_from_slice(&[0xff; 8]); - assert_eq!(of(&saved), Some(Effects { memory: false, images: true, instructions: 2 })); + assert_eq!(of(&saved), Some(Effects { memory: false, images: true, instructions: 2, bvh_intersect: false })); } #[test] @@ -235,7 +235,7 @@ mod tests { END, ("S_CODE_END", "ENC_SOPP", &[]), ]); - assert_eq!(of(&far_ok), Some(Effects { memory: false, images: true, instructions: 7 })); + assert_eq!(of(&far_ok), Some(Effects { memory: false, images: true, instructions: 7, bvh_intersect: false })); // resolved far jump whose target lands past the decoded slice still fails closed let far_oob = asm(&[ diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index b18a2d3200..46e0704e10 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -8351,7 +8351,7 @@ fn ps_mrtz_sample_mask_writes_sv_coverage() { ("EXP", "ENC_EXP", mrtz, None), ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1), ("VM", 1)], None), ]); - let psi = PsInterface { inputs: vec![], outputs, input_ena: 0x2, attrs: None }; + let psi = PsInterface { inputs: vec![], outputs, input_ena: 0x2, attrs: None, early_depth: false }; let pt = translate(&code, &Options { mode: Mode::Pixel(psi), wave64: true, ..Default::default() }).unwrap(); assert!(pt.complete(), "{:?}\n{}", pt.unsupported_why, pt.hlsl); if super::dxc::location().is_ok() { @@ -9789,7 +9789,7 @@ fn list_loop_ps() -> super::Translation { code.extend(ins("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", back)], None)); code.extend(tail); code.extend(ins("S_ENDPGM", "ENC_SOPP", &[], None)); - let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None }; + let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; translate(&code, &Options { mode: Mode::Pixel(psi), wave64: false, ..Default::default() }).unwrap() } @@ -9870,7 +9870,7 @@ fn mask_loop_ps() -> super::Translation { ] .concat(), ); - let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None }; + let psi = PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], input_ena: 0x302, attrs: None, early_depth: false }; translate(&code, &Options { mode: Mode::Pixel(psi), wave64: false, ..Default::default() }).unwrap() } diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs index fcef239dee..5c749c6514 100644 --- a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -582,6 +582,8 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + quarantined: VecDeque::new(), + queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), staging: None, diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 91b9f80ebc..6dc8213424 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2859,7 +2859,7 @@ mod tests { assert!(total >= 1); let key = ReservedKey::from_desc(&desc, D3D12_RESOURCE_STATE_COMMON.0 as u32); - let (used1, extra1) = pages.bind(&dev, borrowed, 0x2000_0000, Some(total as u64 * PAGE as u64), total).expect("initial bind"); + let (used1, extra1, _) = pages.bind(&dev, borrowed, raw, 0x2000_0000, Some(total as u64 * PAGE as u64), total).expect("initial bind"); pages.unmap(borrowed, total); pages.release_tiles(used1, extra1, std::time::Instant::now(), false); assert_eq!(pages.reserved_pool.push(key, raw, total, None), None); @@ -2875,7 +2875,7 @@ mod tests { assert_eq!(reused_levels, None); let reused_ptr = reused_raw as *mut c_void; let reused = ID3D12Resource::from_raw_borrowed(&reused_ptr).unwrap(); - let (used2, extra2) = pages.bind(&dev, reused, 0x2010_0000, Some(total as u64 * PAGE as u64), reused_total).expect("rebind after recycle"); + let (used2, extra2, _) = pages.bind(&dev, reused, reused_raw, 0x2010_0000, Some(total as u64 * PAGE as u64), reused_total).expect("rebind after recycle"); pages.unmap(reused, reused_total); pages.release_tiles(used2, extra2, std::time::Instant::now(), false); // Wait for unmap on the tile-mapping queue before dropping the resource and heaps. From 9cb36c1c7873d7dc5bce60bf268752b3fec41a30 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:23:05 +0100 Subject: [PATCH 088/258] D3D12.X: hoist indirect arg clamps into batched prelude command list Running guard_dispatch_args and make_scaled_args_buffer inline before every indirect draw/dispatch forces per-call graphics -> compute -> barrier -> graphics transitions, shattering draw batching on AMD RDNA4. Hoist indirect argument guard/scale passes into a single batched prelude PC command list submitted right before each recording segment via title_list::push_segments and reclaim_for_kickoff (opt-out via XCL_INDIRECT_PRELUDE=0): - Add PRELUDE_GUARD_HLSL (batched Dispatch(ceil(N/64),1,1) with >65,535 X->Y folding + IO_GROUP_LIMIT writeback) and PRELUDE_SCALE_HLSL (batched Dispatch(num_jobs,1,1), one 64-lane group per two-pass ExecuteIndirect) reading UMA windows u2..u5 directly into dedicated prelude scratch buffers transitioned once COMMON -> UAV -> INDIRECT_ARGUMENT. - Mark recording segments as prelude-blocked in bind::note_gpu_write when any compute dispatch, indirect compute dispatch, mid-list Wait32/64 split, or buffer-writing/waiting title_list vtable slot executes, falling back seamlessly to inline ping-pong passes after GPU writes/waits so no read-before-write hazard can occur. - Pool prelude (allocator, list) pairs tied to the title allocator reset lifecycle (release_allocator_res), and add unit + D3D12 compute regression tests. Verified with cargo check -p xcl --tests (0 errors and 0 warnings in bind.rs and title_list.rs). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 860 +++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/title_list.rs | 130 +++- 2 files changed, 946 insertions(+), 44 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index cfab7708ee..6b644a854d 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -81,6 +81,42 @@ struct ScratchSlot { state: D3D12_RESOURCE_STATES, } +#[derive(Default)] +struct PreludeScratchSlot { + buf: Option<(ID3D12Resource, u64, usize)>, + used: u64, + buf_idx: usize, +} + +#[derive(Clone, Copy, Debug)] +struct PreludeGuardJob { + buf_idx: usize, + dst_off: u32, + src_win: u32, + src_off: u32, + most: u32, + lim_win: u32, + lim_off: u32, +} + +#[derive(Clone, Copy, Debug)] +struct PreludeScaleJob { + buf_idx: usize, + dst_off: u32, + count: u32, + stride: u32, + mesh_offset: u32, + split: u32, + cap: u32, + src_win: u32, + src_off: u32, + has_cnt: u32, + cnt_win: u32, + cnt_off: u32, +} + +type PreludeEntry = (ID3D12CommandAllocator, ID3D12GraphicsCommandList, usize, i32); + #[derive(Default)] struct State { layout: Option>, @@ -111,6 +147,17 @@ struct State { scratch: [ScratchSlot; 2], scratch_next: usize, scratch_taken: u64, + /// Hoisted indirect-argument clamps recorded into a single batched prelude command list + /// submitted right before this segment (`title_list::push_segments` / `reclaim_for_kickoff`). + /// Disabled for the remainder of the segment once any GPU buffer write or cross-queue wait + /// is recorded (`prelude_blocked`). + prelude_blocked: bool, + prelude_scratch: PreludeScratchSlot, + prelude_bufs: Vec, + prelude_guards: Vec, + prelude_scales: Vec, + prelude_owned: Option, + prelude_built: Option, /// true after an `INDIRECT_ARGUMENT` transition has ordered prior writes on this list and /// no compute/mesh dispatch has run since (skips redundant `fresh_indirect_arguments` barriers /// across runs of consecutive indirect graphics draws). @@ -138,9 +185,13 @@ const SCRATCH_BLOCK: u64 = 1 << 20; const SCRATCH_CAP: u64 = 16 << 20; /// Most bytes of buffers kept for reuse (`FREE_RES`) const FREE_RES_CAP: u64 = 256 << 20; +/// Most recycled prelude (allocator, list) pairs kept for reuse (`FREE_PRELUDE`) +const FREE_PRELUDE_CAP: usize = 64; static ALLOC_RES: Mutex>>> = Mutex::new(None); static FREE_RES: Mutex> = Mutex::new(Vec::new()); +static ALLOC_PRELUDE: Mutex>>> = Mutex::new(None); +static FREE_PRELUDE: Mutex> = Mutex::new(Vec::new()); fn hold_res_until_reset(allocator: usize, mut bufs: Vec<(ID3D12Resource, u64, usize)>) { if bufs.is_empty() || allocator == 0 { @@ -149,13 +200,30 @@ fn hold_res_until_reset(allocator: usize, mut bufs: Vec<(ID3D12Resource, u64, us ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); } +fn hold_prelude_until_reset(allocator: usize, entry: Option) { + let Some(entry) = entry else { return }; + if allocator == 0 { + return; + } + ALLOC_PRELUDE.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().push(entry); +} + pub(super) fn release_allocator_res(allocator: usize) { - let Some(bufs) = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) else { return }; - let mut free = FREE_RES.lock().unwrap(); - for b in bufs { - let held: u64 = free.iter().map(|f| f.1).sum(); - if pool_keeps(free.len(), held, b.1) { - free.push(b); + if let Some(bufs) = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { + let mut free = FREE_RES.lock().unwrap(); + for b in bufs { + let held: u64 = free.iter().map(|f| f.1).sum(); + if pool_keeps(free.len(), held, b.1) { + free.push(b); + } + } + } + if let Some(entries) = ALLOC_PRELUDE.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { + let mut free = FREE_PRELUDE.lock().unwrap(); + for e in entries { + if free.len() < FREE_PRELUDE_CAP { + free.push(e); + } } } } @@ -198,11 +266,21 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default()) } +/// Note that the active recording segment issued a GPU buffer write or cross-queue fence wait: +/// subsequent indirect argument clamps must execute inline instead of hoisting into the prelude, +/// and indirect argument ordering is no longer clean. +pub(super) fn note_gpu_write(list: *mut c_void) { + with(list, |s| { + s.prelude_blocked = true; + s.arg_order_clean = false; + }); +} + /// The list was created or reset onto `allocator` with `initial_pso`: the previous /// recording's memory is the previous allocator's until that one is reset, and pipeline /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { - let (old, blocks, res_bufs) = with(list, |s| { + let (old, blocks, res_bufs, prelude) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.pso = initial_pso; @@ -217,6 +295,13 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.scratch = Default::default(); s.scratch_next = 0; s.scratch_taken = 0; + s.prelude_blocked = false; + s.prelude_scratch = Default::default(); + s.prelude_bufs.clear(); + s.prelude_guards.clear(); + s.prelude_scales.clear(); + let prelude = s.prelude_owned.take(); + s.prelude_built = None; s.arg_order_clean = false; s.uma_windows = None; s.dummy_res_va = 0; @@ -233,10 +318,11 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { res_bufs.push(b); } s.rs_cs = 0; - (old, std::mem::take(&mut s.uma), res_bufs) + (old, std::mem::take(&mut s.uma), res_bufs, prelude) }); console_list::hold_until_reset(old, blocks); hold_res_until_reset(old, res_bufs); + hold_prelude_until_reset(old, prelude); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults @@ -269,7 +355,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u let (layout, args, layout_gfx, args_gfx, rs_gfx, rs_cs, pso, heaps) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.rs_cs, s.pso, s.heaps) }); - let (old, blocks) = with(to, |s| { + let (old, blocks, res_bufs, prelude) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, allocator); s.arena = Default::default(); s.layout = layout; @@ -283,6 +369,16 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.scratch = Default::default(); s.scratch_next = 0; s.scratch_taken = 0; + // A continuation segment (`from != to`) begins after a mid-list Wait32/64 split, so never + // hoist clamps ahead of that segment's head fence wait. A KickoffX non-split (`from == to`) + // starts a fresh post-kickoff segment and may hoist again. + s.prelude_blocked = from != to; + s.prelude_scratch = Default::default(); + s.prelude_bufs.clear(); + s.prelude_guards.clear(); + s.prelude_scales.clear(); + let prelude = s.prelude_owned.take(); + s.prelude_built = None; s.arg_order_clean = false; s.uma_windows = None; s.dummy_res_va = 0; @@ -294,9 +390,11 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.io_cache_cs = None; s.io_cache_tp_cs = None; s.io_cache_tp_ms = None; - (old, std::mem::take(&mut s.uma)) + (old, std::mem::take(&mut s.uma), std::mem::take(&mut s.res_retired), prelude) }); console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); + hold_prelude_until_reset(old, prelude); } /// The list is gone. @@ -307,6 +405,7 @@ pub(super) fn forget(list: *mut c_void) { s.res_retired.push(b); } hold_res_until_reset(s.allocator, s.res_retired); + hold_prelude_until_reset(s.allocator, s.prelude_owned.take()); } } @@ -900,6 +999,481 @@ void main() { const GUARD_ARGS_DRED_LABEL: &str = "xcl guard_dispatch_args"; const SCALE_ARGS_DRED_LABEL: &str = "xcl make_scaled_args_buffer"; +const PRELUDE_GUARD_DRED_LABEL: &str = "xcl prelude_guard_dispatch_args"; +const PRELUDE_SCALE_DRED_LABEL: &str = "xcl prelude_scale_mesh_args"; + +/// Batched prelude pass clamping & >65,535-folding all hoisted indirect compute dispatches of a +/// command list in a single Dispatch(ceil(N / 64), 1, 1) before the list runs. +/// `jobs` (u0): `[total, 0, 0, 0]` followed by `total` 32-byte records +/// `[src_win, src_off, most, dst_off, lim_win, lim_off, 0, 0]`. +pub(super) const PRELUDE_GUARD_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +RWByteAddressBuffer w0 : register(u2); +RWByteAddressBuffer w1 : register(u3); +RWByteAddressBuffer w2 : register(u4); +RWByteAddressBuffer w3 : register(u5); +uint3 load_u32x3(uint win, uint off) { + if (win == 0u) return w0.Load3(off); + if (win == 1u) return w1.Load3(off); + if (win == 2u) return w2.Load3(off); + return w3.Load3(off); +} +void store_u32(uint win, uint off, uint v) { + if (win == 0u) w0.Store(off, v); + else if (win == 1u) w1.Store(off, v); + else if (win == 2u) w2.Store(off, v); + else w3.Store(off, v); +} +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + uint total = jobs.Load(0); + if (tid >= total) return; + uint b = 16u + tid * 32u; + uint src_win = jobs.Load(b); + uint src_off = jobs.Load(b + 4u); + uint most = jobs.Load(b + 8u); + uint dst_off = jobs.Load(b + 12u); + uint lim_win = jobs.Load(b + 16u); + uint lim_off = jobs.Load(b + 20u); + uint3 g = load_u32x3(src_win, src_off); + uint3 out_g = uint3(0u, 0u, 0u); + uint limit = 0u; + if (g.x != 0u && g.y != 0u && g.z != 0u && all(g <= most)) { + if (g.x <= most / g.y) { + if (g.x * g.y <= most / g.z) { + if (g.x > 65535u && g.y == 1u && g.z <= 65535u) { + uint rows = (g.x - 1u) / 65535u + 1u; + if (rows <= 65535u) { + out_g = uint3(65535u, rows, g.z); + limit = g.x; + } else { + out_g = min(g, 65535u.xxx); + } + } else { + out_g = min(g, 65535u.xxx); + } + } + } + } + dst.Store3(dst_off, out_g); + if (lim_off != 0xFFFFFFFFu) { + store_u32(lim_win, lim_off, limit); + } +} +"#; + +/// Batched prelude pass scaling all hoisted two-pass ExecuteIndirect(DispatchMesh) draws of a +/// command list in a single Dispatch(num_jobs, 1, 1) before the list runs (one 64-lane group per +/// job, looping over `count` commands). `jobs` (u0): 48-byte records +/// `[count, stride, offset, split, cap, src_win, src_off, dst_off, has_cnt, cnt_win, cnt_off, 0]`. +pub(super) const PRELUDE_SCALE_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +RWByteAddressBuffer w0 : register(u2); +RWByteAddressBuffer w1 : register(u3); +RWByteAddressBuffer w2 : register(u4); +RWByteAddressBuffer w3 : register(u5); +uint load_u32(uint win, uint off) { + if (win == 0u) return w0.Load(off); + if (win == 1u) return w1.Load(off); + if (win == 2u) return w2.Load(off); + return w3.Load(off); +} +uint3 load_u32x3(uint win, uint off) { + if (win == 0u) return w0.Load3(off); + if (win == 1u) return w1.Load3(off); + if (win == 2u) return w2.Load3(off); + return w3.Load3(off); +} +[numthreads(64, 1, 1)] +void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { + uint b = gid.x * 48u; + uint count = jobs.Load(b); + uint stride = jobs.Load(b + 4u); + uint offset = jobs.Load(b + 8u); + uint split = jobs.Load(b + 12u); + uint cap = jobs.Load(b + 16u); + uint src_win = jobs.Load(b + 20u); + uint src_off = jobs.Load(b + 24u); + uint dst_off = jobs.Load(b + 28u); + uint has_cnt = jobs.Load(b + 32u); + uint cnt_win = jobs.Load(b + 36u); + uint cnt_off = jobs.Load(b + 40u); + uint live = count; + if (has_cnt != 0u) { + live = min(count, load_u32(cnt_win, cnt_off)); + } + for (uint tid = gtid.x; tid < count; tid += 64u) { + uint s = src_off + tid * stride; + uint d = dst_off + tid * stride; + uint m = d + count * stride; + for (uint i = 0u; i < stride; i += 4u) { + uint w = load_u32(src_win, s + i); + dst.Store(d + i, w); + dst.Store(m + i, w); + } + uint3 g = load_u32x3(src_win, s + offset); + uint n = 0u; + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { + n = min(g.x, cap); + n = g.y > cap / n ? cap : n * g.y; + n = g.z > cap / n ? cap : n * g.z; + } + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); + } +} +"#; + +/// `XCL_INDIRECT_PRELUDE=0`: run indirect argument clamp/scale passes inline instead of hoisting +/// them into a batched prelude command list submitted right before the recording. +fn indirect_prelude_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INDIRECT_PRELUDE").map_or(true, |v| v.trim() != "0")) +} + +/// Map a 4-byte-aligned UMA host address + byte span to `(window_index, byte_offset)` within +/// the 4 UMA windows (`u2..u5`), ensuring `byte_offset + span` fits in 32-bit HLSL byte offsets. +fn uma_win_off(u: &crate::gpu::uma::Uma, p: usize, span: usize) -> Option<(u32, u32)> { + if p % 4 != 0 || span == 0 { + return None; + } + let k = u.window_of(p)?; + if k >= 4 { + return None; + } + let (base, size) = u.window(k); + let off = p.checked_sub(base)?; + let end = off.checked_add(span)?; + if end > size || end > u32::MAX as usize { + return None; + } + Some((k as u32, off as u32)) +} + +fn can_hoist_prelude(this: *mut c_void) -> bool { + indirect_prelude_on() + && super::title_list::wrapper_of(this).is_some() + && matches!( + super::list_x::tracked_list_type(this), + Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE) + ) + && with(this, |s| !s.prelude_blocked && s.allocator != 0 && s.prelude_built.is_none()) +} + +unsafe fn prelude_root_signature(dev: &ID3D12Device) -> Result { + let params: [D3D12_ROOT_PARAMETER1; 6] = std::array::from_fn(|reg| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: reg as u32, + RegisterSpace: 0, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: 0, + pStaticSamplers: std::ptr::null(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }, + }, + }; + let mut blob: Option = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None).map_err(|e| format!("prelude root signature serialize: {e}"))?; + let blob = blob.ok_or("prelude root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("prelude root signature create: {e}")) +} + +unsafe fn prelude_pipeline(dev: &ID3D12Device, hlsl: &str, label: &str, cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let key = dev.as_raw() as usize; + if let Some(pair) = cache.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let rs = prelude_root_signature(dev)?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("{label} pso create: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from(label)); + super::dred::label_text(pso.as_raw() as usize, || label.to_string()); + cache.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + +unsafe fn prelude_guard_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_pipeline(dev, PRELUDE_GUARD_HLSL, PRELUDE_GUARD_DRED_LABEL, &CACHE) +} + +unsafe fn prelude_scale_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_pipeline(dev, PRELUDE_SCALE_HLSL, PRELUDE_SCALE_DRED_LABEL, &CACHE) +} + +/// Allocate `bytes` in `State::prelude_scratch` (disjoint from inline ping-pong scratch so the +/// prelude leaves these buffers in `INDIRECT_ARGUMENT` for the entire main segment). +unsafe fn alloc_prelude_scratch(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64, usize), String> { + let bytes = bytes.next_multiple_of(256); + if let Some(r) = with(this, |s| { + let sl = &mut s.prelude_scratch; + let (b, cap, _) = sl.buf.as_ref()?; + (sl.used + bytes <= *cap).then(|| { + sl.used += bytes; + (b.clone(), sl.used - bytes, sl.buf_idx) + }) + }) { + return Ok(r); + } + let size = bytes.max(SCRATCH_BLOCK); + let remaining = SCRATCH_CAP.saturating_sub(with(this, |s| s.scratch_taken)); + if size > remaining { + return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); + } + let dev_key = dev.as_raw() as usize; + let picked = { + let mut free = FREE_RES.lock().unwrap(); + free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= size && *cap <= remaining).map(|i| free.swap_remove(i)) + }; + let block = match picked { + Some(e) => e, + None => (default_uav_buffer(dev, size, "prelude indirect argument scratch")?, size, dev_key), + }; + let b = block.0.clone(); + let buf_idx = with(this, |s| { + let idx = s.prelude_bufs.len(); + s.scratch_taken += block.1; + s.prelude_bufs.push(b.clone()); + s.prelude_scratch = PreludeScratchSlot { + buf: Some(block.clone()), + used: bytes, + buf_idx: idx, + }; + s.res_retired.push(block); + idx + }); + Ok((b, 0, buf_idx)) +} + +/// Build (once per recording) and return the closed PC prelude command list that runs all hoisted +/// indirect-argument clamp/scale jobs for `seg` before `seg` executes on the queue. +pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { + let (already, bufs, guards, scales) = with(seg, |s| { + if let Some(ref built) = s.prelude_built { + return (Some(built.as_raw()), Vec::new(), Vec::new(), Vec::new()); + } + if s.prelude_guards.is_empty() && s.prelude_scales.is_empty() { + return (None, Vec::new(), Vec::new(), Vec::new()); + } + (None, s.prelude_bufs.clone(), s.prelude_guards.clone(), s.prelude_scales.clone()) + }); + if let Some(p) = already { + return Some(p); + } + if guards.is_empty() && scales.is_empty() { + return None; + } + let run = (|| -> Result { + let dev = super::real::list_device(seg).ok_or("no device for prelude list")?; + let ty = super::list_x::tracked_list_type(seg).ok_or("no list type for prelude list")?; + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return Err("unsupported list type for prelude".into()); + } + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let win_vas = with(seg, |s| -> Result<[u64; 4], String> { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + let w = super::real::uma_window_vas(); + if w.is_empty() { + return Err("unified memory is not open on the GPU".into()); + } + s.uma_windows = Some(w); + } + let w = s.uma_windows.as_deref().unwrap(); + let first = w[0]; + Ok([first, w.get(1).copied().unwrap_or(first), w.get(2).copied().unwrap_or(first), w.get(3).copied().unwrap_or(first)]) + })?; + + let dev_key = dev.as_raw() as usize; + let reused = { + let mut free = FREE_PRELUDE.lock().unwrap(); + free.iter().position(|e| e.2 == dev_key && e.3 == ty.0).map(|i| free.swap_remove(i)) + }; + let (alloc, list) = match reused { + Some((a, l, _, _)) => { + a.Reset().map_err(|e| format!("prelude allocator reset: {e}"))?; + l.Reset(&a, None).map_err(|e| format!("prelude list reset: {e}"))?; + (a, l) + } + None => { + let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).map_err(|e| format!("prelude allocator create: {e}"))?; + let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &a, None).map_err(|e| format!("prelude list create: {e}"))?; + (a, l) + } + }; + + // 1. Order prior queue writes into UMA and transition all prelude scratch buffers COMMON -> UAV. + let mut pre_barriers: Vec = Vec::with_capacity(1 + bufs.len()); + pre_barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), + }, + }); + for b in &bufs { + pre_barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(b.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_COMMON, + StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + }), + }, + }); + } + list.ResourceBarrier(&pre_barriers); + for b in pre_barriers.iter_mut().skip(1) { + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); + } + + // Helper to upload a packed `u32` job slice into `seg`'s UMA arena. + let upload_words = |words: &[u32]| -> Result { + let bytes = std::mem::size_of_val(words); + let p = with(seg, |s| s.arena.take(u, bytes.max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), p, bytes); + super::real::uma_va_of(p as usize).ok_or_else(|| "unified memory is not open on the GPU".into()) + }; + + let bind_windows = |list: &ID3D12GraphicsCommandList| { + for (k, &va) in win_vas.iter().enumerate() { + list.SetComputeRootUnorderedAccessView((2 + k) as u32, va); + } + }; + + // 2. Emit batched guard dispatches grouped by prelude scratch buffer. + if !guards.is_empty() { + let (rs, pso) = prelude_guard_pipeline(&dev)?; + list.SetComputeRootSignature(&rs); + bind_windows(&list); + list.SetPipelineState(&pso); + for (buf_idx, buf) in bufs.iter().enumerate() { + let batch: Vec<&PreludeGuardJob> = guards.iter().filter(|j| j.buf_idx == buf_idx).collect(); + if batch.is_empty() { + continue; + } + let dst_va = buf.GetGPUVirtualAddress(); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for chunk in batch.chunks(65_535 * 64) { + let mut words = Vec::with_capacity(4 + chunk.len() * 8); + words.extend_from_slice(&[chunk.len() as u32, 0, 0, 0]); + for j in chunk { + words.extend_from_slice(&[j.src_win, j.src_off, j.most, j.dst_off, j.lim_win, j.lim_off, 0, 0]); + } + let jobs_va = upload_words(&words)?; + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.Dispatch((chunk.len() as u32).div_ceil(64), 1, 1); + } + } + } + + // 3. Emit batched scale dispatches grouped by prelude scratch buffer. + if !scales.is_empty() { + let (rs, pso) = prelude_scale_pipeline(&dev)?; + list.SetComputeRootSignature(&rs); + bind_windows(&list); + list.SetPipelineState(&pso); + for (buf_idx, buf) in bufs.iter().enumerate() { + let batch: Vec<&PreludeScaleJob> = scales.iter().filter(|j| j.buf_idx == buf_idx).collect(); + if batch.is_empty() { + continue; + } + let dst_va = buf.GetGPUVirtualAddress(); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for chunk in batch.chunks(65_535) { + let mut words = Vec::with_capacity(chunk.len() * 12); + for j in chunk { + words.extend_from_slice(&[ + j.count, j.stride, j.mesh_offset, j.split, j.cap, j.src_win, j.src_off, j.dst_off, j.has_cnt, j.cnt_win, j.cnt_off, 0, + ]); + } + let jobs_va = upload_words(&words)?; + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.Dispatch(chunk.len() as u32, 1, 1); + } + } + } + + // 4. Transition all prelude scratch buffers UAV -> INDIRECT_ARGUMENT (plus global UAV + // barrier if any guard jobs wrote `IO_GROUP_LIMIT` into UMA). + let mut post_barriers: Vec = Vec::with_capacity(bufs.len() + usize::from(!guards.is_empty())); + for b in &bufs { + post_barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(b.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + }), + }, + }); + } + if !guards.is_empty() { + post_barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), + }, + }); + } + list.ResourceBarrier(&post_barriers); + for b in post_barriers.iter_mut().take(bufs.len()) { + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); + } + + list.Close().map_err(|e| format!("prelude list close: {e}"))?; + with(seg, |s| { + s.prelude_owned = Some((alloc, list.clone(), dev_key, ty.0)); + s.prelude_built = Some(list.clone()); + }); + static BATCHES: AtomicU64 = AtomicU64::new(0); + static TOTAL_JOBS: AtomicU64 = AtomicU64::new(0); + let n_jobs = (guards.len() + scales.len()) as u64; + let b = BATCHES.fetch_add(1, Ordering::Relaxed) + 1; + let tot = TOTAL_JOBS.fetch_add(n_jobs, Ordering::Relaxed) + n_jobs; + if b == 1 || (b.is_power_of_two() && b >= 16) { + crate::xlog_info!("D3D12.X: indirect prelude batch #{b} ({} guard + {} scale jobs, {tot} hoisted total)", guards.len(), scales.len()); + } + Ok(list) + })(); + match run { + Ok(l) => Some(l.as_raw()), + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: indirect prelude build failed: {e}"); + } + None + } + } +} /// The groups of an indirect dispatch above which they are not the title's (`GUARD_ARGS_HLSL`): /// a 4K target in groups of 2x2 pixels is 2.1 million. @@ -954,16 +1528,39 @@ fn indirect_guard() -> bool { /// The arguments of one indirect dispatch at UMA address `src`, checked and >65 535 X-folded /// (`GUARD_ARGS_HLSL`): writes the guarded/folded `(x, y, z)` to scratch (`INDIRECT_ARGUMENT`) -/// and writes `IO_GROUP_LIMIT` into `dispatch_io_va`. The list's compute root signature and -/// pipeline are the guard's after this. -unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, dispatch_io_va: u64) -> Result<(ID3D12Resource, u64), String> { +/// and writes `IO_GROUP_LIMIT` into `dispatch_io_va`. When no prior GPU write or cross-queue +/// wait occurred in this segment, hoists the guard into the segment's batched prelude list so +/// the main list avoids inline compute/barrier bubbles; otherwise runs inline. +unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandList, src: usize, dispatch_io_va: u64, dispatch_io_host: usize) -> Result<(ID3D12Resource, u64), String> { if super::list_x::tracked_list_type(this) == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) { return Err("command bundles cannot record indirect argument barriers".into()); } let dev = super::real::list_device(this).ok_or("no device")?; - let (rs, pso) = guard_indirect_pipeline(&dev)?; let u = crate::gpu::uma::get().ok_or("no unified memory")?; super::real::uma_window_buffer(src, 12).ok_or("the indirect arguments are not in one memory window")?; + if can_hoist_prelude(this) { + if let (Some((src_win, src_off)), Some((lim_win, lim_off))) = ( + uma_win_off(u, src, 12), + uma_win_off(u, dispatch_io_host + crate::gpu::recomp::IO_GROUP_LIMIT * 4, 4), + ) { + let (dst, dst_off, buf_idx) = alloc_prelude_scratch(this, &dev, 256)?; + if let Ok(dst_off32) = u32::try_from(dst_off) { + with(this, |s| { + s.prelude_guards.push(PreludeGuardJob { + buf_idx, + dst_off: dst_off32, + src_win, + src_off, + most: most_groups(), + lim_win, + lim_off, + }); + }); + return Ok((dst, dst_off)); + } + } + } + let (rs, pso) = guard_indirect_pipeline(&dev)?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; let (src_base, src_off) = align_root_uav(src_va)?; let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, 256)?; @@ -1150,9 +1747,44 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman } let commands = validate_scale_args_layout(max, stride, mesh_offset)?; let dev = super::real::list_device(this).ok_or("no device")?; - let (rs, pso) = scale_indirect_pipeline(&dev)?; let u = crate::gpu::uma::get().ok_or("no unified memory")?; super::real::uma_window_buffer(src, commands as usize).ok_or("the indirect arguments are not in one memory window")?; + if let Some(p) = count { + super::real::uma_window_buffer(p, 4).ok_or("the indirect count is not in a memory window")?; + } + if can_hoist_prelude(this) { + if let Some((src_win, src_off)) = uma_win_off(u, src, commands as usize) { + let cnt_loc = match count { + Some(p) => uma_win_off(u, p, 4).map(|(w, o)| (1u32, w, o)), + None => Some((0u32, 0u32, 0u32)), + }; + if let Some((has_cnt, cnt_win, cnt_off)) = cnt_loc { + let (dst, dst_off, buf_idx) = alloc_prelude_scratch(this, &dev, commands.saturating_mul(2))?; + if let Ok(dst_off32) = u32::try_from(dst_off) { + if dst_off32.checked_add((commands * 2) as u32).is_some() { + with(this, |s| { + s.prelude_scales.push(PreludeScaleJob { + buf_idx, + dst_off: dst_off32, + count: max, + stride, + mesh_offset, + split, + cap, + src_win, + src_off, + has_cnt, + cnt_win, + cnt_off, + }); + }); + return Ok((dst, dst_off)); + } + } + } + } + } + let (rs, pso) = scale_indirect_pipeline(&dev)?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; let (src_base, src_off) = align_root_uav(src_va)?; if (src_off as u64).checked_add(commands).is_none_or(|end| end > u32::MAX as u64) { @@ -1160,7 +1792,6 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman } let count_bound = match count { Some(p) => { - super::real::uma_window_buffer(p, 4).ok_or("the indirect count is not in a memory window")?; let va = super::real::uma_va_of(p).ok_or("unified memory is not open on the GPU")?; Some(align_root_uav(va)?) } @@ -1449,9 +2080,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // Allocate a dedicated `io` buffer for this dispatch so `guard_dispatch_args` can // write `IO_GROUP_LIMIT` on the GPU without racing against cached `io` slots. match alloc_fresh_compute_io(this, pso) { - Ok(io_va) => { + Ok((io_va, io_host)) => { preset_io = Some(io_va); - match guard_dispatch_args(this, list, p, io_va) { + match guard_dispatch_args(this, list, p, io_va, io_host) { Ok(g) => guarded = Some(g), Err(e) => { static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -1486,7 +2117,10 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } super::culprit::after_dispatch(list, mark); if compute { - with(this, |s| s.arg_order_clean = false); + with(this, |s| { + s.arg_order_clean = false; + s.prelude_blocked = true; + }); } } Err(e) => { @@ -2170,7 +2804,10 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis let mark = super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [x, y, z]); let r = super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]); super::culprit::after_dispatch(list, mark); - with(this, |s| s.arg_order_clean = false); + with(this, |s| { + s.arg_order_clean = false; + s.prelude_blocked = true; + }); r } @@ -2193,12 +2830,12 @@ pub(super) fn fold(x: u32, y: u32, z: u32) -> (u32, [u32; 3]) { } /// Allocate a dedicated compute `io` buffer in UMA for an indirect dispatch whose `IO_GROUP_LIMIT` -/// slot will be written on the GPU by `guard_dispatch_args`. -unsafe fn alloc_fresh_compute_io(this: *mut c_void, pso: usize) -> Result { +/// slot will be written on the GPU by `guard_dispatch_args`. Returns `(gpu_va, host_ptr)`. +unsafe fn alloc_fresh_compute_io(this: *mut c_void, pso: usize) -> Result<(u64, usize), String> { let u = crate::gpu::uma::get().ok_or("no unified memory")?; let real = super::pso_async::resolve_wait(pso); let user_sgprs = super::real::pso_user_sgprs(real); - with(this, |s| -> Result { + with(this, |s| -> Result<(u64, usize), String> { if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { let w = super::real::uma_window_vas(); if w.is_empty() { @@ -2227,7 +2864,7 @@ unsafe fn alloc_fresh_compute_io(this: *mut c_void, pso: usize) -> Result(), io_p, io_bytes); - Ok(uma_va_in(u, windows, io_p as usize).unwrap_or(first)) + Ok((uma_va_in(u, windows, io_p as usize).unwrap_or(first), io_p as usize)) }) } @@ -3808,4 +4445,179 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) assert_eq!(fake.set_compute_uav_calls.load(Ordering::Relaxed), 0); assert_eq!(counts_snapshot(), before); } + + #[test] + fn prelude_state_tracks_gpu_writes_splits_and_resets() { + let a = 0x7710_0001usize as *mut c_void; + let b = 0x7710_0002usize as *mut c_void; + reset(a, 0x7710_A001, 0); + with(a, |s| { + assert!(!s.prelude_blocked); + s.arg_order_clean = true; + s.prelude_guards.push(PreludeGuardJob { + buf_idx: 0, + dst_off: 0, + src_win: 0, + src_off: 16, + most: MOST_GROUPS, + lim_win: 0, + lim_off: 64, + }); + }); + // Recording a GPU write/wait blocks subsequent hoisting without dropping prior hoisted jobs. + note_gpu_write(a); + with(a, |s| { + assert!(s.prelude_blocked); + assert!(!s.arg_order_clean); + assert_eq!(s.prelude_guards.len(), 1); + }); + // Mid-list split (`from != to`) blocks hoisting on the continuation segment (Wait64 head). + inherit_for_split(a, b, 0x7710_A001); + with(b, |s| { + assert!(s.prelude_blocked); + assert!(s.prelude_guards.is_empty()); + }); + // KickoffX non-split (`from == to`) starts a fresh post-kickoff segment and unblocks hoisting. + inherit_for_split(a, a, 0x7710_A001); + with(a, |s| { + assert!(!s.prelude_blocked); + assert!(s.prelude_guards.is_empty()); + }); + note_gpu_write(a); + reset(a, 0x7710_A002, 0); + with(a, |s| { + assert!(!s.prelude_blocked); + assert!(s.prelude_guards.is_empty()); + assert!(s.prelude_scales.is_empty()); + }); + forget(a); + forget(b); + } + + #[test] + fn prelude_guard_and_scale_shaders_compile_and_transform_batches() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return; + } + let dev = dev.unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let (guard_rs, guard_pso) = prelude_guard_pipeline(&dev).expect("prelude guard pipeline"); + let (scale_rs, scale_pso) = prelude_scale_pipeline(&dev).expect("prelude scale pipeline"); + + let mk_buf = |bytes: u64, heap: D3D12_HEAP_TYPE, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES| -> ID3D12Resource { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: flags, + ..Default::default() + }; + let mut res: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut res).unwrap(); + res.unwrap() + }; + + let w0 = mk_buf(4096, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + let dst = mk_buf(4096, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + let jobs = mk_buf(4096, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON); + let up_w0 = mk_buf(4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + let up_jobs = mk_buf(4096, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ); + let rb_dst = mk_buf(4096, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + let rb_w0 = mk_buf(4096, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST); + + // Seed w0: + // 0x000: guard job 0 input (115_200, 1, 1) -> folded (65_535, 2, 1), limit = 115_200 at 0x100 + // 0x010: guard job 1 input (0xFFFF_FFFF, 1, 1) -> zeroed (0, 0, 0), limit = 0 at 0x104 + // 0x200: scale job 0 (2 cmds, stride 16, mesh_offset 4, split 2, cap 10, count=1 at 0x300) + // cmd0 = [0xAA, 4, 2, 1] -> n=8 -> compute (8,1,1), mesh (16,1,1) + // cmd1 = [0xBB, 3, 1, 1] -> tid>=live(1) -> (0,1,1) + let mut p = std::ptr::null_mut(); + up_w0.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, 0, 4096); + let w0_u32 = std::slice::from_raw_parts_mut(p as *mut u32, 1024); + w0_u32[0..3].copy_from_slice(&[115_200, 1, 1]); + w0_u32[4..7].copy_from_slice(&[u32::MAX, 1, 1]); + w0_u32[0x200 / 4..0x200 / 4 + 8].copy_from_slice(&[0xAA, 4, 2, 1, 0xBB, 3, 1, 1]); + w0_u32[0x300 / 4] = 1; + up_w0.Unmap(0, None); + + // Seed jobs: guard batch at 0x000 (2 jobs), scale batch at 0x200 (1 job). + up_jobs.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, 0, 4096); + let j_u32 = std::slice::from_raw_parts_mut(p as *mut u32, 1024); + j_u32[0..4].copy_from_slice(&[2, 0, 0, 0]); + j_u32[4..12].copy_from_slice(&[0, 0x000, MOST_GROUPS, 0x000, 0, 0x100, 0, 0]); + j_u32[12..20].copy_from_slice(&[0, 0x010, MOST_GROUPS, 0x100, 0, 0x104, 0, 0]); + j_u32[0x200 / 4..0x200 / 4 + 12].copy_from_slice(&[2, 16, 4, 2, 10, 0, 0x200, 0x400, 1, 0, 0x300, 0]); + up_jobs.Unmap(0, None); + + list.CopyBufferRegion(&w0, 0, &up_w0, 0, 4096); + list.CopyBufferRegion(&jobs, 0, &up_jobs, 0, 4096); + emit_transition(&list, &w0, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_transition(&list, &jobs, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + emit_transition(&list, &dst, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + + let w0_va = w0.GetGPUVirtualAddress(); + let dst_va = dst.GetGPUVirtualAddress(); + let jobs_va = jobs.GetGPUVirtualAddress(); + list.SetComputeRootSignature(&guard_rs); + list.SetPipelineState(&guard_pso); + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for k in 2..6 { + list.SetComputeRootUnorderedAccessView(k, w0_va); + } + list.Dispatch(1, 1, 1); + emit_uav_barrier(&list, Some(&w0)); + + list.SetComputeRootSignature(&scale_rs); + list.SetPipelineState(&scale_pso); + list.SetComputeRootUnorderedAccessView(0, jobs_va + 0x200); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for k in 2..6 { + list.SetComputeRootUnorderedAccessView(k, w0_va); + } + list.Dispatch(1, 1, 1); + + emit_transition(&list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + emit_transition(&list, &w0, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&rb_dst, 0, &dst, 0, 4096); + list.CopyBufferRegion(&rb_w0, 0, &w0, 0, 4096); + list.Close().unwrap(); + + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 5000).unwrap(); + + rb_dst.Map(0, None, Some(&mut p)).unwrap(); + let out = std::slice::from_raw_parts(p as *const u32, 1024); + assert_eq!(&out[0..3], &[65_535, 2, 1], "guard job 0 must fold 115,200 into 65,535 x 2 x 1"); + assert_eq!(&out[0x100 / 4..0x100 / 4 + 3], &[0, 0, 0], "guard job 1 overflow must zero out"); + // Scale job 0 output at 0x400: compute cmds (0x400..0x420), mesh cmds (0x420..0x440) + let s = 0x400 / 4; + assert_eq!(&out[s..s + 4], &[0xAA, 8, 1, 1], "scale cmd0 compute"); + assert_eq!(&out[s + 4..s + 8], &[0xBB, 0, 1, 1], "scale cmd1 masked by count"); + assert_eq!(&out[s + 8..s + 12], &[0xAA, 16, 1, 1], "scale cmd0 mesh (split=2)"); + assert_eq!(&out[s + 12..s + 16], &[0xBB, 0, 1, 1], "scale cmd1 mesh masked by count"); + rb_dst.Unmap(0, None); + + rb_w0.Map(0, None, Some(&mut p)).unwrap(); + let w0_out = std::slice::from_raw_parts(p as *const u32, 1024); + assert_eq!(w0_out[0x100 / 4], 115_200, "guard job 0 must store IO_GROUP_LIMIT"); + assert_eq!(w0_out[0x104 / 4], 0, "guard job 1 overflow must store 0 limit"); + rb_w0.Unmap(0, None); + let _ = alloc; + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index 52fedf8685..93c86089fe 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -59,6 +59,34 @@ static WRAPPER_OF: Mutex>> = Mutex::new(None); struct Vtable(usize); +/// Command-list vtable slots (PC + older/newer console layouts) that can write to GPU buffers +/// or wait on cross-queue fences: calling any of them marks the active recording segment as +/// having GPU writes/waits so subsequent indirect argument clamps stay inline instead of being +/// hoisted into the segment's prelude command list. +fn is_gpu_write_or_wait_slot(slot: usize) -> bool { + matches!( + slot, + 15..=18 // CopyBufferRegion, CopyTextureRegion, CopyResource, CopyTiles + | 27 // ExecuteBundle + | 30 // ResolveQueryData (console #30 = PC #54) + | 53..=54 // ClearUnorderedAccessView{Uint,Float} (console #53/#54 = PC #49/#50) + | 60..=65 // CopyMemoryToMemoryX / Fill{32,64,128}X (older + newer +2 shifted; #61 filtered below) + | 69..=74 // Write{32,64}BottomX / Wait{32,64}X (older + newer +2 shifted; #70 filtered below) + | 83..=86 // Copy{TextureRegion,Resource}FlagsX (older + newer +2 shifted; #83 filtered below) + | 88..=92 // Write{32,64}TopX / Write32BottomOfShaderX (older + newer +2 shifted) + | 104..=105 // AtomicCopyBufferUINT / UINT64 + ) +} + +fn slot_writes_or_waits_now(slot: usize, shifted: bool) -> bool { + if !is_gpu_write_or_wait_slot(slot) { + return false; + } + // On the newer console layout (+2 shifted), #61 is ExecuteIndirect, #70 is SetDepthBoundsX, + // and #83 is DrawIndexedX – none of these write indirect arguments. + !(shifted && matches!(slot, 61 | 70 | 83)) +} + /// The console list vtable: QueryInterface / AddRef / Release / Close / Reset of their own, /// every other slot a thunk to the currently active PC list's entry (`F_BACKING`). fn vtable() -> usize { @@ -67,7 +95,13 @@ fn vtable() -> usize { let mut v = vec![0usize; LIST_SLOTS]; let trace = std::env::var_os("XCL_LIST_TRACE").is_some(); for (slot, e) in v.iter_mut().enumerate() { - *e = if trace { forward_traced(slot) } else { forward(slot) }; + *e = if trace { + forward_precall(slot, record as usize) + } else if is_gpu_write_or_wait_slot(slot) { + forward_precall(slot, note_write_or_wait as usize) + } else { + forward(slot) + }; } v[0] = qi as usize; v[1] = add_ref as usize; @@ -93,8 +127,8 @@ fn forward(slot: usize) -> usize { p as usize } -/// `forward` after `record(this, slot)` (argument registers, xmm0–3 kept) -fn forward_traced(slot: usize) -> usize { +/// `forward` after calling `precall(this, slot)` (argument registers and xmm0–3 preserved). +fn forward_precall(slot: usize, precall: usize) -> usize { let mut c: Vec = vec![0x51, 0x52, 0x41, 0x50, 0x41, 0x51]; // push rcx, rdx, r8, r9 c.extend_from_slice(&[0x48, 0x83, 0xEC, 0x68]); // sub rsp, 0x68 for (reg, off) in [(0x44u8, 0x20u8), (0x4C, 0x30), (0x54, 0x40), (0x5C, 0x50)] { @@ -102,8 +136,8 @@ fn forward_traced(slot: usize) -> usize { } c.push(0xBA); // mov edx, slot c.extend_from_slice(&(slot as u32).to_le_bytes()); - c.extend_from_slice(&[0x48, 0xB8]); // mov rax, record - c.extend_from_slice(&(record as usize as u64).to_le_bytes()); + c.extend_from_slice(&[0x48, 0xB8]); // mov rax, precall + c.extend_from_slice(&(precall as u64).to_le_bytes()); c.extend_from_slice(&[0xFF, 0xD0]); // call rax for (reg, off) in [(0x44u8, 0x20u8), (0x4C, 0x30), (0x54, 0x40), (0x5C, 0x50)] { c.extend_from_slice(&[0xF3, 0x0F, 0x6F, reg, 0x24, off]); // movdqu xmmN, [rsp+off] @@ -121,11 +155,20 @@ fn forward_traced(slot: usize) -> usize { p as usize } +unsafe extern "system" fn note_write_or_wait(this: *mut c_void, slot: u32) { + let shifted = super::real::QUEUE_SHIFTED.load(std::sync::atomic::Ordering::Relaxed); + if slot_writes_or_waits_now(slot as usize, shifted) { + let pc = *((this as usize + F_BACKING) as *const *mut c_void); + super::bind::note_gpu_write(pc); + } +} + unsafe extern "system" fn record(this: *mut c_void, slot: u32) { let at = (this as usize + F_RING_AT) as *mut usize; let k = *at % RING; *((this as usize + F_RING + 2 * k) as *mut u16) = slot as u16; *at += 1; + note_write_or_wait(this, slot); } /// #9 Close: closes the active recording segment (`F_BACKING`); a failure is logged with @@ -245,18 +288,28 @@ pub fn backing(list: *mut c_void) -> Option<*mut c_void> { } /// Expand a console list object into all of its recorded PC command list segments (in exact -/// recording order). Returns `false` if `list` is not a `title_list` wrapper. +/// recording order), inserting any hoisted indirect-argument prelude list right before the +/// segment that consumes it. Returns `false` if `list` is not a `title_list` wrapper. pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { let Some(primary) = backing(list) else { return false; }; - let sg = SEGMENTS.lock().unwrap(); - let book = sg.as_ref().and_then(|m| m.get(&(list as usize))); - out.push(book.and_then(|b| b.first).map_or(primary, |f| f as *mut c_void)); - if let Some(book) = book { - for &seg in &book.extra_active { - out.push(seg as *mut c_void); + let (first, extras) = { + let sg = SEGMENTS.lock().unwrap(); + let book = sg.as_ref().and_then(|m| m.get(&(list as usize))); + let first = book.and_then(|b| b.first).map_or(primary, |f| f as *mut c_void); + let extras: Vec<*mut c_void> = book.map_or_else(Vec::new, |b| b.extra_active.iter().map(|&s| s as *mut c_void).collect()); + (first, extras) + }; + let push_with_prelude = |seg: *mut c_void, out: &mut Vec<*mut c_void>| { + if let Some(prelude) = unsafe { super::bind::prelude_list_for(seg) } { + out.push(prelude); } + out.push(seg); + }; + push_with_prelude(first, out); + for seg in extras { + push_with_prelude(seg, out); } true } @@ -309,19 +362,27 @@ pub(super) unsafe fn activate_segment(wrapper: *mut c_void, old_pc: *mut c_void, m.insert(new_pc as usize, wrapper as usize); } -/// For `KickoffX` on an already-split list: returns `(primary, prior_closed_segments, extra_to_reclaim)` -/// when `active_pc != primary`, switches `F_BACKING` back to `primary`, and moves all extra +/// For `KickoffX`: returns `(primary, prior_closed_segments, extra_to_reclaim)` when `active_pc` +/// was split mid-recording OR has hoisted indirect-argument prelude work that must execute right +/// before `active_pc`. When split, switches `F_BACKING` back to `primary` and moves all extra /// segments (including `active_pc`) into `spares` so recording resumes cleanly on `primary`. /// (`primary` here is the recording's first segment: `first` when one stands in.) pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut c_void, Vec<*mut c_void>, Vec)> { let wrapper = wrapper_of(active_pc)?; - let mut sg = SEGMENTS.lock().unwrap(); - let book = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize)))?; - let primary = book.first.map_or_else(|| *((wrapper as usize + F_PRIMARY) as *const *mut c_void), |f| f as *mut c_void); + let primary = { + let sg = SEGMENTS.lock().unwrap(); + sg.as_ref() + .and_then(|m| m.get(&(wrapper as usize))) + .and_then(|b| b.first) + .map_or_else(|| *((wrapper as usize + F_PRIMARY) as *const *mut c_void), |f| f as *mut c_void) + }; if primary == active_pc { - return None; + let prelude = super::bind::prelude_list_for(active_pc)?; + return Some((primary, vec![prelude], Vec::new())); } - let (prior, reclaimed) = { + let (raw_prior, reclaimed) = { + let mut sg = SEGMENTS.lock().unwrap(); + let book = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize)))?; let extra = std::mem::take(&mut book.extra_active); let mut prior = Vec::with_capacity(extra.len()); prior.push(primary); @@ -333,7 +394,6 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut book.spares.extend(extra.iter().copied()); (prior, extra) }; - drop(sg); *((wrapper as usize + F_BACKING) as *mut usize) = primary as usize; { let mut wg = WRAPPER_OF.lock().unwrap(); @@ -344,6 +404,16 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut m.insert(primary as usize, wrapper as usize); } } + let mut prior = Vec::with_capacity(raw_prior.len() * 2 + 1); + for seg in raw_prior { + if let Some(p) = super::bind::prelude_list_for(seg) { + prior.push(p); + } + prior.push(seg); + } + if let Some(p) = super::bind::prelude_list_for(active_pc) { + prior.push(p); + } Some((primary, prior, reclaimed)) } @@ -636,4 +706,24 @@ mod tests { drop(Box::from_raw(seg1)); } } + + #[test] + fn gpu_write_and_wait_slots_track_older_and_newer_layouts() { + // Common buffer-write / bundle / clear / wait slots block prelude hoisting on both layouts. + for slot in [15, 16, 17, 18, 27, 30, 53, 54, 60, 62, 71, 72, 84, 86, 88, 89, 90, 91, 92, 104, 105] { + assert!(slot_writes_or_waits_now(slot, false), "older slot {slot}"); + assert!(slot_writes_or_waits_now(slot, true), "newer slot {slot}"); + } + // On the newer (+2 shifted) layout, #61 is ExecuteIndirect, #70 is SetDepthBoundsX, and + // #83 is DrawIndexedX – must NOT block hoisting when shifted, while blocking on older. + for slot in [61, 70, 83] { + assert!(slot_writes_or_waits_now(slot, false), "older slot {slot}"); + assert!(!slot_writes_or_waits_now(slot, true), "newer non-write slot {slot}"); + } + // Hot draw / PSO / root-arg slots never block prelude hoisting. + for slot in [12, 13, 25, 34, 36, 38, 40, 42, 44, 46, 59, 127, 129] { + assert!(!slot_writes_or_waits_now(slot, false), "non-write slot {slot}"); + assert!(!slot_writes_or_waits_now(slot, true), "non-write slot {slot}"); + } + } } From 5ce71b651e371abcae0b0195e6216ecc5ed7af05 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:23:06 +0100 Subject: [PATCH 089/258] D3D12.X: fall back to smaller dispatch-chain slabs on scratch OOM When growing a recording's split-compute scratch buffer fails under VRAM pressure in dispatch_chain::scratch_for, returning None forced dispatch() into Chain::whole() (stalling the title thread compiling the unsplit shader). Fall back to reusing the list's existing scratch buffer with smaller slabs when it already holds at least one workgroup, or try a minimal 1-workgroup scratch allocation before falling back to Chain::whole(). Includes focused unit tests for scratch_oom_fallback. Verified with cargo check -p xcl --tests (0 errors and 0 warnings in dispatch_chain.rs). Assisted-by: Antigravity (Gemini 4 Neon High) --- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 50 +++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 7cf8f5a012..b6b9ddf7e0 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -223,16 +223,46 @@ fn scratch_bytes(needed: u64, group: u64, budget: u64, had: Option, live: u } } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ScratchOomFallback { + /// Reuse the recording's existing scratch buffer (running smaller slabs). + ReuseExisting, + /// Allocate a minimal 1-workgroup scratch buffer instead of falling back to `Chain::whole()`. + TryMinimal(u64), + /// Neither existing reuse nor a smaller allocation is viable. + None, +} + +/// Choose a smaller-slab fallback when growing `scratch_buffer` fails under VRAM pressure. +fn scratch_oom_fallback(had_bytes: Option, attempted: u64, group: u64) -> ScratchOomFallback { + if had_bytes.is_some_and(|h| h >= group) { + ScratchOomFallback::ReuseExisting + } else if attempted > group { + ScratchOomFallback::TryMinimal(group) + } else { + ScratchOomFallback::None + } +} + /// A scratch for a chain of `needed` bytes recorded on `list` with `allocator`, and whether a /// chain before it on the list used it. unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, needed: u64, group: u64) -> Option<(Arc, bool)> { let had = SHARED.lock().unwrap().get(&list).filter(|s| s.0 == allocator).and_then(|s| s.1.upgrade()); - let (bytes, make) = scratch_bytes(needed, group, scratch_budget(), had.as_ref().map(|s| s.bytes), LIVE.load(Ordering::Relaxed), scratch_total()); + let had_bytes = had.as_ref().map(|s| s.bytes); + let (bytes, make) = scratch_bytes(needed, group, scratch_budget(), had_bytes, LIVE.load(Ordering::Relaxed), scratch_total()); if !make { return had.map(|s| (s, true)); } - let s = Arc::new(Scratch { buffer: scratch_buffer(dev, bytes)?, bytes }); - let live = LIVE.fetch_add(bytes, Ordering::Relaxed) + bytes; + let (buffer, actual) = match scratch_buffer(dev, bytes) { + Some(b) => (b, bytes), + None => match scratch_oom_fallback(had_bytes, bytes, group) { + ScratchOomFallback::ReuseExisting => return had.map(|s| (s, true)), + ScratchOomFallback::TryMinimal(min_bytes) => (scratch_buffer(dev, min_bytes)?, min_bytes), + ScratchOomFallback::None => return None, + }, + }; + let s = Arc::new(Scratch { buffer, bytes: actual }); + let live = LIVE.fetch_add(actual, Ordering::Relaxed) + actual; PEAK.fetch_max(live, Ordering::Relaxed); SHARED.lock().unwrap().insert(list, (allocator, Arc::downgrade(&s))); Some((s, false)) @@ -319,4 +349,18 @@ mod tests { assert!(matches!(unsafe { super::whole_nonblocking(0) }, super::WholeStatus::NotSplit)); assert!(matches!(unsafe { super::whole_nonblocking(0x7800_0001) }, super::WholeStatus::NotSplit)); } + + #[test] + fn scratch_oom_fallback_reuses_existing_or_shrinks_to_one_group() { + use super::{scratch_oom_fallback, ScratchOomFallback}; + let group = 256 << 10; + // Existing list scratch fits >= 1 group: reuse it with smaller slabs instead of Chain::whole. + assert_eq!(scratch_oom_fallback(Some(2 * MB), 64 * MB, group), ScratchOomFallback::ReuseExisting); + assert_eq!(scratch_oom_fallback(Some(group), 64 * MB, group), ScratchOomFallback::ReuseExisting); + // No usable existing scratch, attempted > 1 group: shrink to minimal 1-group scratch. + assert_eq!(scratch_oom_fallback(None, 64 * MB, group), ScratchOomFallback::TryMinimal(group)); + assert_eq!(scratch_oom_fallback(Some(group - 1), 4 * MB, group), ScratchOomFallback::TryMinimal(group)); + // Already attempted minimal 1-group allocation with no usable existing scratch: give up. + assert_eq!(scratch_oom_fallback(None, group, group), ScratchOomFallback::None); + } } From ba41b03083e38b3e9e84370bd3c769765e4ec16c Mon Sep 17 00:00:00 2001 From: Emu Synths Date: Wed, 25 Nov 2026 13:02:59 -0600 Subject: [PATCH 090/258] Recompiler: enable scalar reload CSE for direct DXIL vertex and pixel shaders Enable reload::analyze for Entry::Vertex and Entry::Pixel in the direct DXIL translator. Unlike two-phase Entry::Geometry, vertex and pixel shaders use the same single-entry Cfg::build as compute, so repeated s_load_dword* descriptor reloads can safely reuse their first values and avoid redundant memory-window switches. Part of #2088 Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/kernel.rs | 6 ++--- crates/xcl/src/gpu/dxil/reload.rs | 38 +++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 5801707707..a931432b3e 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -195,7 +195,7 @@ fn translate_on_this_thread( None => Cfg::build(code)?, }; let kernel = matches!(entry, Entry::Kernel); - let follow_loads = matches!(entry, Entry::Kernel | Entry::Compute(_)); + let follow_loads = matches!(entry, Entry::Kernel | Entry::Compute(_) | Entry::Vertex(_) | Entry::Pixel(_)); let gfx = matches!(entry, Entry::Vertex(_) | Entry::Pixel(_)); let compute = matches!(entry, Entry::Compute(_)); let split = o.wave64 && o.split && !gfx; @@ -334,8 +334,8 @@ fn translate_on_this_thread( lw.edge(Block(0), h0); } let switch = if two_phase { Some(lw.block(None)) } else { None }; - // scalar loads the program repeats keep their first values (compute programs and kernels: - // the other stages enter their code by edges the CFG does not hold) + // scalar loads the program repeats keep their first values (compute, vertex, pixel and + // kernel: geometry enters its GS blocks by edges the CFG does not hold) let reloads = if follow_loads { super::reload::analyze(&cfg) } else { Default::default() }; let mut gs_entry: Option = None; if let Some(p) = &plan { diff --git a/crates/xcl/src/gpu/dxil/reload.rs b/crates/xcl/src/gpu/dxil/reload.rs index 47beaa5103..96dfc2cdf1 100644 --- a/crates/xcl/src/gpu/dxil/reload.rs +++ b/crates/xcl/src/gpu/dxil/reload.rs @@ -365,6 +365,44 @@ mod tests { assert_eq!(buffer_loads(&[LOAD, ADD, store, LOAD, sum, END]), buffer_loads(&[LOAD, ADD, store, sum, END]) + 1, "a store in between: loaded again"); } + #[test] + fn graphics_stages_emit_a_repeated_load_once() { + use super::super::kernel::{translate_pixel, translate_vertex, KernelOptions}; + use crate::gpu::recomp::{PsInterface, VsInterface}; + + let encode = |insts: &[I]| -> Vec { + insts.iter().flat_map(|(n, e, f)| rdna2::encode(n, e, f, None).unwrap()).collect() + }; + let count_loads = |dxil: &[u8]| -> usize { + super::super::validate::validate(dxil).expect("valid DXIL"); + let dis = super::super::validate::disassemble(dxil).expect("disassemble"); + dis.lines().filter(|l| l.contains("@dx.op.rawBufferLoad") && l.contains(" = call ")).count() + }; + let opts = KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }; + let sum: I = ("S_ADD_U32", "ENC_SOP2", &[("SDST", 21), ("SSRC0", 20), ("SSRC1", 12)]); + let store: I = ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 2), ("SADDR", 125)]); + let once_code = encode(&[LOAD, ADD, END]); + let repeat_code = encode(&[LOAD, ADD, LOAD, sum, END]); + let store_once_code = encode(&[LOAD, ADD, store, sum, END]); + let store_repeat_code = encode(&[LOAD, ADD, store, LOAD, sum, END]); + + let vs = VsInterface::default(); + let vs_once = count_loads(&translate_vertex(&once_code, opts, &vs).expect("VS once").dxil); + let vs_repeat = count_loads(&translate_vertex(&repeat_code, opts, &vs).expect("VS repeat").dxil); + assert_eq!(vs_repeat, vs_once, "VS repeated s_load_dwordx4 should reuse cached values"); + let vs_store_once = count_loads(&translate_vertex(&store_once_code, opts, &vs).expect("VS store once").dxil); + let vs_store_repeat = count_loads(&translate_vertex(&store_repeat_code, opts, &vs).expect("VS store repeat").dxil); + assert_eq!(vs_store_repeat, vs_store_once + 4, "VS store should invalidate reload across 4 windows"); + + let ps = PsInterface::default(); + let ps_once = count_loads(&translate_pixel(&once_code, opts, &ps).expect("PS once").dxil); + let ps_repeat = count_loads(&translate_pixel(&repeat_code, opts, &ps).expect("PS repeat").dxil); + assert_eq!(ps_repeat, ps_once, "PS repeated s_load_dwordx4 should reuse cached values"); + let ps_store_once = count_loads(&translate_pixel(&store_once_code, opts, &ps).expect("PS store once").dxil); + let ps_store_repeat = count_loads(&translate_pixel(&store_repeat_code, opts, &ps).expect("PS store repeat").dxil); + assert_eq!(ps_store_repeat, ps_store_once + 4, "PS store should invalidate reload across 4 windows"); + } + /// Every output operand type of the instruction tables is one `changes` knows: a new one /// must be looked at here, not passed over. #[test] From 3806dba7b768e9c1c2bf5eda875b351c700d1315 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:51:21 +0300 Subject: [PATCH 091/258] dxil: emit InnerCoverage, ShadingRate, MeshDerivatives, and 64UAVs flags in graphics shaders Shader::try_finish_graphics previously omitted four DXIL shader/SFI0 flag bits required by dxil.dll when the corresponding graphics features are present: - InnerCoverage (1 << 10 / SFI0 0x400) for pixel shaders with a surviving post-optimize dx.op.innerCoverage (op 92) call. - ShadingRate (1 << 24 / SFI0 0x8_0000) for vertex outputs and pixel inputs carrying SemKind::ShadingRate (not mesh primitive outputs). - DerivativesInMeshAndAmpShaders (1 << 29 / SFI0 0x100_0000) for mesh shaders with surviving post-optimize derivatives or implicit-LOD ops (unary 83..=86, sample 60, sampleBias 61, sampleCmp 64, calculateLOD 81). - 64UAVs (1 << 15 / SFI0 0x8) across vertex, pixel, and mesh stages when more than 8 static UAV bindings are declared. Scan surviving post-optimize instructions for inner coverage and mesh derivatives so eliminated calls in unreachable blocks or DCE'd derivatives do not leave spurious flags, and add DXC-validated unit tests covering each flag and its negative guards. Part of #1401 Part of #1833 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/graphics.rs | 40 +++++++- crates/xcl/src/gpu/dxil/graphics_tests.rs | 107 ++++++++++++++++++++++ 2 files changed, 145 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/graphics.rs b/crates/xcl/src/gpu/dxil/graphics.rs index 239a923ea9..5dcf2f1752 100644 --- a/crates/xcl/src/gpu/dxil/graphics.rs +++ b/crates/xcl/src/gpu/dxil/graphics.rs @@ -1008,11 +1008,47 @@ impl Shader { sfi0 |= 0x10; } // Bound UAVs outside pixel/compute shaders (DXC: not for mesh shaders, - // nor for heap-indexed UAVs). - if self.stage == Stage::Vertex && self.bindings.iter().any(|b| b.class == ResClass::Uav) { + // nor for heap-indexed UAVs); >8 static UAVs require the 64-UAVs flag on every stage. + let uav_count = self.bindings.iter().filter(|b| b.class == ResClass::Uav).count(); + if self.stage == Stage::Vertex && uav_count > 0 { flags |= 1 << 16; sfi0 |= 0x4; } + if uav_count > 8 { + flags |= 1 << 15; + sfi0 |= 0x8; + } + if match self.stage { + Stage::Vertex => outs.iter().any(|e| e.e.kind == SemKind::ShadingRate), + Stage::Pixel => ins.iter().any(|e| e.e.kind == SemKind::ShadingRate), + _ => false, + } { + flags |= 1 << 24; + sfi0 |= 0x8_0000; + } + if matches!(self.stage, Stage::Pixel | Stage::Mesh) { + let (mut inner_cov, mut mesh_deriv) = (false, false); + for b in 0..self.m.block_count() { + for &inst in self.m.block_insts(Block(b as u32)) { + let InstInfo::Call(name, args) = self.m.inst_info(inst) else { continue }; + let op = args.first().and_then(|&v| self.m.const_u64(v)); + inner_cov |= name.starts_with("dx.op.innerCoverage.") && op == Some(92); + mesh_deriv |= (name.starts_with("dx.op.unary.") && op.is_some_and(|o| (83..=86).contains(&o))) + || (name.starts_with("dx.op.sample.") && op == Some(60)) + || (name.starts_with("dx.op.sampleBias.") && op == Some(61)) + || (name.starts_with("dx.op.sampleCmp.") && op == Some(64)) + || (name.starts_with("dx.op.calculateLOD.") && op == Some(81)); + } + } + if self.stage == Stage::Mesh && mesh_deriv { + flags |= 1 << 29; + sfi0 |= 0x100_0000; + } + if self.stage == Stage::Pixel && inner_cov { + flags |= 1 << 10; + sfi0 |= 0x400; + } + } if self.stage == Stage::Pixel { if outs.iter().any(|e| e.e.kind == SemKind::StencilRef) { flags |= 1 << 11; diff --git a/crates/xcl/src/gpu/dxil/graphics_tests.rs b/crates/xcl/src/gpu/dxil/graphics_tests.rs index c8f3802053..8228f179e2 100644 --- a/crates/xcl/src/gpu/dxil/graphics_tests.rs +++ b/crates/xcl/src/gpu/dxil/graphics_tests.rs @@ -1236,3 +1236,110 @@ fn ps_static_resources_match_dxc() { assert_eq!(part(&c, b"SFI0"), part(DXC_PS_RESOURCES, b"SFI0")); assert_valid(&c); } + +fn assert_flags(c: &[u8], want_sfi0: u64, want_meta: u64, label: &str) { + assert_eq!(u64::from_le_bytes(part(c, b"SFI0").unwrap().try_into().unwrap()), want_sfi0, "{label}: SFI0"); + assert_valid(c); + if crate::gpu::recomp::dxc::location().is_ok() { + let dis = validate::disassemble(c).unwrap(); + let ok = if want_meta != 0 { dis.contains(&format!("!{{i32 0, i64 {want_meta}}}")) || dis.contains(&format!("!{{i32 0, i64 {want_meta},")) } else { !dis.contains("!{i32 0, i64 ") }; + assert!(ok, "{label}: meta {want_meta:#x} in:\n{dis}"); + } +} + +fn finish_ms_with(mut s: Shader, mut io: GraphicsIo, x: Value, prim: Option) -> Vec { + let pos = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let (c0, c1, c2, c3, z) = (s.m.i32c(0), s.m.i32c(1), s.m.i32c(2), s.m.i32c(3), f(&mut s, 0.0)); + io.set_mesh_output_counts(&mut s, c3, c1); + for (c, &v) in [x, z, z, z].iter().enumerate() { io.store_vertex_output(&mut s, pos, 0, c as u8, v, c0); } + io.emit_indices(&mut s, c0, &[c0, c1, c2]); + if let Some(p) = prim { io.store_primitive_output(&mut s, p, 0, 0, c0, c0); } + s.finish_graphics(io, StageInfo::Mesh { numthreads: [4, 1, 1], max_vertices: 3, max_primitives: 1, topology: Topology::Triangle, payload_bytes: 0 }) +} + +#[test] +fn ps_inner_coverage_sets_flag_only_when_live() { + for live in [true, false] { + let (mut s, mut io) = (Shader::new(Stage::Pixel, (6, 6)), GraphicsIo::new(Stage::Pixel)); + let t = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::U32, 1)); + let out = if live { io.inner_coverage(&mut s) } else { + let (dead, cont) = (s.m.new_block(), s.m.new_block()); + s.m.br(cont); s.m.set_block(dead); let _ = io.inner_coverage(&mut s); s.m.br(cont); s.m.set_block(cont); + s.m.i32c(0) + }; + io.store_output(&mut s, t, 0, 0, out); + let c = s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }); + assert_flags(&c, if live { 0x400 } else { 0 }, if live { 1 << 10 } else { 0 }, if live { "ps_inner_cov_live" } else { "ps_inner_cov_dead" }); + } +} + +#[test] +fn shading_rate_sets_flag_for_vs_and_ps_but_not_ms() { + let (mut vs, mut vio) = (Shader::new(Stage::Vertex, (6, 6)), GraphicsIo::new(Stage::Vertex)); + let vp = vio.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + let vr = vio.output(SigElement::new("SV_ShadingRate", 0, SemKind::ShadingRate, CompType::U32, 1)); + let (z, r) = (f(&mut vs, 0.0), vs.m.i32c(0)); + for c in 0..4 { vio.store_output(&mut vs, vp, 0, c, z); } + vio.store_output(&mut vs, vr, 0, 0, r); + assert_flags(&vs.finish_graphics(vio, StageInfo::Vertex), 0x8_0000, 1 << 24, "vs_shading_rate"); + let (mut ps, mut pio) = (Shader::new(Stage::Pixel, (6, 6)), GraphicsIo::new(Stage::Pixel)); + let _ = pio.input(SigElement::new("SV_ShadingRate", 0, SemKind::ShadingRate, CompType::U32, 1)); + let pt = pio.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::U32, 1)); + let pz = ps.m.i32c(0); + pio.store_output(&mut ps, pt, 0, 0, pz); + assert_flags(&ps.finish_graphics(pio, StageInfo::Pixel { early_depth_stencil: false }), 0x8_0000, 1 << 24, "ps_shading_rate"); + let (mut ms, mut mio) = (Shader::new(Stage::Mesh, (6, 6)), GraphicsIo::new(Stage::Mesh)); + let mr = mio.primitive(SigElement::new("SV_ShadingRate", 0, SemKind::ShadingRate, CompType::U32, 1)); + let mz = f(&mut ms, 0.0); + assert_flags(&finish_ms_with(ms, mio, mz, Some(mr)), 0, 0, "ms_shading_rate"); +} + +#[test] +fn ms_derivatives_and_implicit_lod_set_flag_but_explicit_lod_does_not() { + use crate::gpu::dxil::ops::{CompType as OpsComp, Deriv, TexKind}; + for kind in ["deriv", "sample", "sample_bias", "sample_cmp", "calc_lod", "sample_level", "dead_deriv"] { + let (mut s, io) = (Shader::new(Stage::Mesh, (6, 6)), GraphicsIo::new(Stage::Mesh)); + let (tid, f32, z) = (s.thread_id_in_group(0), s.m.f32(), f(&mut s, 0.0)); + let u = s.m.cast(CastOp::UIToFP, tid, f32); + let val = if kind == "deriv" { s.deriv(Deriv::FineX, u) } else if kind == "dead_deriv" { let _ = s.deriv(Deriv::FineX, u); z } else { + let (tex, smp) = (s.srv_texture(0, 0, TexKind::D2, OpsComp::F32, 4), s.sampler(0, 0, kind == "sample_cmp")); + match kind { + "sample" => s.sample(tex, smp, &[u, z], &[], None)[0], + "sample_bias" => s.sample_bias(tex, smp, &[u, z], &[], z, None)[0], + "sample_cmp" => s.sample_cmp(tex, smp, &[u, z], &[], z, None)[0], + "calc_lod" => s.calculate_lod(tex, smp, &[u, z], true), + _ => s.sample_level(tex, smp, &[u, z], &[], z)[0], + } + }; + let needs = !matches!(kind, "sample_level" | "dead_deriv"); + assert_flags(&finish_ms_with(s, io, val, None), if needs { 0x100_0000 } else { 0 }, if needs { 1 << 29 } else { 0 }, kind); + } +} + +#[test] +fn graphics_64_uavs_flag_tracks_static_uav_count() { + const RAW: u64 = 1 << 4; + let run = |stage: Stage, slots: &[u32]| { + let (mut s, mut io) = (Shader::new(stage, (6, 6)), GraphicsIo::new(stage)); + let (z, mut acc) = (s.m.i32c(0), s.m.i32c(0)); + for &u in slots { let h = s.raw_uav(u, 0); let v = s.raw_load(h, z, 1)[0]; acc = s.m.bin(BinOp::Add, acc, v); } + if stage == Stage::Pixel { + let t = io.output(SigElement::new("SV_Target", 0, SemKind::Target, CompType::U32, 1)); + io.store_output(&mut s, t, 0, 0, acc); + return s.finish_graphics(io, StageInfo::Pixel { early_depth_stencil: false }); + } + let vf = { let t = s.m.f32(); s.m.cast(CastOp::UIToFP, acc, t) }; + if stage == Stage::Mesh { return finish_ms_with(s, io, vf, None); } + let p = io.output(SigElement::new("SV_Position", 0, SemKind::Position, CompType::F32, 4)); + for c in 0..4 { io.store_output(&mut s, p, 0, c, vf); } + s.finish_graphics(io, StageInfo::Vertex) + }; + let (nine, eight): (Vec, Vec) = ((0..9).collect(), (0..8).collect()); + for (st, slots, sfi, meta, lbl) in [ + (Stage::Vertex, &nine[..], 0xC, (1 << 15) | (1 << 16) | RAW, "vs_9uav"), + (Stage::Pixel, &nine[..], 0x8, (1 << 15) | RAW, "ps_9uav"), + (Stage::Mesh, &nine[..], 0x8, (1 << 15) | RAW, "ms_9uav"), + (Stage::Pixel, &eight[..], 0, RAW, "ps_8uav"), + (Stage::Pixel, &[8][..], 0, RAW, "ps_single_u8"), + ] { assert_flags(&run(st, slots), sfi, meta, lbl); } +} From f02c0fc42182ca94a4b846d78bf928142d12e083 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:29:30 +0300 Subject: [PATCH 092/258] D3D12.X: strip console-only root-signature flags in D3D12SerializeRootSignature `D3D12SerializeVersionedRootSignature` already stripped Xbox console-only flag bits above `PC_FLAGS = 0xFFF` (e.g. `0x3000000`) and logged/cleaned up error blobs, whereas 1.0 `D3D12SerializeRootSignature` forwarded raw `D3D12_ROOT_SIGNATURE_DESC` straight to Windows `d3d12.dll`, which rejects unknown flag bits with `E_INVALIDARG`. - Share `PC_FLAGS = 0xFFF`, aligned stack-copy flag sanitization (`+32` in 40-byte `D3D12_ROOT_SIGNATURE_DESC`, `+40` in 48-byte `D3D12_VERSIONED_ROOT_SIGNATURE_DESC`), and error-blob logging/cleanup across both serializers via `serialize_root_sig`. - Zero caller-supplied `*err` before forwarding so failed calls never leave or dereference uninitialized pointers. - Add a WARP/CPU unit test verifying layout offsets, console-flag stripping with PC-flag preservation via `D3D12CreateRootSignatureDeserializer`, caller descriptor immutability, and error-blob handling. Part of #1452 Part of #1333 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/hle/d3d12x/mod.rs | 119 ++++++++++++++++++++++--------- 1 file changed, 85 insertions(+), 34 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 89f95b8040..99944adb53 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -139,46 +139,31 @@ pub unsafe extern "system" fn D3D12GetDebugInterface(riid: *const c_void, ppv: * forward!("D3D12GetDebugInterface", unsafe extern "system" fn(*const c_void, *mut *mut c_void) -> HRESULT, null::D3D12GetDebugInterface, (riid, ppv)) } -pub unsafe extern "system" fn D3D12SerializeRootSignature(d: *const c_void, v: u32, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT { - forward!( - "D3D12SerializeRootSignature", - unsafe extern "system" fn(*const c_void, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT, - null::D3D12SerializeRootSignature, - (d, v, blob, err) - ) -} +// console-only root signature flags (seen: 0x3000000 from XboxBvhBuilder.dll) – Windows +// rejects unknown bits; flags sit at +32 in 40-byte 1.0 desc and +40 in 48-byte versioned desc +const PC_FLAGS: u32 = 0xFFF; -pub unsafe extern "system" fn D3D12SerializeVersionedRootSignature(d: *const c_void, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT { +unsafe fn serialize_root_sig( + name: &str, d: *const c_void, flags_off: usize, err: *mut *mut c_void, + meta: impl FnOnce(*const u8) -> (u32, u32, u32, u32), + call: impl FnOnce(*const c_void, *mut *mut c_void) -> HRESULT, +) -> HRESULT { let mut own_err: *mut c_void = std::ptr::null_mut(); - let e = if err.is_null() { &mut own_err as *mut _ } else { err }; - // console-only root signature flags (seen: 0x3000000 from XboxBvhBuilder.dll) – Windows - // rejects unknown bits; the flags sit at +40 in every version of the desc (48 bytes) - const PC_FLAGS: u32 = 0xFFF; - let mut copy = [0u8; 48]; + let e = if err.is_null() { &mut own_err as *mut _ } else { *err = std::ptr::null_mut(); err }; + let mut copy = [0u64; QWORDS]; let mut d = d; - if !d.is_null() && *(d as *const u8).add(40).cast::() & !PC_FLAGS != 0 { - std::ptr::copy_nonoverlapping(d as *const u8, copy.as_mut_ptr(), 48); - let f = copy.as_mut_ptr().add(40).cast::(); - crate::xlog_info!("D3D12SerializeVersionedRootSignature: console flags {:#x} dropped", *f & !PC_FLAGS); + if !d.is_null() && (d as *const u8).add(flags_off).cast::().read_unaligned() & !PC_FLAGS != 0 { + let dst = copy.as_mut_ptr().cast::(); + std::ptr::copy_nonoverlapping(d.cast::(), dst, QWORDS * 8); + let f = dst.add(flags_off).cast::(); + crate::xlog_info!("{name}: console flags {:#x} dropped", *f & !PC_FLAGS); *f &= PC_FLAGS; - d = copy.as_ptr() as *const c_void; + d = dst.cast::(); } - type Serialize = unsafe extern "system" fn(*const c_void, *mut *mut c_void, *mut *mut c_void) -> HRESULT; - let hr = match sys("D3D12SerializeVersionedRootSignature").filter(|_| backend() == Backend::Real) { - Some(f) => std::mem::transmute::<_, Serialize>(f)(d, blob, e), - None => null::D3D12SerializeVersionedRootSignature(d, blob, e), - }; + let hr = call(d, e); if hr < 0 && !d.is_null() { - // D3D12_VERSIONED_ROOT_SIGNATURE_DESC: version, then (1.1 / 1.2) parameters, samplers, flags - let w = |o: usize| *(d as *const u8).add(o).cast::(); - let text = blob_text(*e); - crate::xlog_warn!( - "D3D12SerializeVersionedRootSignature: {hr:#x} (version {}, parameters {}, samplers {}, flags {:#x}): {text}", - w(0), - w(8), - w(24), - w(40) - ); + let (ver, params, samplers, flags) = meta(d.cast::()); + crate::xlog_warn!("{name}: {hr:#x} (version {ver}, parameters {params}, samplers {samplers}, flags {flags:#x}): {}", blob_text(*e)); } if err.is_null() && !own_err.is_null() { blob_release(own_err); @@ -186,6 +171,26 @@ pub unsafe extern "system" fn D3D12SerializeVersionedRootSignature(d: *const c_v hr } +pub unsafe extern "system" fn D3D12SerializeRootSignature(d: *const c_void, v: u32, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT { + type Serialize = unsafe extern "system" fn(*const c_void, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT; + serialize_root_sig::<5>("D3D12SerializeRootSignature", d, 32, err, |p| (v, p.cast::().read_unaligned(), p.add(16).cast::().read_unaligned(), p.add(32).cast::().read_unaligned()), |d, e| { + match sys("D3D12SerializeRootSignature").filter(|_| backend() == Backend::Real) { + Some(f) => std::mem::transmute::<_, Serialize>(f)(d, v, blob, e), + None => null::D3D12SerializeRootSignature(d, v, blob, e), + } + }) +} + +pub unsafe extern "system" fn D3D12SerializeVersionedRootSignature(d: *const c_void, blob: *mut *mut c_void, err: *mut *mut c_void) -> HRESULT { + type Serialize = unsafe extern "system" fn(*const c_void, *mut *mut c_void, *mut *mut c_void) -> HRESULT; + serialize_root_sig::<6>("D3D12SerializeVersionedRootSignature", d, 40, err, |p| (p.cast::().read_unaligned(), p.add(8).cast::().read_unaligned(), p.add(24).cast::().read_unaligned(), p.add(40).cast::().read_unaligned()), |d, e| { + match sys("D3D12SerializeVersionedRootSignature").filter(|_| backend() == Backend::Real) { + Some(f) => std::mem::transmute::<_, Serialize>(f)(d, blob, e), + None => null::D3D12SerializeVersionedRootSignature(d, blob, e), + } + }) +} + /// text of an ID3DBlob (error messages) unsafe fn blob_text(b: *mut c_void) -> String { if b.is_null() { @@ -257,3 +262,49 @@ pub unsafe extern "system" fn D3D12ConfigureVirtualMemoryX(config: *const c_void } S_OK } + +#[cfg(test)] +mod tests { + use super::*; + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::ID3DBlob; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_ROOT_SIGNATURE_DESC, D3D12_ROOT_SIGNATURE_FLAGS, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, + D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS, D3D12_VERSIONED_ROOT_SIGNATURE_DESC, + D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0, D3D_ROOT_SIGNATURE_VERSION_1_0, ID3D12RootSignatureDeserializer, + }; + + #[test] + fn serialize_root_signature_strips_console_flags_and_preserves_pc_flags() { + assert_eq!((std::mem::size_of::(), std::mem::offset_of!(D3D12_ROOT_SIGNATURE_DESC, Flags)), (40, 32)); + assert_eq!((std::mem::size_of::(), std::mem::offset_of!(D3D12_VERSIONED_ROOT_SIGNATURE_DESC, Anonymous) + std::mem::offset_of!(D3D12_ROOT_SIGNATURE_DESC, Flags)), (48, 40)); + unsafe { + let deser_flags = |blob_raw: *mut c_void| -> D3D12_ROOT_SIGNATURE_FLAGS { + let blob = ID3DBlob::from_raw(blob_raw); + let mut deser_raw = std::ptr::null_mut(); + assert_eq!(D3D12CreateRootSignatureDeserializer(blob.GetBufferPointer(), blob.GetBufferSize(), (&ID3D12RootSignatureDeserializer::IID as *const windows::core::GUID).cast(), &mut deser_raw), S_OK); + (*ID3D12RootSignatureDeserializer::from_raw(deser_raw).GetRootSignatureDesc()).Flags + }; + let pc_flags = D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | D3D12_ROOT_SIGNATURE_FLAG_DENY_PIXEL_SHADER_ROOT_ACCESS; + let raw_flags = D3D12_ROOT_SIGNATURE_FLAGS(pc_flags.0 | 0x0300_0000); + let desc = D3D12_ROOT_SIGNATURE_DESC { Flags: raw_flags, ..Default::default() }; + let (mut blob_raw, mut vblob_raw) = (std::ptr::null_mut(), std::ptr::null_mut()); + assert_eq!(D3D12SerializeRootSignature(&desc as *const _ as *const c_void, D3D_ROOT_SIGNATURE_VERSION_1_0.0 as u32, &mut blob_raw, std::ptr::null_mut()), S_OK); + assert_eq!(desc.Flags, raw_flags, "caller descriptor must not be mutated"); + assert_eq!(deser_flags(blob_raw), pc_flags); + + let vdesc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { Version: D3D_ROOT_SIGNATURE_VERSION_1_0, Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { Desc_1_0: desc } }; + assert_eq!(D3D12SerializeVersionedRootSignature(&vdesc as *const _ as *const c_void, &mut vblob_raw, std::ptr::null_mut()), S_OK); + assert_eq!(deser_flags(vblob_raw), pc_flags); + + let (mut out, mut err_out) = (std::ptr::null_mut(), 1usize as *mut c_void); + assert!(D3D12SerializeRootSignature(&desc as *const _ as *const c_void, 99, &mut out, std::ptr::null_mut()) < 0); + assert!(D3D12SerializeRootSignature(&desc as *const _ as *const c_void, 99, &mut out, &mut err_out) < 0); + assert!(blob_text(err_out).contains("version"), "caller error blob missing diagnostic"); + blob_release(err_out); + err_out = 1usize as *mut c_void; + assert!(D3D12SerializeRootSignature(std::ptr::null(), D3D_ROOT_SIGNATURE_VERSION_1_0.0 as u32, &mut out, &mut err_out) < 0); + assert!(err_out.is_null()); + } + } +} From aabb15cd8c7e663dcb6da850db71579b24bee02c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:29:58 +0100 Subject: [PATCH 093/258] D3D12.X: resolve GPU-view root descriptors to UMA before sparse mirror bind::readable_root previously bypassed real::resolve_uma_va and fell straight into the read-only sparse::gpu_view mirror, leaving GPU-view root UAV writes unreflected and taking the gpu_view lock even for VAs already inside UMA. Consult real::resolve_uma_va(va, 0x1000) first in readable_root so contiguous GPU-view root descriptors resolve zero-copy into UMA (supporting both reads and root UAV writes) and UMA VAs return without locking sparse::gpu_view, falling back to sparse::gpu_view::base_for only for scattered mappings. Verified with cargo check -p xcl --lib (exit 0, 0 new warnings). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index a835d68d1d..877226a9e0 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -523,10 +523,13 @@ pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_v put_in(this, true, i, 0, &va.to_le_bytes()); } -/// The address a root descriptor at `va` gets (`sparse::gpu_view`): a root descriptor has no -/// size, so as much of the tile is taken as lies in the view. A read through it is in step with -/// the title's memory, a write is not (a root UAV in a GPU view stays what it was before). +/// The address a root descriptor at `va` gets: first try resolving a GPU-view VA directly to +/// contiguous UMA backing (`real::resolve_uma_va`, zero-copy for both reads and root UAV writes), +/// then fall back to the read-only `sparse::gpu_view` mirror for scattered mappings. fn readable_root(va: u64) -> u64 { + if let Some(u) = super::real::resolve_uma_va(va, 0x1000) { + return u; + } for len in [0x1_0000usize, 0x1000] { if let Some(b) = super::sparse::gpu_view::base_for(va as usize, len) { return b as u64; From 119c89b1dc67b50c3c2b3413424039cdbce2c484 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:29:56 +0100 Subject: [PATCH 094/258] Recompiler: make HLSL heap memory windows branchless via MEM_HEAP_NULL Port #1695's null raw UAV slot (MEM_HEAP_NULL) for out-of-range heap memory windows so HLSL mem_accessors replace per-access [branch] if (xcl_w >= N) guards with branchless min/select index clamping. Large two-pass mesh graphics PSOs on AMD RDNA4 carry 256-491 KiB HLSL pixel shaders with up to ~800 heap memory accesses (1,300+ conditional branches and 4,100+ PHIs), taking 6.4-18.1s in the driver compiler. Removing the per-access branch eliminates ~60% of basic blocks and handle PHIs across all HLSL shader stages. Also check D3D12_OPTIONS11 AtomicInt64OnDescriptorHeapResourceSupported inside console_heap::set_window_views so devices lacking 64-bit heap atomics fall back cleanly, and update runner and unit tests for MEM_HEAP_NULL. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/recomp/emit.rs | 16 ++--- crates/xcl/src/gpu/recomp/mod.rs | 11 +++- crates/xcl/src/gpu/recomp/pso.rs | 2 +- crates/xcl/src/gpu/recomp/runner.rs | 10 ++- crates/xcl/src/gpu/recomp/tests.rs | 74 +++++++++++++++++------ crates/xcl/src/gpu/uma.rs | 5 +- crates/xcl/src/hle/d3d12x/console_heap.rs | 42 +++++++++---- 7 files changed, 113 insertions(+), 47 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 3b54d0dbb6..b6bf0215d3 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -5849,14 +5849,16 @@ fn mem_accessors(windows: u32, heap: Option<&str>) -> String { let mut s = String::new(); if let Some(coherent) = heap { // one access: window k is descriptor MEM_HEAP_BASE + k; an `xcl_w` outside the windows - // does what the switch's `default` does - let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + xcl_w)]", super::MEM_HEAP_BASE); - let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] if (xcl_w >= {windows}u) {{ return uint4(0u, 0u, 0u, 0u); }} XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); - for (ret, name, params, args, def) in sigs { + // takes the null view at MEM_HEAP_NULL, which does what the switch's `default` does. No + // branch: a guard gives each access two paths, exploding basic blocks and handle PHIs in + // large HLSL pixel shaders and causing drivers to stall or reject them (#1695). + let null = super::MEM_HEAP_NULL - super::MEM_HEAP_BASE; + let index = if windows >= null { format!("min(xcl_w, {null}u)") } else { format!("select(xcl_w < {windows}u, xcl_w, {null}u)") }; + let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + {index})]", super::MEM_HEAP_BASE); + let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); + for (ret, name, params, args, _) in sigs { let r = if ret == "void" { "" } else { "return " }; - // (the switch's `break` leaves the accessor) - let outside = def.replace("break;", "return;"); - let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}"); + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ XCL_MW; {r}m.{name}({args}); }}"); } return s; } diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 48d0e599dc..efe999ad27 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -79,6 +79,10 @@ mod heap_window_tests; /// (`console_heap::null_views`). pub const MEM_HEAP_BASE: u32 = 4; +/// The null raw UAV after the windows' views: an `xcl_w` outside the windows takes it (reads 0, +/// stores and atomics dropped, atomics return 0: the switch's `default`). +pub const MEM_HEAP_NULL: u32 = MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; + /// Flag in a memory-windows count (`pso::mem_windows`, the translation caches' keys): /// `Options::heap_windows`. `translate` takes it out of `mem_windows`. pub const HEAP_WINDOWS: u32 = 0x100; @@ -548,9 +552,10 @@ pub struct Options { /// every access from the high address bits pub mem_windows: u32, /// with `mem_windows` > 1: reach window k through descriptor `MEM_HEAP_BASE + k` of the - /// shader-visible heap (a raw UAV of the window, `ResourceDescriptorHeap`) – one access per - /// site instead of a `switch` over the root UAVs `mem`, `mem1`.., which inlines every - /// access once per window (HANDOFF: twice the DXC + driver time with 4 windows) + /// shader-visible heap (a raw UAV of the window, `ResourceDescriptorHeap`; `MEM_HEAP_NULL` + /// outside the windows) – one access per site, with no branch, instead of a `switch` over the + /// root UAVs `mem`, `mem1`.., which inlines every access once per window (HANDOFF: twice the + /// DXC + driver time with 4 windows) pub heap_windows: bool, /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 0c8bf2a9c7..ec2842f831 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -105,7 +105,7 @@ pub fn in_switch_form(f: impl FnOnce() -> R) -> R { } /// Whether translated shaders reach the memory windows through the shared descriptor heap -/// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`.. made by `console_heap::set_window_views`) +/// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`..=`MEM_HEAP_NULL` made by `console_heap::set_window_views`) /// instead of a `switch` over root UAVs. Opt-in: on with `XCL_HEAP_WINDOWS=1`, unless the views /// could not be made (no shared heap: then the switch, as before). Off by default: two NVIDIA /// setups failed with it (the driver's compiler ending the process; a device removal when the diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 459c7021a8..49cf68e923 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1532,7 +1532,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result, Some(&raw_window_uav(size as u64)), h); } + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += super::MEM_HEAP_NULL as usize * inc; + dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(0)), h); list.SetDescriptorHeaps(&[Some(dh.clone())]); list.SetComputeRootSignature(&gpu.rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); @@ -1723,7 +1726,7 @@ fn dispatch_with( let dh: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - NumDescriptors: super::MEM_HEAP_BASE + win_count as u32, + NumDescriptors: super::MEM_HEAP_NULL + 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }) @@ -1734,6 +1737,9 @@ fn dispatch_with( h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc; dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h); } + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += super::MEM_HEAP_NULL as usize * inc; + dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(0)), h); list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]); list.SetComputeRootSignature(rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 46e0704e10..3db3df6b01 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4061,23 +4061,30 @@ fn gpu_mesh_mode_reads_memory_windows() { /// accesses in window 0. #[test] fn gpu_memory_windows_above_4_gib() { - memory_windows_above_4_gib(false); + memory_windows_above_4_gib(2, false); } /// The same program with the windows taken from the descriptor heap (`Options::heap_windows`): /// same results, and no `switch` over windows in the HLSL. #[test] fn gpu_memory_windows_from_the_heap() { - memory_windows_above_4_gib(true); + memory_windows_above_4_gib(2, true); } -fn memory_windows_above_4_gib(heap: bool) { +#[test] +fn gpu_memory_windows_beyond_the_root_uavs() { + for windows in [8, 16] { + memory_windows_above_4_gib(windows, true); + } +} + +fn memory_windows_above_4_gib(windows: usize, heap: bool) { if !gpu_ready() { return; } - let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); - let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); - assert_eq!(w1 - w0, 1 << 32); + let arena = crate::gpu::uma::Uma::with_windows(windows, 1 << 20).unwrap(); + let (w0, w1) = (arena.window(0).0 as u64, arena.window(windows - 1).0 as u64); + assert_eq!(w1 - w0, ((windows - 1) as u64) << 32); let word = |a: u64| unsafe { &mut *(a as *mut u32) }; *word(w1 + 0x1000) = 0xC0FFEE; *word(w1 + 0x1004) = 0x1234; @@ -4102,12 +4109,18 @@ fn memory_windows_above_4_gib(heap: bool) { let p = prog(&refs); let one = translate(&p, &Options::default()).unwrap(); assert!(!one.hlsl.contains("mem1") && !one.hlsl.contains("xcl_w =") && !one.hlsl.contains("xcl_m"), "one window: the single-window HLSL"); - let t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap(); + let t = translate(&p, &on_gpu(Options { mem_windows: windows as u32, heap_windows: heap, ..Default::default() })).unwrap(); assert!(t.hlsl.contains("RWByteAddressBuffer mem1 : register(u3)")); assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap, "heap windows: no switch over windows"); - assert_eq!(t.hlsl.contains("ResourceDescriptorHeap[NonUniformResourceIndex(4u + xcl_w)]"), heap); let hlsl_dxil = || super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); - let dxil = direct_or(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() }), hlsl_dxil()); + let dxil = if windows > 4 && runner::direct_dxil() { + crate::gpu::dxil::kernel::translate(&p, crate::gpu::dxil::kernel::KernelOptions { + wave64: true, split: runner::split_wave64(), + mem_windows: windows as u32 | super::HEAP_WINDOWS, sampler_base: 0, + }).expect("expanded direct DXIL") + } else { + direct_or(&p, &on_gpu(Options { mem_windows: windows as u32, heap_windows: heap, ..Default::default() }), hlsl_dxil()) + }; let hi = |a: u64| (a >> 32) as u32; let mut st = KernelState::default(); st.sgpr[2..4].copy_from_slice(&[(w1 + 0x1000) as u32, hi(w1)]); @@ -4136,6 +4149,12 @@ fn memory_windows_above_4_gib(heap: bool) { } assert_eq!(*word(w1 + 0x6000), 64, "global_atomic_add in window 1"); assert_eq!(*word(w0 + 0x6000), 0, "nothing in window 0 at the same low address"); + if heap { + let null = super::MEM_HEAP_NULL - super::MEM_HEAP_BASE; + let index = if windows as u32 >= null { format!("min(xcl_w, {null}u)") } else { format!("select(xcl_w < {windows}u, xcl_w, {null}u)") }; + assert!(t.hlsl.contains(&format!("ResourceDescriptorHeap[NonUniformResourceIndex({}u + {index})]", super::MEM_HEAP_BASE))); + assert!(!t.hlsl.contains("if (xcl_w"), "heap windows: no branch around an access"); + } } /// Out-of-UMA addresses must NEVER alias onto live UMA windows via `& 3`: @@ -4148,24 +4167,33 @@ fn memory_windows_above_4_gib(heap: bool) { /// on `global_load`/`global_store` updates the target window accurately. #[test] fn gpu_memory_windows_reject_out_of_uma_aliasing() { - memory_windows_reject_out_of_uma_aliasing(false); + memory_windows_reject_out_of_uma_aliasing(false, 2); } /// The same with the windows taken from the descriptor heap (`Options::heap_windows`): an /// address outside them reads 0 and drops its stores and atomics there too. #[test] fn gpu_heap_windows_reject_out_of_uma_aliasing() { - memory_windows_reject_out_of_uma_aliasing(true); + memory_windows_reject_out_of_uma_aliasing(true, 2); +} + +/// Cover partial and complete expanded layouts; the full layout uses the min-index path. +#[test] +fn gpu_heap_windows_reject_out_of_uma_aliasing_all_slots() { + for windows in [4, 8, 16] { + memory_windows_reject_out_of_uma_aliasing(true, windows); + } } -fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { +fn memory_windows_reject_out_of_uma_aliasing(heap: bool, windows: u32) { if !gpu_ready() { return; } - let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let arena = crate::gpu::uma::Uma::with_windows(windows as usize, 1 << 20).unwrap(); let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); assert_eq!(w1 - w0, 1 << 32); let base_hi = (w0 >> 32) as u32; + let outside = windows.max(4); assert!(base_hi >= 4); let word = |a: u64| unsafe { &mut *(a as *mut u32) }; @@ -4212,17 +4240,23 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { ]; let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); let p = prog(&refs); - let t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap(); + let t = translate(&p, &on_gpu(Options { mem_windows: windows, heap_windows: heap, ..Default::default() })).unwrap(); assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap); let hlsl_dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); - let dxil = direct_or(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() }), hlsl_dxil); + let dxil = if windows > 4 && runner::direct_dxil() { + crate::gpu::dxil::kernel::translate(&p, crate::gpu::dxil::kernel::KernelOptions { + wave64: true, split: runner::split_wave64(), mem_windows: windows | super::HEAP_WINDOWS, sampler_base: 0, + }).expect("expanded direct DXIL") + } else { + direct_or(&p, &on_gpu(Options { mem_windows: windows, heap_windows: heap, ..Default::default() }), hlsl_dxil) + }; let mut st = KernelState::default(); - st.sgpr[2..4].copy_from_slice(&[0x1000, base_hi + 4]); // s[2:3]: out-of-UMA hi = base_hi + 4 + st.sgpr[2..4].copy_from_slice(&[0x1000, base_hi + outside]); // s[2:3]: out-of-UMA hi = base_hi + outside st.sgpr[4..6].copy_from_slice(&[0x4000, 0]); // s[4:5]: hi == 0 32-bit descriptor read - st.sgpr[8..12].copy_from_slice(&[0x1000, ((base_hi + 5) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA V# (aliases w1 under & 3) + st.sgpr[8..12].copy_from_slice(&[0x1000, ((base_hi + outside + 1) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA V# (aliases w1 under & 3) st.sgpr[12..16].copy_from_slice(&[0x5000, ((base_hi + 1) & 0xFFFF) | (4 << 16), 64, 0]); // valid strided V# in w1 - st.sgpr[16..20].copy_from_slice(&[0x3000, ((base_hi + 4) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA atomic V# (aliases w0 under & 3) + st.sgpr[16..20].copy_from_slice(&[0x3000, ((base_hi + outside) & 0xFFFF) | (4 << 16), 64, 0]); // out-of-UMA atomic V# (aliases w0 under & 3) st.sgpr[20..22].copy_from_slice(&[0xFFFF_FFF0, base_hi]); // carry base st.sgpr[22..24].copy_from_slice(&[0, base_hi]); // borrow base (0 - 16 borrows into base_hi - 1) for r in st.vgpr.iter_mut() { @@ -4233,11 +4267,11 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) { r[11] = 0x7777_7777; r[14] = 0xBAD0_DEAD; r[4] = 0x1000; - r[5] = base_hi + 4; // out-of-UMA global_store (aliases w0 under & 3) + r[5] = base_hi + outside; // out-of-UMA global_store (aliases w0 under & 3) r[6] = 0x2000; r[7] = 0; // hi == 0 global_store (null pointer -> must be dropped) r[8] = 0x2000; - r[9] = base_hi + 5; // out-of-UMA global_atomic_add (aliases w1 under & 3) + r[9] = base_hi + outside + 1; // out-of-UMA global_atomic_add (aliases w1 under & 3) r[12] = 0x3000; r[13] = 0xFFFF_FFFF; // out-of-UMA global_atomic_inc CAS loop r[16] = 0x20; // carry offset: 0xFFFF_FFF0 + 0x20 = 0x1_0000_0010 -> w1 + 0x10 diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 7592d044b0..fffb5e4690 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -1157,7 +1157,10 @@ 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"); + // no guard branch: an index outside the windows takes the null view at MEM_HEAP_NULL + let null = recomp::MEM_HEAP_NULL - recomp::MEM_HEAP_BASE; + let want = if w >= null { format!("min(xcl_w, {null}u)") } else { format!("select(xcl_w < {w}u, xcl_w, {null}u)") }; + assert!(t.hlsl.contains(&want) && !t.hlsl.contains("xcl_w >= "), "HLSL must clamp to {w} windows: {want}"); 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(); diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index b9ef5b6c2e..592787c64a 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -185,8 +185,9 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), heap, cap, - // the memory windows' raw UAVs (`set_window_views`) come first - next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, + // the memory windows' raw UAVs and the null view after them (`set_window_views`) + // come first + next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), }); } @@ -229,11 +230,21 @@ pub fn window_views_failed() -> bool { /// The memory windows' buffers `(resource, bytes)` as raw UAVs at `MEM_HEAP_BASE + k` of the /// shared heap, made now if need be (`Options::heap_windows`: shaders take window k from there). /// Active windows (`bytes > 0`) in wider layouts (8 / 16) must all have a valid buffer; unused -/// trailing slots (`(0, 0)`) safely alias window 0's buffer. +/// trailing slots (`(0, 0)`) safely alias window 0's buffer. `MEM_HEAP_NULL` after the windows +/// holds a null raw UAV; heap views require 64-bit atomics on descriptor heap resources. pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) -> bool { + let mut o11 = D3D12_FEATURE_DATA_D3D12_OPTIONS11::default(); + let atomics64 = dev + .CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS11, &mut o11 as *mut _ as *mut std::ffi::c_void, std::mem::size_of_val(&o11) as u32) + .is_ok() + && o11.AtomicInt64OnDescriptorHeapResourceSupported.as_bool(); + set_window_views_checked(dev, windows, atomics64) +} + +unsafe fn set_window_views_checked(dev: &ID3D12Device, windows: &[(usize, usize)], atomics64: bool) -> 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 ok = atomics64 && count <= 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(); @@ -247,11 +258,13 @@ pub unsafe fn set_window_views(dev: &ID3D12Device, windows: &[(usize, usize)]) - let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + (crate::gpu::recomp::MEM_HEAP_BASE as u64 + k as u64) * inc as u64) as usize }; device.CreateUnorderedAccessView(r, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(bytes as u64)), at); } + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + crate::gpu::recomp::MEM_HEAP_NULL as u64 * inc as u64) as usize }; + device.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(0)), at); true }; 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 {count} window(s) (64-bit atomics on heap views: {atomics64}) in the shared descriptor heap"); } ok } @@ -886,21 +899,24 @@ mod tests { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, - next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), + next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), }); let window = (&mut resource as *mut _ as usize, 0x10000); - assert!(set_window_views(&dev, &[window])); - assert_eq!(CALLS.swap(0, Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32); + assert!(set_window_views_checked(&dev, &[window], true)); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), crate::gpu::uma::MAX_WINDOWS as u32 + 1); 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); + assert!(set_window_views_checked(&dev, &windows, true)); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32 + 1); // Unused trailing window `(0, 0)` safely aliases window 0; an active window that failed // to open `(0, bytes > 0)` is rejected. windows[7] = (0, 0); - assert!(set_window_views(&dev, &windows)); - assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32); + assert!(set_window_views_checked(&dev, &windows, true)); + assert_eq!(CALLS.swap(0, Ordering::Relaxed), windows.len() as u32 + 1); windows[7] = (0, 0x10000); - assert!(!set_window_views(&dev, &windows)); + assert!(!set_window_views_checked(&dev, &windows, true)); + assert_eq!(CALLS.load(Ordering::Relaxed), 0); + // Without 64-bit atomics on descriptor heap resources, heap window views are rejected. + assert!(!set_window_views_checked(&dev, &[window], false)); assert_eq!(CALLS.load(Ordering::Relaxed), 0); assert!(UNLOCKED.load(Ordering::Relaxed), "device callback ran while GLOBAL was locked"); *GLOBAL.lock().unwrap() = None; From 3227e365f7d43236695bb9804a01d534279e41bc Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:32:39 +0100 Subject: [PATCH 095/258] Recompiler: default XCL_HEAP_FLAT on, extend to VS/PS, fix GS heap inputs Three clean improvements to Direct DXIL heap memory windows: - Default pso::heap_flat() to on (opt-out with XCL_HEAP_FLAT=0) now that branchless Direct DXIL heap reads are verified stable on AMD RDNA4 (cutting PHIs 20x in large compute shaders). - Remove the !gfx restriction in dxil/kernel.rs so Direct DXIL VS and PS stages also emit branchless heap reads instead of per-load branches and handle PHIs. - Port #2383 in geom_init so ES+GS pre-fetched vertex inputs read from heap window 0 (MEM_HEAP_BASE) when HEAP_WINDOWS is active, with regression test in geometry_tests.rs. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/geometry_tests.rs | 51 ++++++++++++++++++++++- crates/xcl/src/gpu/dxil/kernel.rs | 11 ++++- crates/xcl/src/gpu/dxil/lower.rs | 2 +- crates/xcl/src/gpu/recomp/mod.rs | 4 +- crates/xcl/src/gpu/recomp/pso.rs | 6 +-- 5 files changed, 65 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/geometry_tests.rs b/crates/xcl/src/gpu/dxil/geometry_tests.rs index 84e09175af..f65d591e14 100644 --- a/crates/xcl/src/gpu/dxil/geometry_tests.rs +++ b/crates/xcl/src/gpu/dxil/geometry_tests.rs @@ -4,7 +4,7 @@ use super::kernel::{translate_geometry, KernelOptions}; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::encode; -use crate::gpu::recomp::{dxc, mesh_passthrough, runner, translate_geometry as hlsl_geometry, GsInterface, IO_GS_PRIMS, MESH_HEADER}; +use crate::gpu::recomp::{dxc, mesh_passthrough, runner, translate_geometry as hlsl_geometry, GsInterface, HEAP_WINDOWS, IO_GS_PRIMS, IO_GS_VERTICES, MESH_HEADER}; fn sig(name: &str, sv: u32, reg: u32, ty: u32) -> SigElement { SigElement { name: name.into(), index: 0, system_value: sv, component_type: ty, register: reg, mask: 0xF, rw_mask: 0xF, stream: 0 } @@ -183,3 +183,52 @@ fn geometry_epilogue_coalesces_header_and_vertex_stores() { assert_eq!(mask_count(1), 1, "expected only 1 scalar store (triangle index):\n{}", stores.join("\n")); assert_eq!(stores.len(), 4, "expected 4 total rawBufferStore calls:\n{}", stores.join("\n")); } + +/// ES+GS with pre-fetched ES vertex inputs (`v9..v12`) under `HEAP_WINDOWS`: `geom_init` +/// must load pre-fetched vertices from window 0 in the descriptor heap (`MEM_HEAP_BASE`) +/// rather than the placeholder `lw.mems[0]` handle (#2383). +#[test] +fn geometry_es_inputs_validate_and_run_with_heap_windows() { + let e = |n: &str, enc: &str, f: &[(&str, u64)], lit: Option| encode(n, enc, f, lit).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut code = Vec::new(); + code.extend(e("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 20), ("SRC0", 130), ("VSRC1", 5)], None)); + code.extend(e("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 20), ("SRC0", 255), ("VSRC1", 20)], Some(0x100))); + code.extend(e("V_MOV_B32", "ENC_VOP1", &[("VDST", 21), ("SRC0", 128)], None)); + code.extend(e("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 20), ("DATA", 9), ("SADDR", 0x7D), ("OFFSET", 0)], None)); + code.extend(e("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 6)], None)); + let gs_start = code.len() as u64; + code.extend(e("S_SENDMSG", "ENC_SOPP", &[("SIMM16", 0x3)], None)); + code.extend(e("S_ENDPGM", "ENC_SOPP", &[], None)); + + let g = GsInterface { + es_inputs: vec![sig("POSITION", 0, 0, 3)], + es_outputs: vec![sig("SV_Position", 1, 0, 3)], + outputs: vec![sig("SV_Position", 1, 0, 3)], + max_vertex_count: 3, + gs_start: Some(gs_start), + }; + + for split in [false, true] { + translate_geometry(&code, opts(split, 4 | HEAP_WINDOWS), &g) + .unwrap_or_else(|err| panic!("split {split}, 4 heap windows: {err}")); + } + + if runner::adapter().is_err() || runner::wave64_programs_supported() != Ok(true) { + runner::skip_test("no GPU / wave64"); + return; + } + let split = runner::split_wave64(); + let dxil = translate_geometry(&code, opts(split, 4 | HEAP_WINDOWS), &g).unwrap().dxil; + let mut io = vec![0u32; 128]; + io[IO_GS_PRIMS] = 1; + io[IO_GS_VERTICES] = 0; + let mut mem = vec![0u32; 128]; + mem[0] = 0x1111_0001; + mem[4] = 0x2222_0002; + mem[8] = 0x3333_0003; + let out = runner::dispatch(&dxil, [1, 1, 1], &io, &mem).unwrap(); + assert_eq!(out[0x100 / 4], 0x1111_0001, "vertex 0 v9 fetched via heap window 0"); + assert_eq!(out[0x100 / 4 + 1], 0x2222_0002, "vertex 1 v9 fetched via heap window 0"); + assert_eq!(out[0x100 / 4 + 2], 0x3333_0003, "vertex 2 v9 fetched via heap window 0"); + assert_eq!(out[0x100 / 4 + 3], 0, "lane past nv gets 0"); +} diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index a931432b3e..452d517998 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -518,7 +518,7 @@ impl Lw { half: z, mems, heap_mem, - heap_flat: heap_mem.is_some() && !gfx && o.mem_windows & crate::gpu::recomp::HEAP_FLAT != 0, + heap_flat: heap_mem.is_some() && o.mem_windows & crate::gpu::recomp::HEAP_FLAT != 0, res, fmt_table: None, fmt_desc_cache: HashMap::new(), @@ -932,12 +932,19 @@ fn geom_init(lw: &mut Lw, g: &GsInterface, _tid: Value, io: super::shader::RawUa let nreg = g.input_registers(); let fetched = fetched_registers(&g.es_inputs); let in_nv = lw.cmp(Pred::ULt, lane, nv); - let mem = lw.mems[0]; + let mut mem = None; for &v in used.iter().filter(|&&v| (9..256).contains(&v)) { let k = ((v - 9) / 4) as usize; if k >= fetched.len() || fetched[k] >= nreg { continue; } + let mem = *mem.get_or_insert_with(|| match lw.heap_mem { + Some(coherent) => { + let idx = lw.c(crate::gpu::recomp::MEM_HEAP_BASE); + lw.s.heap_raw_buffer_uav(idx, coherent) + } + None => lw.mems[0], + }); let (r, c) = (fetched[k], ((v - 9) % 4) as u32); // mem.Load(vin + ((p0 * 3 + lane) * nreg + r) * 16 + 4c), 0 past the group's vertices let kn = lw.c(nreg); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index bdb7bcca67..13dfb3277a 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -187,7 +187,7 @@ pub struct Lw { /// the windows come from the descriptor heap (`lower_window`; `mems` only counts them): /// Some(globallycoherent) pub heap_mem: Option, - /// heap windows read without a branch (`recomp::HEAP_FLAT`; not in VS / PS) + /// heap windows read without a branch (`recomp::HEAP_FLAT`) pub heap_flat: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index efe999ad27..954a9c059d 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -88,8 +88,8 @@ pub const MEM_HEAP_NULL: u32 = MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS pub const HEAP_WINDOWS: u32 = 0x100; /// Flag in a memory-windows count next to `HEAP_WINDOWS` (`pso::mem_windows`, the caches' keys): -/// the direct DXIL translator reads the heap windows of compute stages without a branch -/// (`Lw::with_mem_i32s`). The HLSL path ignores it. +/// the direct DXIL translator reads heap windows without a branch (`Lw::with_mem_i32s`). The +/// HLSL path ignores it (it uses `MEM_HEAP_NULL` unconditionally). pub const HEAP_FLAT: u32 = 0x200; pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index ec2842f831..5c2e2b76e2 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -115,11 +115,11 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } -/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap -/// windows without a branch per access (`HEAP_FLAT`). +/// `XCL_HEAP_FLAT` (default on with heap windows; `=0` to disable): the direct DXIL translator +/// reads heap windows without a branch per access (`HEAP_FLAT`). pub fn heap_flat() -> bool { static ENV: OnceLock = OnceLock::new(); - *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1")) + *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").map_or(true, |v| v.trim() != "0")) } /// A static sampler of a translated program: (S#, comparison) – see `Translation`. From 6ea50d1a7d990e93870432089548fc0bdd5d121f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:32:39 +0100 Subject: [PATCH 096/258] Recompiler: emit branchless root-UAV loads in Direct DXIL Port #2368's Lw::with_mem_raw_loads and mem_ld_chunks into Direct DXIL lowering so non-graphics stages running in root-UAV form (in_switch_form fallback or XCL_HEAP_WINDOWS=0) emit straight-line branchless loads reading offset 0 on unselected windows / inactive lanes and merging via select, eliminating per-load switch CFGs and handle PHIs. Includes regression tests in core_tests.rs covering branchless root-UAV loads, exec/OOB semantics, and branchless Direct DXIL PS heap-flat loads. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/core_tests.rs | 208 ++++++++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_mem.rs | 145 +++++++++++++----- 2 files changed, 317 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 8494a68bb7..a86c1f72d4 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -754,3 +754,211 @@ fn early_depth_pixel_shaders_test_depth_first_on_both_paths() { } } } + +#[test] +fn raw_loads_in_root_windows_are_branchless() { + let loads = prog(&[ + ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 12), ("SBASE", 0), ("OFFSET", 0x40), ("SOFFSET", 125)], None), + ("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 16), ("SBASE", 6), ("OFFSET", 0x10), ("SOFFSET", 125)], None), + ("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)], None), + ("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 8), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_XYZW", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_UBYTE", "ENC_MUBUF", &[("VDATA", 14), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("GLOBAL_LOAD_DWORDX4", "ENC_FLAT_GLBL", &[("VDST", 16), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("GLOBAL_LOAD_USHORT", "ENC_FLAT_GLBL", &[("VDST", 20), ("ADDR", 0), ("SADDR", 0x7D), ("OFFSET", 4)], None), + ]); + for (wave64, split) in [(false, false), (true, true), (true, false)] { + let dxil = translate(&loads, KernelOptions { wave64, split, mem_windows: 4, sampler_base: 0 }) + .unwrap_or_else(|e| panic!("wave64={wave64} split={split}: {e}")); + super::validate::validate(&dxil).expect("valid DXIL"); + if let Ok(dis) = super::validate::disassemble(&dxil) { + let body = dis.split("define void @main()").nth(1).and_then(|s| s.split("\n}\n").next()).expect("main body"); + assert!(dis.contains("@dx.op.rawBufferLoad"), "expected rawBufferLoad in DXIL:\n{dis}"); + assert!(!body.contains("switch i32"), "multi-window root-UAV loads must not emit switch (wave64={wave64}, split={split}):\n{dis}"); + } + } + let heap_dxil = translate(&loads, KernelOptions { wave64: false, split: false, mem_windows: 4 | crate::gpu::recomp::HEAP_WINDOWS, sampler_base: 0 }) + .expect("heap windows translate"); + super::validate::validate(&heap_dxil).expect("heap windows validate"); + + let writes = prog(&[ + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("GLOBAL_ATOMIC_ADD", "ENC_FLAT_GLBL", &[("VDST", 3), ("ADDR", 4), ("DATA", 5), ("SADDR", 0x7D), ("OFFSET", 0), ("GLC", 1)], None), + ]); + let wdxil = translate(&writes, KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }).expect("writes translate"); + super::validate::validate(&wdxil).expect("writes validate"); + if let Ok(dis) = super::validate::disassemble(&wdxil) { + let body = dis.split("define void @main()").nth(1).and_then(|s| s.split("\n}\n").next()).expect("main body"); + assert!(body.contains("switch i32"), "stores and atomics must keep multi-window switch:\n{dis}"); + } + + let ps_code = prog(&[ + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 4), ("ADDR", 0), ("SADDR", 0), ("OFFSET", 0)], None), + ("EXP", "ENC_EXP", &[("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 4), ("VSRC2", 4), ("VSRC3", 4), ("DONE", 1), ("VM", 1)], None), + ]); + let psi = crate::gpu::recomp::PsInterface { + inputs: vec![sig("SV_Position", 0, 1, 3, 0, 0xF)], + outputs: vec![sig("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x2, + attrs: None, + early_depth: false, + }; + let ps_k = super::kernel::translate_pixel(&ps_code, KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }, &psi) + .expect("pixel shader multi-window load translates"); + super::validate::validate(&ps_k.dxil).expect("pixel shader validates"); + if let Ok(dis) = super::validate::disassemble(&ps_k.dxil) { + let body = dis.split("define void @main()").nth(1).and_then(|s| s.split("\n}\n").next()).expect("main body"); + assert!(body.contains("switch i32"), "pixel shader root-UAV loads must keep switch:\n{dis}"); + } + let ps_flat = super::kernel::translate_pixel( + &ps_code, + KernelOptions { wave64: false, split: false, mem_windows: 4 | crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT, sampler_base: 0 }, + &psi, + ) + .expect("pixel shader heap-flat load translates"); + super::validate::validate(&ps_flat.dxil).expect("pixel shader heap-flat validates"); + if let Ok(dis) = super::validate::disassemble(&ps_flat.dxil) { + let body = dis.split("define void @main()").nth(1).and_then(|s| s.split("\n}\n").next()).expect("main body"); + assert!(!body.contains("switch i32"), "pixel shader heap-flat loads must not emit switch:\n{dis}"); + } +} + +#[test] +fn raw_loads_in_root_windows_respect_exec_and_bounds() { + use crate::gpu::recomp::runner::{self, KernelState}; + let code = prog(&[ + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 1), ("OFFSET", 0)], None), + ("V_CMPX_EQ_U32", "ENC_VOPC", &[("SRC0", 129), ("VSRC1", 15)], None), + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 20), ("ADDR", 2), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("GLOBAL_LOAD_DWORDX2", "ENC_FLAT_GLBL", &[("VDST", 22), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 16)], None), + ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 24), ("VADDR", 10), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("BUFFER_LOAD_FORMAT_X", "ENC_MUBUF", &[("VDATA", 25), ("VADDR", 10), ("SRSRC", 4), ("SOFFSET", 128), ("IDXEN", 1), ("OFFSET", 2)], None), + ]); + let w32_dxil = translate(&code, KernelOptions { wave64: false, split: false, mem_windows: 4, sampler_base: 0 }).expect("wave32 translates"); + let split_dxil = translate(&code, KernelOptions { wave64: true, split: true, mem_windows: 4, sampler_base: 0 }).expect("split-wave64 translates"); + let w64_dxil = translate(&code, KernelOptions { wave64: true, split: false, mem_windows: 4, sampler_base: 0 }).expect("wave64 translates"); + for dxil in [&w32_dxil, &split_dxil, &w64_dxil] { + super::validate::validate(dxil).expect("valid DXIL"); + } + let (has_w32, has_w64) = match (runner::wave32_supported(), runner::wave64_supported()) { + (Ok(a), Ok(b)) => (a, b), + (Err(e), _) | (_, Err(e)) => return runner::skip_test(&e), + }; + if !has_w32 && !has_w64 { + return runner::skip_test("no GPU"); + } + let arena = crate::gpu::uma::Uma::with_windows(4, 1 << 20).expect("4 UMA windows"); + let ws: [u64; 4] = std::array::from_fn(|k| arena.window(k).0 as u64); + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for (k, &wk) in ws.iter().enumerate() { + *word(wk) = 0xBAD0_0000 | k as u32; + *word(wk + 0x1000) = 0xA000_0000 | (k as u32 * 0x11); + *word(wk + 0x1004) = 0xB000_0000 | (k as u32 * 0x11); + } + *word(ws[1] + 8) = 0xCA44_0001; + *word(ws[1] + 12) = 0xCA44_0002; + *word(ws[2] + 0x1000) = 0x510A_D001; + *word(ws[2] + 0x1004) = 0x510A_D002; + for l in 0..64u64 { + *word(ws[3] + 0x2000 + 4 * l) = 0x3000_0000 | l as u32; + *word(ws[2] + 0x2000 + 4 * l) = ((0xF000 | (l as u32 + 1)) << 16) | 0xBEEF; + } + let hi = |a: u64| (a >> 32) as u32; + let ident = 4 | (5 << 3) | (6 << 6) | (7 << 9); + let mut st = KernelState::default(); + st.sgpr[2..4].copy_from_slice(&[(ws[2] + 0x1000) as u32, hi(ws[2])]); + st.sgpr[12..16].copy_from_slice(&[(ws[3] + 0x2000) as u32, (hi(ws[3]) & 0xFFFF) | (4 << 16), 64, 0]); + st.sgpr[16..20].copy_from_slice(&[(ws[2] + 0x2000) as u32, (hi(ws[2]) & 0xFFFF) | (4 << 16), 64, ident | (11 << 12)]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + let slot = l % 16; + let active = slot < 8; + r[15] = u32::from(active); + r[10] = if active { l as u32 } else { 0xFFFF_FFFF }; + r[20] = 0x5EED_0000 | l as u32; + r[22] = 0x5EED_1000 | l as u32; + r[23] = 0x5EED_2000 | l as u32; + r[24] = 0x5EED_3000 | l as u32; + r[25] = 0x5EED_4000 | l as u32; + if !active { + r[2] = 0x7FFF_FFE0; + r[3] = 0xDEAD_0000; + r[4] = 0x7FFF_FFE0; + r[5] = 0xDEAD_0000; + continue; + } + match slot { + 0..=3 => { + r[2] = (ws[slot] + 0x1000) as u32; + r[3] = hi(ws[slot]); + r[4] = (ws[slot] + 0xFF0) as u32; + r[5] = hi(ws[slot]); + } + 4 => { + r[2] = 0x1000; + r[3] = hi(ws[0]) + 4; + r[4] = 0xFF0; + r[5] = hi(ws[0]) + 4; + } + 5 => { + r[2] = 0x1000; + r[3] = 0xFFFF_FFFF; + r[4] = 0xFF0; + r[5] = 0xFFFF_FFFF; + } + 6 => { + r[2] = 0x1000; + r[3] = 0; + r[4] = 0xFF0; + r[5] = 0; + } + 7 => { + r[2] = 0x1000; + r[3] = hi(ws[0]); + r[4] = 0xFFFF_FFF8; + r[5] = hi(ws[0]); + } + _ => unreachable!(), + } + } + let mut runs: Vec<(&str, &[u8], usize)> = Vec::new(); + if has_w32 { + runs.push(("wave32", &w32_dxil, 32)); + runs.push(("split-wave64", &split_dxil, 64)); + } + if has_w64 { + runs.push(("native-wave64", &w64_dxil, 64)); + } + for (label, dxil, lanes) in runs { + let r = runner::run_in_arena(dxil, &st, &arena).unwrap_or_else(|e| panic!("{label}: {e}")); + assert_eq!((r.sgpr[20], r.sgpr[21]), (0x510A_D001, 0x510A_D002), "{label}: s_load_dwordx2 from window 2"); + for l in 0..lanes { + let slot = l % 16; + if slot >= 8 { + assert_eq!(r.vgpr[l][20], 0x5EED_0000 | l as u32, "{label} lane {l}: inactive global_load preserved v20"); + assert_eq!(r.vgpr[l][22], 0x5EED_1000 | l as u32, "{label} lane {l}: inactive global_loadx2 preserved v22"); + assert_eq!(r.vgpr[l][23], 0x5EED_2000 | l as u32, "{label} lane {l}: inactive global_loadx2 preserved v23"); + assert_eq!(r.vgpr[l][24], 0x5EED_3000 | l as u32, "{label} lane {l}: inactive buffer_load preserved v24"); + assert_eq!(r.vgpr[l][25], 0x5EED_4000 | l as u32, "{label} lane {l}: inactive buffer_load_format preserved v25"); + continue; + } + let (want20, want22, want23) = match slot { + 0..=3 => { + let w = slot as u32; + let w20 = if w == 2 { 0x510A_D001 } else { 0xA000_0000 | (w * 0x11) }; + let w22 = if w == 2 { 0x510A_D001 } else { 0xA000_0000 | (w * 0x11) }; + let w23 = if w == 2 { 0x510A_D002 } else { 0xB000_0000 | (w * 0x11) }; + (w20, w22, w23) + } + 4 | 5 => (0, 0, 0), + 6 => (0xA000_0000, 0xA000_0000, 0xB000_0000), + 7 => (0xA000_0000, 0xCA44_0001, 0xCA44_0002), + _ => unreachable!(), + }; + assert_eq!(r.vgpr[l][20], want20, "{label} lane {l} (slot {slot}): global_load_dword"); + assert_eq!((r.vgpr[l][22], r.vgpr[l][23]), (want22, want23), "{label} lane {l} (slot {slot}): global_load_dwordx2"); + assert_eq!(r.vgpr[l][24], 0x3000_0000 | l as u32, "{label} lane {l}: buffer_load_dword from window 3"); + assert_eq!(r.vgpr[l][25], 0xF000 | (l as u32 + 1), "{label} lane {l}: buffer_load_format_x unaligned from window 2"); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 1a3f5233aa..3332adc513 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -314,6 +314,93 @@ impl Lw { out } + /// Pure read-only raw buffer loads across the active memory window (`loads` is a slice of + /// `(aligned_byte_offset, component_mask)` pairs). For non-graphics stages with root UAV + /// windows (`self.heap_mem.is_none() && self.gfx.is_none()`), emits branchless straight-line + /// loads reading offset `0` on unselected windows / inactive lanes and merging with `select`, + /// eliminating per-load `switch` / guard CFGs and `phi` nodes while preserving out-of-range + /// and inactive-lane zero semantics. Graphics stages (`VS`/`PS`) keep the `switch` form for + /// root UAVs; heap-window stages delegate to `with_mem_i32s` (`heap_flat` when enabled). + pub(crate) fn with_mem_raw_loads( + &mut self, + mut guard: Option, + loads: &[(Value, u8)], + ) -> Vec { + let total: usize = loads.iter().map(|&(_, mask)| mask.count_ones() as usize).sum(); + let z = self.c(0); + if let Some(c) = guard { + match self.s.m.const_u64(c) { + Some(1) => guard = None, + Some(0) => return vec![z; total], + _ => {} + } + } + if self.heap_mem.is_some() || self.gfx.is_some() { + return self.with_mem_i32s(guard, total, &mut |lw, m| { + let mut out = Vec::with_capacity(total); + for &(a, mask) in loads { + out.extend(lw.s.raw_load(m, a, mask)); + } + out + }); + } + let fixed_mem = if self.mems.len() <= 1 { + Some(self.mems[0]) + } else { + let w = self.rd(super::lower::VAR_WIN); + if let Some(k) = self.s.m.const_u64(w) { + if (k as usize) < self.mems.len() { + Some(self.mems[k as usize]) + } else { + return vec![z; total]; + } + } else { + None + } + }; + if let Some(m) = fixed_mem { + let mut out = Vec::with_capacity(total); + if let Some(cond) = guard { + for &(a, mask) in loads { + let at = self.sel(cond, a, z); + for v in self.s.raw_load(m, at, mask) { + out.push(self.sel(cond, v, z)); + } + } + } else { + for &(a, mask) in loads { + out.extend(self.s.raw_load(m, a, mask)); + } + } + return out; + } + let w = self.rd(super::lower::VAR_WIN); + let mems = self.mems.clone(); + let n = mems.len(); + let w_eff = if let Some(cond) = guard { + let skip = self.c(n as u32); + self.sel(cond, w, skip) + } else { + w + }; + let sels: Vec = (0..n).map(|k| self.cmpc(Pred::Eq, w_eff, k as u32)).collect(); + let mut out = Vec::with_capacity(total); + for &(a, mask) in loads { + let count = mask.count_ones() as usize; + let mut acc = vec![z; count]; + for (k, &m) in mems.iter().enumerate() { + let sel_k = sels[k]; + let at = self.sel(sel_k, a, z); + let vals = self.s.raw_load(m, at, mask); + for (dst, v) in acc.iter_mut().zip(vals) { + *dst = self.sel(sel_k, v, *dst); + } + } + out.extend(acc); + } + out + } + /// `with_mem_many_tys` of `n` dwords for a read (`f` only loads). With `heap_flat`, no branch: /// `f` reads window `w`, or window 0 when `w` is outside the windows or the lane is not in /// `guard`, and those lanes then take 0 (a raw buffer read out of the view's range gives 0, @@ -368,14 +455,26 @@ impl Lw { /// `mem.Load(a & ~3)` pub fn mem_ld(&mut self, a: Value) -> Value { let a = self.andc(a, !3); - self.with_mem_i32s(None, 1, &mut |lw, m| lw.s.raw_load(m, a, 1))[0] + self.with_mem_raw_loads(None, &[(a, 1)])[0] } - /// `mem.Load2/3/4(a & ~3)` (1..=4 consecutive dwords in one window switch). + /// `mem.Load2/3/4(a & ~3)` (1..=4 consecutive dwords across root or heap memory windows). pub(crate) fn mem_ld_n(&mut self, guard: Option, a: Value, count: u32) -> Vec { debug_assert!((1..=4).contains(&count)); let a = self.andc(a, !3); let mask = ((1u32 << count) - 1) as u8; - self.with_mem_i32s(guard, count as usize, &mut |lw, m| lw.s.raw_load(m, a, mask)) + self.with_mem_raw_loads(guard, &[(a, mask)]) + } + fn mem_ld_chunks(&mut self, base_aligned: Value, count: u32) -> Vec { + let mut loads = Vec::new(); + let mut done = 0u32; + while done < count { + let chunk = (count - done).min(4); + let at = self.addc(base_aligned, 4 * done); + let mask = ((1u32 << chunk) - 1) as u8; + loads.push((at, mask)); + done += chunk; + } + self.with_mem_raw_loads(None, &loads) } /// `mem.Store(a & ~3, v)` pub fn mem_st(&mut self, a: Value, v: Value) { @@ -390,17 +489,13 @@ impl Lw { } /// `ld_raw`: four dwords from an unaligned byte address (one Load4 + one Load1 - /// in a single window switch, optionally combined with a lane guard). + /// across memory windows, optionally combined with a lane guard). fn ld_raw_guarded(&mut self, guard: Option, a: Value) -> [Value; 4] { let b = self.andc(a, !3); let b16 = self.addc(b, 16); let s = self.andc(a, 3); let s = self.shlc(s, 3); - let w = self.with_mem_i32s(guard, 5, &mut |lw, m| { - let mut v = lw.s.raw_load(m, b, 0xF); - v.push(lw.s.raw_load(m, b16, 1)[0]); - v - }); + let w = self.with_mem_raw_loads(guard, &[(b, 0xF), (b16, 1)]); let k32 = self.c(32); let inv = self.sub(k32, s); let inv = self.andc(inv, 31); @@ -415,12 +510,12 @@ impl Lw { r } - /// One unaligned dword from byte address `a` (one Load2 in a single window switch). + /// One unaligned dword from byte address `a` (one Load2 across memory windows). fn ld_raw_u32_guarded(&mut self, guard: Option, a: Value) -> Value { let b = self.andc(a, !3); let s = self.andc(a, 3); let s = self.shlc(s, 3); - let w = self.with_mem_i32s(guard, 2, &mut |lw, m| lw.s.raw_load(m, b, 0x3)); + let w = self.with_mem_raw_loads(guard, &[(b, 0x3)]); let k32 = self.c(32); let inv = self.sub(k32, s); let inv = self.andc(inv, 31); @@ -1093,18 +1188,7 @@ impl Lw { let lim = self.sel(sz, d2, lim); let base = self.add(d0, off); let base_aligned = self.andc(base, !3); - let raw = self.with_mem_i32s(None, count as usize, &mut |lw, m| { - let mut out = Vec::with_capacity(count as usize); - let mut done = 0u32; - while done < count { - let chunk = (count - done).min(4); - let at = lw.addc(base_aligned, 4 * done); - let mask = ((1u32 << chunk) - 1) as u8; - out.extend(lw.s.raw_load(m, at, mask)); - done += chunk; - } - out - }); + let raw = self.mem_ld_chunks(base_aligned, count); let z = self.c(0); (0..count) .map(|i| { @@ -1131,18 +1215,7 @@ impl Lw { let a = self.add(b, k); let a = self.add(a, soff); let base_aligned = self.andc(a, !3); - self.with_mem_i32s(None, count as usize, &mut |lw, m| { - let mut out = Vec::with_capacity(count as usize); - let mut done = 0u32; - while done < count { - let chunk = (count - done).min(4); - let at = lw.addc(base_aligned, 4 * done); - let mask = ((1u32 << chunk) - 1) as u8; - out.extend(lw.s.raw_load(m, at, mask)); - done += chunk; - } - out - }) + self.mem_ld_chunks(base_aligned, count) }; let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)); if self.split && coherent { @@ -1312,7 +1385,7 @@ impl Lw { let ea3 = self.andc(ea, 3); let ea3_8 = self.shlc(ea3, 3); let s = self.or(ea3_8, c1.off_bits); - let w = self.with_mem_i32s(Some(act), 2, &mut |lw, m| lw.s.raw_load(m, eb, 0x3)); + let w = self.with_mem_raw_loads(Some(act), &[(eb, 0x3)]); let lo = self.bin(BinOp::LShr, w[0], s); let k32 = self.c(32); let inv = self.sub(k32, s); From 0e19dc1d2913b5e45368837e0d15766c006e831c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:34:03 +0100 Subject: [PATCH 097/258] D3D12.X: guard zero UMA window VAs for branchless root-UAV loads (#2368) Fall back to windows[0] when uma_window_vas() entries 1..3 are zero so branchless Direct DXIL root-UAV loads (6ea50d1a) and prelude indirect passes never bind a null root UAV. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 877226a9e0..6a05e7f53a 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -875,9 +875,9 @@ unsafe fn bind_two_pass_stage( let first = windows[0]; let win_vas = [ first, - windows.get(1).copied().unwrap_or(first), - windows.get(2).copied().unwrap_or(first), - windows.get(3).copied().unwrap_or(first), + windows.get(1).copied().filter(|&v| v != 0).unwrap_or(first), + windows.get(2).copied().filter(|&v| v != 0).unwrap_or(first), + windows.get(3).copied().filter(|&v| v != 0).unwrap_or(first), ]; let cached_io = if compute_pass { @@ -1304,7 +1304,12 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { } let w = s.uma_windows.as_deref().unwrap(); let first = w[0]; - Ok([first, w.get(1).copied().unwrap_or(first), w.get(2).copied().unwrap_or(first), w.get(3).copied().unwrap_or(first)]) + Ok([ + first, + w.get(1).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(2).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(3).copied().filter(|&v| v != 0).unwrap_or(first), + ]) })?; let dev_key = dev.as_raw() as usize; @@ -2900,9 +2905,9 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let first = windows[0]; let win_vas = [ first, - windows.get(1).copied().unwrap_or(first), - windows.get(2).copied().unwrap_or(first), - windows.get(3).copied().unwrap_or(first), + windows.get(1).copied().filter(|&v| v != 0).unwrap_or(first), + windows.get(2).copied().filter(|&v| v != 0).unwrap_or(first), + windows.get(3).copied().filter(|&v| v != 0).unwrap_or(first), ]; // Runtime VS/PS/CS shaders never write to `u1` (`res`), so one zeroed 256-byte slot From f7aaee879aed2456538aab8cb1350a61fe8b09c0 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:26:52 +0100 Subject: [PATCH 098/258] D3D12.X: tier PSO gating, prioritize MS PSOs, keep >=512 KiB compute async Fix both world-entry PSO compile bottlenecks observed in RX 9070 XT profiling: 1. Separate 256-512 KiB medium-large compiles (two-pass world MS PSOs, ~200-400 MB each) into MEDIUM_COMPILES (default 3 background / 4 wanted on >= 32 GiB hosts, 2/3 on < 32 GiB; XCL_MEDIUM_PSO_CONCURRENCY / XCL_MEDIUM_PSO_WANTED_CONCURRENCY), isolating >= 512 KiB heavyweights (686-1061 KiB RT compute shaders) in BIG_COMPILES (1/2) and >= 4 MiB giants in GIANT_COMPILES (1/1). Wanted slots beyond 2 require commit headroom (big_compile_commit_free) so wider medium concurrency cannot OOM when a >= 512 KiB shader spikes commit. 2. Never synchronously compile uses_bvh_intersect or heavyweight compute PSOs (>= 24 KiB console code / ~512+ KiB DXIL, XCL_ASYNC_HEAVY_COMPUTE=0 or XCL_RT_GATE=0 to disable) on title threads: queue them asynchronously onto background workers (unwanted -> BIG_COMPILES concurrency=1) at lower priority than normal/MS PSOs and return the stand-in until ready, eliminating the 5-way title-thread +11.8 GB commit spike and 224 s PresentX freeze at world entry. 3. Replace pso_async's FIFO mpsc channel with a 3-tier priority PsoQueue (wanted > normal/MS > deprioritized >= 512 KiB/BVH compute), and wake both PsoQueue and Slots condvars immediately in Pending::want() alongside dxc::notify_wanted(). 4. Add unit tests for 3-tier lane routing, RAM-scaled defaults, commit-tight throttling above 2 wanted slots, and 3-tier PsoQueue priority ordering. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/effects.rs | 10 ++ crates/xcl/src/hle/d3d12x/pso_async.rs | 192 +++++++++++++++++++++---- crates/xcl/src/hle/d3d12x/real.rs | 158 +++++++++++++++++--- 3 files changed, 311 insertions(+), 49 deletions(-) diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index 69d5bfe1cd..05ef4eacb1 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -109,6 +109,16 @@ pub fn big_and_image_only(blob: &[u8]) -> bool { code.len() >= BIG_CODE && of(&code).is_some_and(|e| !e.memory) } +/// Console RDNA2 code bytes (24 KiB, ~6 000 instructions, ~512+ KiB DXIL) from which a compute +/// shader is treated as heavyweight for async-only compilation so title threads never freeze +/// compiling multi-10s RT compute shaders synchronously. +pub const HEAVY_CODE: usize = 24 << 10; + +/// Length in bytes of the compute program's RDNA2 code (`None` if not a valid console CS). +pub fn compute_code_len(blob: &[u8]) -> Option { + compute_code(blob).map(|c| c.len()) +} + /// Whether the compute shader `blob` issues `IMAGE_BVH_INTERSECT_RAY` or `IMAGE_BVH64_INTERSECT_RAY`. pub fn uses_bvh_intersect(blob: &[u8]) -> bool { let Some(code) = compute_code(blob) else { return false }; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 11b8312fd9..4704d48166 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -35,6 +35,9 @@ struct Pending { spared: std::sync::atomic::AtomicBool, /// shader issues `image_bvh*_intersect_ray`: held back without blocking until BVH builds succeed bvh_traversal: std::sync::atomic::AtomicBool, + /// heavyweight RT/compute shader (`>= 512 KiB` DXIL / BVH traversal): lower worker queue + /// priority than normal/MS PSOs so world-entry draws finish ahead of slow RT compiles + deprioritized: std::sync::atomic::AtomicBool, demand: Mutex, } @@ -113,6 +116,8 @@ impl Pending { }; if became_wanted { crate::gpu::recomp::dxc::notify_wanted(); + notify_queue_wanted(); + super::real::notify_big_compile_wanted(); } } @@ -291,38 +296,92 @@ fn drop_unstarted_job(p: &Pending) { type Work = Box; -fn queue() -> &'static Mutex> { - static Q: OnceLock>> = OnceLock::new(); - Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::(); - let rx = Arc::new(Mutex::new(rx)); +struct PsoWork { + work: Work, + pending: Option>, +} + +/// Priority work queue for `xcl-pso-*` workers: pipelines waited on by a title thread (`wanted`) +/// jump ahead of queued background builds. +struct PsoQueue { + items: Mutex>, + cv: Condvar, +} + +impl PsoQueue { + fn new() -> Self { + Self { items: Mutex::new(std::collections::VecDeque::new()), cv: Condvar::new() } + } + + fn push(&self, work: Work, pending: Option>) { + self.items.lock().unwrap().push_back(PsoWork { work, pending }); + self.cv.notify_one(); + } + + fn notify_wanted(&self) { + let _g = self.items.lock().unwrap(); + drop(_g); + self.cv.notify_all(); + } + + fn pop(&self) -> Work { + let mut g = self.items.lock().unwrap(); + loop { + if let Some(pos) = g.iter().position(|item| item.pending.as_ref().is_some_and(|p| p.demand.lock().unwrap().wanted)) { + return g.remove(pos).unwrap().work; + } + if let Some(pos) = g.iter().position(|item| !item.pending.as_ref().is_some_and(|p| p.deprioritized.load(Ordering::Acquire))) { + return g.remove(pos).unwrap().work; + } + if let Some(item) = g.pop_front() { + return item.work; + } + g = self.cv.wait(g).unwrap(); + } + } +} + +static WORK_QUEUE: OnceLock> = OnceLock::new(); + +fn notify_queue_wanted() { + if let Some(q) = WORK_QUEUE.get() { + q.notify_wanted(); + } +} + +fn queue() -> &'static Arc { + WORK_QUEUE.get_or_init(|| { + let q = Arc::new(PsoQueue::new()); // translation recurses deeply on big programs; DXC itself runs on its own pool let n = crate::gpu::recomp::dxc::compile_threads(); for k in 0..n { - let rx = rx.clone(); + let q = q.clone(); let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { - let next = rx.lock().unwrap().recv(); - let Ok(work) = next else { return }; + let work = q.pop(); work(); }); } - Mutex::new(tx) + q }) } fn enqueue(p: Arc) { - let _ = queue().lock().unwrap().send(Box::new(move || { - // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { - drop_unstarted_job(&p); - return; - } - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - build(&p, job, false); - } - })); + let p_q = p.clone(); + queue().push( + Box::new(move || { + // (released by the title meanwhile) + if p.orphan.load(Ordering::Acquire) { + drop_unstarted_job(&p); + return; + } + // (None: a bind took it and builds it itself) + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + build(&p, job, false); + } + }), + Some(p_q), + ); } /// The caller also drains its batch. Multiple workers can therefore build @@ -339,12 +398,15 @@ pub(super) fn build_pieces(jobs: Vec) -> Vec { // the helpers build for this worker's pipeline: the title waiting for it waits for them too let parent = BUILDING.with(|b| b.borrow().clone()); for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { - let (drain, parent) = (drain.clone(), parent.clone()); - let _ = queue().lock().unwrap().send(Box::new(move || { - let before = BUILDING.with(|b| b.replace(parent)); - drain(); - BUILDING.with(|b| *b.borrow_mut() = before); - })); + let (drain, parent_run, parent_q) = (drain.clone(), parent.clone(), parent.clone()); + queue().push( + Box::new(move || { + let before = BUILDING.with(|b| b.replace(parent_run)); + drain(); + BUILDING.with(|b| *b.borrow_mut() = before); + }), + parent_q, + ); } drain(); let mut results = vec![0; count]; @@ -395,6 +457,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { late: Default::default(), spared: Default::default(), bvh_traversal: Default::default(), + deprioritized: Default::default(), demand: Default::default(), }); PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); @@ -1042,7 +1105,7 @@ pub fn resolve_wait(pso: usize) -> usize { fn resolve_wait_for(pso: usize, budget: Option) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); - if p.spared.load(Ordering::Acquire) || (p.bvh_traversal.load(Ordering::Acquire) && !super::real::bvh_traversal_allowed()) { + if p.spared.load(Ordering::Acquire) || p.bvh_traversal.load(Ordering::Acquire) { return resolve_spared(&p, pso); } // (the title's thread is held from here until the pipeline is built or the budget is over) @@ -1127,10 +1190,28 @@ pub fn image_only(standin: usize) { } } -/// The compute pipeline behind stand-in `standin` issues `image_bvh*_intersect_ray`: binds do not -/// block waiting for it while the BVH builder gate is still closed. +/// Whether heavyweight compute shaders (`>= 512 KiB` DXIL / `>= 24 KiB` console code) compile +/// asynchronously off title threads (default on, `XCL_ASYNC_HEAVY_COMPUTE=0` to disable). +pub fn async_heavy_compute() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_ASYNC_HEAVY_COMPUTE").is_ok_and(|v| v.trim() == "0")) +} + +/// The compute pipeline behind stand-in `standin` is a heavyweight shader (`>= 512 KiB` DXIL): +/// never compile it synchronously on title threads — queue it at lower worker priority behind +/// normal/MS PSOs and return the stand-in until background `BIG_COMPILES` finishes it. +pub fn heavy_compute(standin: usize) { + if let Some(p) = entry(standin) { + p.deprioritized.store(true, Ordering::Release); + p.spared.store(true, Ordering::Release); + } +} + +/// The compute pipeline behind stand-in `standin` issues `image_bvh*_intersect_ray`: binds never +/// compile it synchronously on title threads; queue it deprioritized behind normal/MS PSOs. pub fn bvh_traversal(standin: usize) { if let Some(p) = entry(standin) { + p.deprioritized.store(true, Ordering::Release); p.bvh_traversal.store(true, Ordering::Release); } } @@ -1201,3 +1282,54 @@ pub fn counts() -> (usize, usize, usize) { let pending = PENDING.read().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) } + +#[cfg(test)] +mod pso_queue_tests { + use super::*; + + fn dummy_pending(wanted: bool, deprioritized: bool) -> Arc { + Arc::new(Pending { + job: Mutex::new(None), + sent: std::sync::atomic::AtomicBool::new(true), + real: AtomicUsize::new(0), + driver: AtomicUsize::new(0), + done: Mutex::new(false), + cv: Condvar::new(), + compute: false, + key: 0, + used: Default::default(), + orphan: Default::default(), + late: Default::default(), + spared: Default::default(), + bvh_traversal: Default::default(), + deprioritized: std::sync::atomic::AtomicBool::new(deprioritized), + demand: Mutex::new(Demand { wanted, preload_thread: 0 }), + }) + } + + #[test] + fn pso_queue_dequeues_wanted_then_normal_ahead_of_deprioritized() { + let q = PsoQueue::new(); + let order = Arc::new(Mutex::new(Vec::<&'static str>::new())); + let push = |name: &'static str, p: Arc| { + let o = order.clone(); + q.push(Box::new(move || o.lock().unwrap().push(name)), Some(p)); + }; + let heavy1 = dummy_pending(false, true); + let bg1 = dummy_pending(false, false); + let promoted = dummy_pending(false, false); + let wanted_now = dummy_pending(true, false); + let heavy2 = dummy_pending(false, true); + push("heavy1", heavy1); + push("bg1", bg1); + push("promoted", promoted.clone()); + push("wanted", wanted_now); + push("heavy2", heavy2); + promoted.demand.lock().unwrap().wanted = true; + q.notify_wanted(); + for _ in 0..5 { + (q.pop())(); + } + assert_eq!(*order.lock().unwrap(), ["promoted", "wanted", "bg1", "heavy1", "heavy2"]); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3061e66e8a..fea4a5897c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4251,12 +4251,15 @@ fn huge_pso_bytes() -> usize { } /// Huge driver compiles at once on the workers (default 1, `XCL_HUGE_PSO_CONCURRENCY`). +/// Applies to `>= 512 KiB` heavyweights (`BIG_COMPILES`); `256 KiB..512 KiB` medium-large compiles +/// (such as two-pass world MS PSOs) use `MEDIUM_COMPILES` so a multi-minute RT compute compile +/// cannot serialize them. fn huge_pso_concurrency() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); *V.get_or_init(|| env_count(std::env::var("XCL_HUGE_PSO_CONCURRENCY").ok().as_deref(), 1, 1, 64)) } -/// Hard cap on concurrent huge (`>= 256 KB`) driver compiles even when wanted by a title bind +/// Hard cap on concurrent huge (`>= 512 KiB`) driver compiles even when wanted by a title bind /// (`XCL_HUGE_PSO_WANTED_CONCURRENCY`, default 2, always `>= huge_pso_concurrency()`). Prevents a /// burst of lazy compute binds from launching 10+ huge driver compiles simultaneously and spiking /// process commit into OOM, while still letting a wanted build overtake 1 background build. @@ -4268,28 +4271,81 @@ fn huge_pso_wanted_concurrency() -> usize { }) } +/// Total physical RAM in bytes (`None` if the OS query fails). +fn total_physical_ram() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + unsafe { (GlobalMemoryStatusEx(&mut m) != 0 && m.ullTotalPhys > 0).then_some(m.ullTotalPhys) } +} + +/// Default `(background, wanted)` concurrency for `256 KiB..512 KiB` medium-large driver compiles +/// (`MEDIUM_COMPILES`): 3/4 on `>= 32 GiB` hosts (or unknown), 2/3 on smaller-RAM hosts. +fn medium_pso_defaults(total_phys_bytes: Option) -> (usize, usize) { + match total_phys_bytes { + Some(bytes) if bytes < (32u64 << 30) => (2, 3), + _ => (3, 4), + } +} + +/// Medium-large (`256 KiB..512 KiB`) background driver compiles at once (`XCL_MEDIUM_PSO_CONCURRENCY`). +fn medium_pso_concurrency() -> usize { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| { + let (def, _) = medium_pso_defaults(total_physical_ram()); + env_count(std::env::var("XCL_MEDIUM_PSO_CONCURRENCY").ok().as_deref(), def, 1, 64) + }) +} + +/// Medium-large (`256 KiB..512 KiB`) wanted driver compiles at once (`XCL_MEDIUM_PSO_WANTED_CONCURRENCY`). +fn medium_pso_wanted_concurrency() -> usize { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| { + let base = medium_pso_concurrency(); + let (_, def) = medium_pso_defaults(total_physical_ram()); + env_count(std::env::var("XCL_MEDIUM_PSO_WANTED_CONCURRENCY").ok().as_deref(), def.max(base), base, 64) + }) +} + /// A count from the environment: `default` when unset or not a number, clamped to the /// inclusive range `min..=max`. fn env_count(v: Option<&str>, default: usize, min: usize, max: usize) -> usize { v.and_then(|v| v.trim().parse::().ok()).unwrap_or(default).clamp(min, max) } -/// A counting semaphore: background driver compiles of big programs at once (`most` 0: the -/// `huge_pso_concurrency` of the environment; `wanted_most` 0: `huge_pso_wanted_concurrency`). +#[derive(Clone, Copy)] +enum SlotLimit { + Medium, + Big, + Fixed(usize, usize), +} + +/// A counting semaphore: background driver compiles of big programs at once. struct Slots { n: Mutex, cv: std::sync::Condvar, - most: usize, - wanted_most: usize, + limit: SlotLimit, } impl Slots { + const fn fixed(most: usize, wanted_most: usize) -> Self { + Self { n: Mutex::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Fixed(most, wanted_most) } + } + fn most(&self) -> usize { - if self.most == 0 { huge_pso_concurrency() } else { self.most } + match self.limit { + SlotLimit::Medium => medium_pso_concurrency(), + SlotLimit::Big => huge_pso_concurrency(), + SlotLimit::Fixed(most, _) => most, + } } fn wanted_most(&self) -> usize { - if self.wanted_most == 0 { huge_pso_wanted_concurrency() } else { self.wanted_most } + match self.limit { + SlotLimit::Medium => medium_pso_wanted_concurrency(), + SlotLimit::Big => huge_pso_wanted_concurrency(), + SlotLimit::Fixed(_, wanted_most) => wanted_most, + } } } @@ -4302,12 +4358,29 @@ impl Drop for SlotGuard { } } -static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 0, wanted_most: 0 }; +const LARGE_DRIVER_COMPILE: usize = 512 << 10; +static MEDIUM_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Medium }; +static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Big }; const GIANT_DRIVER_COMPILE: usize = 4 << 20; -static GIANT_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; +static GIANT_COMPILES: Slots = Slots::fixed(1, 1); fn compile_slots(bytes: usize) -> &'static Slots { - if bytes >= GIANT_DRIVER_COMPILE { &GIANT_COMPILES } else { &BIG_COMPILES } + if bytes >= GIANT_DRIVER_COMPILE { + &GIANT_COMPILES + } else if bytes >= LARGE_DRIVER_COMPILE { + &BIG_COMPILES + } else { + &MEDIUM_COMPILES + } +} + +/// Wake workers waiting in `big_compile_turn` when a queued pipeline becomes wanted by a title thread. +pub(super) fn notify_big_compile_wanted() { + for slots in [&MEDIUM_COMPILES, &BIG_COMPILES, &GIANT_COMPILES] { + let _g = slots.n.lock().unwrap(); + drop(_g); + slots.cv.notify_all(); + } } /// A driver compile of `bytes` of DXIL through `build`: a huge one on an `xcl-pso*` worker @@ -4377,7 +4450,14 @@ fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wante loop { let is_wanted = wanted(); let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; - if *n < cap && (is_wanted || commit_free()) { + let ok = if is_wanted { + // Always allow the first 2 wanted slots (never deadlock under tight commit); extra + // wanted slots on wider tiers (e.g. MEDIUM_COMPILES cap 4) require commit headroom. + *n < cap && (*n < 2 || commit_free()) + } else { + *n < cap && commit_free() + }; + if ok { *n += 1; return SlotGuard(slots); } @@ -4410,7 +4490,7 @@ mod big_compile_tests { #[test] fn wanted_builds_bypass_commit_and_unwanted_slot_but_respect_hard_cap() { - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + static S: Slots = Slots::fixed(1, 2); let held = big_compile_turn(&S, || true, || false); assert_eq!(*S.n.lock().unwrap(), 1); // Unwanted slot is full, but a wanted build immediately takes the 2nd (wanted) slot and @@ -4448,7 +4528,7 @@ mod big_compile_tests { // Mirrors GIANT_COMPILES (`most == 1, wanted_most == 1`) under low commit (< 3 GiB): // an unwanted compile waiting on commit headroom must never hold the slot and deadlock a // wanted compile. - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; + static S: Slots = Slots::fixed(1, 1); static FREE: AtomicBool = AtomicBool::new(false); let bg = std::thread::spawn(|| { let _g = big_compile_turn(&S, || FREE.load(Ordering::Acquire), || false); @@ -4469,7 +4549,7 @@ mod big_compile_tests { #[test] fn wanted_burst_is_hard_capped_to_wanted_most() { use std::sync::atomic::AtomicUsize; - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + static S: Slots = Slots::fixed(1, 2); static IN: AtomicUsize = AtomicUsize::new(0); static PEAK: AtomicUsize = AtomicUsize::new(0); let t: Vec<_> = (0..12) @@ -4508,10 +4588,42 @@ mod big_compile_tests { #[test] fn giant_driver_compiles_have_their_own_lane() { + assert!(std::ptr::eq(compile_slots(LARGE_DRIVER_COMPILE - 1), &MEDIUM_COMPILES)); + assert!(std::ptr::eq(compile_slots(LARGE_DRIVER_COMPILE), &BIG_COMPILES)); assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE - 1), &BIG_COMPILES)); assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE), &GIANT_COMPILES)); } + #[test] + fn medium_tier_defaults_scale_with_ram_and_throttle_above_two_when_commit_tight() { + assert_eq!(medium_pso_defaults(Some(16u64 << 30)), (2, 3)); + assert_eq!(medium_pso_defaults(Some(32u64 << 30)), (3, 4)); + assert_eq!(medium_pso_defaults(Some(64u64 << 30)), (3, 4)); + assert_eq!(medium_pso_defaults(None), (3, 4)); + + // With commit free: 4 wanted medium compiles run concurrently. + static S: Slots = Slots::fixed(3, 4); + let g1 = big_compile_turn(&S, || true, || true); + let g2 = big_compile_turn(&S, || true, || true); + let g3 = big_compile_turn(&S, || true, || true); + let g4 = big_compile_turn(&S, || true, || true); + assert_eq!(*S.n.lock().unwrap(), 4); + drop((g1, g2, g3, g4)); + + // Without commit free: wanted burst still gets 2 slots (no deadlock) but pauses slots 3..4. + let w1 = big_compile_turn(&S, || false, || true); + let w2 = big_compile_turn(&S, || false, || true); + assert_eq!(*S.n.lock().unwrap(), 2); + let t = std::thread::spawn(|| { + let _g = big_compile_turn(&S, || false, || true); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(!t.is_finished(), "3rd wanted slot must wait when commit headroom is exhausted"); + drop((w1, w2)); + t.join().unwrap(); + assert_eq!(*S.n.lock().unwrap(), 0); + } + #[test] fn only_a_cold_compute_compile_takes_a_slot() { assert!(!gate_compute_driver_compile(true), "the cached-blob attempt bypasses the gate"); @@ -4521,7 +4633,7 @@ mod big_compile_tests { #[test] fn the_concurrency_limit_holds_and_all_finish() { use std::sync::atomic::AtomicUsize; - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 2, wanted_most: 2 }; + static S: Slots = Slots::fixed(2, 2); static IN: AtomicUsize = AtomicUsize::new(0); static PEAK: AtomicUsize = AtomicUsize::new(0); // the two holders of the slots meet here: both are inside at once, deterministically @@ -4549,8 +4661,9 @@ mod big_compile_tests { fn small_and_title_thread_compiles_bypass_the_gate() { // every slot taken: a small compile on a worker, and a huge one on an unnamed (title) // thread, both go on at once - // (both lanes: a huge compile of any size would block on a gate it should bypass) - let mut held: Vec<_> = (0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false)).collect(); + // (all three lanes: a huge compile of any size would block on a gate it should bypass) + let mut held: Vec<_> = (0..medium_pso_concurrency()).map(|_| big_compile_turn(&MEDIUM_COMPILES, || true, || false)).collect(); + held.extend((0..huge_pso_concurrency()).map(|_| big_compile_turn(&BIG_COMPILES, || true, || false))); held.push(big_compile_turn(&GIANT_COMPILES, || true, || false)); let small = std::thread::Builder::new() .name("xcl-pso-test".into()) @@ -4578,7 +4691,7 @@ mod big_compile_tests { #[test] fn unwanted_builds_go_one_at_a_time_when_the_commit_is_there() { - static S: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 2 }; + static S: Slots = Slots::fixed(1, 2); let first = big_compile_turn(&S, || true, || false); let t = std::thread::spawn(|| { let _g = big_compile_turn(&S, || true, || false); @@ -5950,6 +6063,10 @@ unsafe fn go_background( // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); let bvh_trav = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::uses_bvh_intersect(b))); + let heavy_compute = compute + && bvh_gate_enabled() + && super::pso_async::async_heavy_compute() + && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::compute_code_len(b).is_some_and(|n| n >= crate::gpu::effects::HEAVY_CODE))); if compute { if let OwnedDesc::Compute(_, b) = &owned { if let Some(cs) = b.first() { @@ -5979,9 +6096,12 @@ unsafe fn go_background( if image_only { super::pso_async::image_only(*ppv as usize); } - if bvh_trav { + if bvh_trav && bvh_gate_enabled() { super::pso_async::bvh_traversal(*ppv as usize); } + if heavy_compute { + super::pso_async::heavy_compute(*ppv as usize); + } Some(hr) } From 33709155348907ab20c2afe1200243a06ff5666f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:34:46 +0100 Subject: [PATCH 099/258] D3D12.X: skip redundant format-alias copies when source is unchanged filter_enhanced_barriers previously scheduled a full-texture format-alias copy (e.g. R32_UINT -> R9G9B9E5_SHAREDEXP through a staging buffer) on every COMMON -> SHADER_RESOURCE enhanced barrier even when the writer texture had not entered any write state/access since its last sync, and per-resource UAV barriers in on_uav_barrier did not deduplicate against bind::activity(). Track a per-writer dirty flag and last_sync_activity in format_alias::TrackedTex (opt-out via XCL_FORMAT_ALIAS_DEDUP=0): - Clear dirty and record bind::activity() only after all reader pairs of a writer copy successfully. - Re-arm dirty on any write state/access transition (UAV, RENDER_TARGET, COPY_DEST), DISCARD/UNDEFINED barrier, format-aliased CopyResource/CopyTextureRegion write, or newly linked alias reader. - Skip redundant COMMON -> read enhanced-barrier copies when dirty is false and skip redundant PlacedUav UAV-barrier copies when bind::activity() is unchanged. Includes unit tests covering skip and re-arm paths. Verified with cargo check -p xcl --tests (exit 0, 0 new warnings). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/format_alias.rs | 254 ++++++++++++++++++++-- 1 file changed, 230 insertions(+), 24 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/format_alias.rs b/crates/xcl/src/hle/d3d12x/format_alias.rs index 874fe0a750..ae3ab872a2 100644 --- a/crates/xcl/src/hle/d3d12x/format_alias.rs +++ b/crates/xcl/src/hle/d3d12x/format_alias.rs @@ -245,12 +245,27 @@ struct TrackedTex { /// Per-subresource PC states (only tracked for `Owner::TitlePlaced`). pc_states: Vec, is_writer: bool, + /// Whether this writer may hold GPU writes not yet copied to its format-aliased readers. + /// Starts `true`, clears after all current readers are synced, and re-arms on any write + /// transition/access, discard, copy-dest, or newly linked reader. + dirty: bool, + /// `bind::activity()` (`(draws, dispatches)`) at the writer's last completed sync. + last_sync_activity: Option<(u64, u64)>, } impl TrackedTex { fn new(device: usize, va: usize, shape: TexShape, owner: Owner, initial_state: u32, is_writer: bool) -> Self { let n = if owner == Owner::TitlePlaced { shape.subresource_count().max(1) as usize } else { 0 }; - Self { device, va, shape, owner, pc_states: vec![initial_state; n], is_writer } + Self { + device, + va, + shape, + owner, + pc_states: vec![initial_state; n], + is_writer, + dirty: is_writer, + last_sync_activity: None, + } } fn uniform_state(&self) -> Option { @@ -360,6 +375,10 @@ impl AliasTable { } } for pair in new_pairs { + if let Some(w) = self.by_res.get_mut(&pair.writer) { + w.dirty = true; + w.last_sync_activity = None; + } self.add_pair(pair); } self.by_va.entry(tex.va).or_default().push(res); @@ -488,6 +507,33 @@ pub fn enabled() -> bool { *ON.get_or_init(|| !std::env::var("XCL_FORMAT_ALIAS").is_ok_and(|v| v.trim() == "0")) } +/// `XCL_FORMAT_ALIAS_DEDUP=0`: disable skipping redundant format-alias copies when the source +/// texture was not written since its last sync. +fn dedup_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !std::env::var("XCL_FORMAT_ALIAS_DEDUP").is_ok_and(|v| v.trim() == "0")) +} + +fn note_skipped_sync() { + static SKIPPED: AtomicU64 = AtomicU64::new(0); + let n = SKIPPED.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || (n.is_power_of_two() && n >= 16) { + crate::xlog_info!("D3D12.X: skipped {n} redundant format-alias texture copies (source unchanged since last sync)"); + } +} + +fn mark_writer_dirty(res: usize) { + if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 && ACTIVE_PLACED_UAV_PAIRS.load(Ordering::Relaxed) == 0 { + return; + } + if let Some(tex) = TABLE.lock().unwrap().as_mut().and_then(|t| t.by_res.get_mut(&res)) { + if tex.is_writer { + tex.dirty = true; + tex.last_sync_activity = None; + } + } +} + unsafe fn create_internal_texture(dev: *mut c_void, pc_desc: &[u8; 0x38], initial_state: u32) -> Option { let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let mut out: *mut c_void = std::ptr::null_mut(); @@ -730,6 +776,7 @@ pub(super) fn forget(res: usize) { /// format-aliased readers need a copy. Ignores split-barrier `BEGIN_ONLY` flags. pub(super) fn note_title_transition(res: usize, subresource: u32, before: u32, after: u32, flags: u32, writers_to_sync: &mut Vec<(usize, u32)>) { const BARRIER_BEGIN_ONLY: u32 = 1; + const STATE_COPY_DEST: u32 = 0x400; if TRACKED_TITLE_TEX.load(Ordering::Relaxed) == 0 || flags == BARRIER_BEGIN_ONLY { return; } @@ -744,6 +791,11 @@ pub(super) fn note_title_transition(res: usize, subresource: u32, before: u32, a return; } tex.update_state(subresource, after); + let write_bits = STATE_UAV | STATE_RENDER_TARGET | STATE_COPY_DEST; + if tex.is_writer && ((before & write_bits != 0) || (after & write_bits != 0)) { + tex.dirty = true; + tex.last_sync_activity = None; + } let uniform = tex.uniform_state(); let is_writer = tex.is_writer; let leaving_write = (before & (STATE_UAV | STATE_RENDER_TARGET) != 0) && (after & (STATE_UAV | STATE_RENDER_TARGET) == 0); @@ -808,6 +860,7 @@ pub(super) unsafe fn filter_enhanced_barriers(n: u32, groups: *const c_void, wri | D3D12_BARRIER_LAYOUT_COMPUTE_QUEUE_COPY_SOURCE ) }; + let dedup = dedup_enabled(); let slice = std::slice::from_raw_parts(groups as *const D3D12_BARRIER_GROUP, group_count); for grp in slice { if grp.Type != D3D12_BARRIER_TYPE_TEXTURE { @@ -823,35 +876,50 @@ pub(super) unsafe fn filter_enhanced_barriers(n: u32, groups: *const c_void, wri continue; } let tbs = std::slice::from_raw_parts(ptr, count); - let g = TABLE.lock().unwrap(); - let Some(t) = g.as_ref() else { + let mut g = TABLE.lock().unwrap(); + let Some(t) = g.as_mut() else { continue; }; for tb in tbs { - let discard = (tb.Flags.0 as u32) & (D3D12_TEXTURE_BARRIER_FLAG_DISCARD.0 as u32) != 0 - || tb.LayoutBefore == D3D12_BARRIER_LAYOUT_UNDEFINED; - if discard { - continue; - } let res: usize = std::mem::transmute_copy(&tb.pResource); if res == 0 { continue; } - let Some(tex) = t.by_res.get(&res) else { + let has_pair = t.pairs.iter().any(|p| p.writer == res); + let Some(tex) = t.by_res.get_mut(&res) else { continue; }; - if tex.owner != Owner::TitlePlaced || !tex.is_writer || !t.pairs.iter().any(|p| p.writer == res) { + if tex.owner != Owner::TitlePlaced || !tex.is_writer || !has_pair { + continue; + } + let discard = (tb.Flags.0 as u32) & (D3D12_TEXTURE_BARRIER_FLAG_DISCARD.0 as u32) != 0 + || tb.LayoutBefore == D3D12_BARRIER_LAYOUT_UNDEFINED; + if discard { + tex.dirty = true; + tex.last_sync_activity = None; continue; } let ab = tb.AccessBefore.0 as u32; let aa = tb.AccessAfter.0 as u32; let before_write = (ab & write_access != 0) || is_write_layout(tb.LayoutBefore); let after_write = (aa & write_access != 0) || is_write_layout(tb.LayoutAfter); + if before_write || after_write { + tex.dirty = true; + tex.last_sync_activity = None; + } let common_to_read = ab == 0 && is_common_layout(tb.LayoutBefore) && ((aa & read_access != 0) || is_read_layout(tb.LayoutAfter)); - if (before_write && !after_write) || common_to_read { + if before_write && !after_write { if let Some(st) = tex.uniform_state() { writers_to_sync.push((res, st)); } + } else if common_to_read { + if !dedup || tex.dirty { + if let Some(st) = tex.uniform_state() { + writers_to_sync.push((res, st)); + } + } else { + note_skipped_sync(); + } } } } @@ -981,11 +1049,11 @@ unsafe fn copy_one_subresource_through_buffer( true } -unsafe fn sync_pair(list: *mut c_void, dev: &ID3D12Device, ty: D3D12_COMMAND_LIST_TYPE, pair: AliasPair, writer_state: u32) { +unsafe fn sync_pair(list: *mut c_void, dev: &ID3D12Device, ty: D3D12_COMMAND_LIST_TYPE, pair: AliasPair, writer_state: u32) -> bool { let w_ptr = pair.writer as *mut c_void; let r_ptr = pair.reader as *mut c_void; let (Some(writer_res), Some(reader_res)) = (ID3D12Resource::from_raw_borrowed(&w_ptr), ID3D12Resource::from_raw_borrowed(&r_ptr)) else { - return; + return false; }; let target_srv = if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { STATE_SRV_ALL } else { STATE_SRV_NON_PIXEL }; @@ -1009,16 +1077,16 @@ unsafe fn sync_pair(list: *mut c_void, dev: &ID3D12Device, ty: D3D12_COMMAND_LIS .and_then(|t| t.by_res.get(&pair.reader)) .and_then(TrackedTex::uniform_state) else { - return; + return false; }; // On a compute list, never emit transitions referencing DIRECT-only states // (`RENDER_TARGET`, `INDEX_BUFFER`, `VERTEX_AND_CONSTANT_BUFFER`, `DEPTH_*`, `PIXEL_SHADER_RESOURCE`). if !state_valid_on_list(ty, st) { - return; + return false; } (st, st) } - Owner::PlacedUav => return, + Owner::PlacedUav => return false, }; if writer_state != D3D12_RESOURCE_STATE_COPY_SOURCE.0 as u32 { @@ -1062,6 +1130,7 @@ unsafe fn sync_pair(list: *mut c_void, dev: &ID3D12Device, ty: D3D12_COMMAND_LIS ); } } + ok } /// Sync active placed-UAV -> format-aliased SRV pairs after a UAV barrier on `list`. @@ -1077,12 +1146,14 @@ pub(super) unsafe fn on_uav_barrier(list: *mut c_void, specific_targets: Option< if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { return; } + let act = super::bind::activity(); + let dedup = dedup_enabled(); // Skip duplicate back-to-back global UAV barriers when no draw or dispatch executed in between. if specific_targets.is_none() { - let act = super::bind::activity(); let mut g = LIST_STATES.lock().unwrap(); let ls = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); if ls.last_activity == act && act != (0, 0) { + note_skipped_sync(); return; } ls.last_activity = act; @@ -1092,6 +1163,7 @@ pub(super) unsafe fn on_uav_barrier(list: *mut c_void, specific_targets: Option< return; }; let dev_raw = dev.as_raw() as usize; + let mut skipped = 0usize; let pairs: Vec = { let g = TABLE.lock().unwrap(); match g.as_ref() { @@ -1100,16 +1172,47 @@ pub(super) unsafe fn on_uav_barrier(list: *mut c_void, specific_targets: Option< .iter() .copied() .filter(|p| { - p.writer_owner == Owner::PlacedUav - && p.device == dev_raw - && specific_targets.is_none_or(|targets| targets.contains(&p.writer)) + if p.writer_owner != Owner::PlacedUav + || p.device != dev_raw + || !specific_targets.is_none_or(|targets| targets.contains(&p.writer)) + { + return false; + } + if dedup && act != (0, 0) { + if let Some(w) = t.by_res.get(&p.writer) { + if !w.dirty && w.last_sync_activity == Some(act) { + skipped += 1; + return false; + } + } + } + true }) .collect(), None => return, } }; + for _ in 0..skipped { + note_skipped_sync(); + } + let mut writer_ok: HashMap = HashMap::new(); for pair in pairs { - sync_pair(list, &dev, ty, pair, STATE_UAV); + let ok = sync_pair(list, &dev, ty, pair, STATE_UAV); + let entry = writer_ok.entry(pair.writer).or_insert(true); + *entry &= ok; + } + if !writer_ok.is_empty() { + let mut g = TABLE.lock().unwrap(); + if let Some(t) = g.as_mut() { + for (writer, all_ok) in writer_ok { + if all_ok { + if let Some(w) = t.by_res.get_mut(&writer) { + w.dirty = false; + w.last_sync_activity = Some(act); + } + } + } + } } } @@ -1128,6 +1231,7 @@ pub(super) unsafe fn sync_title_writers(list: *mut c_void, writers: &[(usize, u3 return; }; let dev_raw = dev.as_raw() as usize; + let act = super::bind::activity(); let mut seen = HashSet::new(); for &(writer, state) in writers { if !seen.insert(writer) { @@ -1140,8 +1244,19 @@ pub(super) unsafe fn sync_title_writers(list: *mut c_void, writers: &[(usize, u3 None => continue, } }; + if pairs.is_empty() { + continue; + } + let mut all_ok = true; for pair in pairs { - sync_pair(list, &dev, ty, pair, state); + all_ok &= sync_pair(list, &dev, ty, pair, state); + } + if all_ok { + let mut g = TABLE.lock().unwrap(); + if let Some(w) = g.as_mut().and_then(|t| t.by_res.get_mut(&writer)) { + w.dirty = false; + w.last_sync_activity = Some(act); + } } } } @@ -1196,6 +1311,7 @@ pub(super) unsafe fn try_copy_resource(list: *mut c_void, dst: usize, src: usize }; let ok = copy_all_subresources_through_buffer(list, &dev, d, s); if ok { + mark_writer_dirty(dst); static N: AtomicU64 = AtomicU64::new(0); let k = N.fetch_add(1, Ordering::Relaxed); if k < 8 || k.is_power_of_two() { @@ -1247,7 +1363,7 @@ pub(super) unsafe fn try_copy_texture_region( let Some(dev) = list_x::device_of_list(list) else { return false; }; - copy_one_subresource_through_buffer( + let ok = copy_one_subresource_through_buffer( list, &dev, d, @@ -1256,7 +1372,11 @@ pub(super) unsafe fn try_copy_texture_region( s, &sd, src.Anonymous.SubresourceIndex, - ) + ); + if ok { + mark_writer_dirty(d.as_raw() as usize); + } + ok } #[cfg(test)] @@ -1382,4 +1502,90 @@ mod tests { assert!(!subresource_footprints_compatible(10, &fp(32, 32, 1), 42, &fp(32, 32, 1)), "8 Bpp vs 4 Bpp must be rejected"); assert!(subresource_footprints_compatible(98, &fp(64, 64, 1), 3, &fp(16, 16, 1)), "BC7 64x64 == R32G32B32A32 16x16"); } + + #[test] + fn enhanced_common_to_read_skips_unchanged_writer_and_rearms_on_write() { + let dev = 0x7A00_0001usize; + let va = 0x7A00_0000_0000usize; + let writer = 0x7A00_1001usize; + let reader = 0x7A00_1002usize; + let reader2 = 0x7A00_1003usize; + let uav_shape = shape(42, 64, 64, 1, 1); // R32_UINT + let srv_shape = shape(67, 64, 64, 1, 1); // R9G9B9E5_SHAREDEXP + + { + let mut g = TABLE.lock().unwrap(); + let t = g.get_or_insert_with(AliasTable::new); + t.insert(writer, TrackedTex::new(dev, va, uav_shape, Owner::TitlePlaced, STATE_COMMON, true)); + t.insert(reader, TrackedTex::new(dev, va, srv_shape, Owner::TitlePlaced, STATE_COMMON, false)); + } + + let mk_group = |tb: &D3D12_TEXTURE_BARRIER| D3D12_BARRIER_GROUP { + Type: D3D12_BARRIER_TYPE_TEXTURE, + NumBarriers: 1, + Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: tb as *const _ }, + }; + let mk_tb = |ab: D3D12_BARRIER_ACCESS, aa: D3D12_BARRIER_ACCESS, lb: D3D12_BARRIER_LAYOUT, la: D3D12_BARRIER_LAYOUT, flags: D3D12_TEXTURE_BARRIER_FLAGS| -> D3D12_TEXTURE_BARRIER { + D3D12_TEXTURE_BARRIER { + SyncBefore: D3D12_BARRIER_SYNC_ALL, + SyncAfter: D3D12_BARRIER_SYNC_ALL, + AccessBefore: ab, + AccessAfter: aa, + LayoutBefore: lb, + LayoutAfter: la, + pResource: unsafe { std::mem::transmute_copy(&writer) }, + Subresources: D3D12_BARRIER_SUBRESOURCE_RANGE::default(), + Flags: flags, + } + }; + + // 1. Fresh writer starts dirty: COMMON -> SRV triggers initial sync. + let tb_c2r = mk_tb( + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_SHADER_RESOURCE, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_SHADER_RESOURCE, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + ); + let grp = mk_group(&tb_c2r); + let mut out = Vec::new(); + unsafe { filter_enhanced_barriers(1, &grp as *const _ as *const c_void, &mut out) }; + assert_eq!(out, vec![(writer, STATE_COMMON)]); + + // Simulate completed sync clearing dirty flag. + TABLE.lock().unwrap().as_mut().unwrap().by_res.get_mut(&writer).unwrap().dirty = false; + + // 2. Second COMMON -> SRV with no intervening write must be skipped. + out.clear(); + unsafe { filter_enhanced_barriers(1, &grp as *const _ as *const c_void, &mut out) }; + assert!(out.is_empty(), "unchanged writer must skip redundant COMMON -> SRV copy"); + + // 3. Entering UAV layout (`COMMON -> UAV`) re-arms dirty without syncing yet. + let tb_c2u = mk_tb( + D3D12_BARRIER_ACCESS_COMMON, + D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + ); + let grp_u = mk_group(&tb_c2u); + unsafe { filter_enhanced_barriers(1, &grp_u as *const _ as *const c_void, &mut out) }; + assert!(out.is_empty()); + assert!(TABLE.lock().unwrap().as_ref().unwrap().by_res.get(&writer).unwrap().dirty); + + // 4. Subsequent COMMON -> SRV now syncs again. + unsafe { filter_enhanced_barriers(1, &grp as *const _ as *const c_void, &mut out) }; + assert_eq!(out, vec![(writer, STATE_COMMON)]); + + // 5. Linking a new format-aliased reader re-arms dirty on the writer. + TABLE.lock().unwrap().as_mut().unwrap().by_res.get_mut(&writer).unwrap().dirty = false; + TABLE.lock().unwrap().as_mut().unwrap().insert(reader2, TrackedTex::new(dev, va, srv_shape, Owner::TitlePlaced, STATE_COMMON, false)); + assert!(TABLE.lock().unwrap().as_ref().unwrap().by_res.get(&writer).unwrap().dirty); + + // Prevent ManuallyDrop::drop on synthetic pointer in tb_c2r / tb_c2u (already ManuallyDrop) + // and clean up test entries from global TABLE. + forget(reader2); + forget(reader); + forget(writer); + } } From c465ba68fcc9e3987687410174b9d114293873cd Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:51:15 +0100 Subject: [PATCH 100/258] D3D12.X: retry uploads after lazy mip mapping failures Port upstream PR #2470 (by razormontana, commit d5f6daf7) cleanly onto amd-dev with #1514 follow_key and indexed Table::pending_res. An upload to unmapped tiles drops the copies, so the source hash in LAST_CONTENT must not suppress a later upload of the same bytes. Map other requested levels and keep their copies in the current batch, returning whether every requested level received pages. Part of #1773. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 34 +++++++++--- crates/xcl/src/hle/d3d12x/vram.rs | 61 +++++++++++++++------ 2 files changed, 70 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index bbc792b2c9..1d984f4cd9 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1244,9 +1244,10 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { if super::present::trace_frame() { note_content(va, &r, &subs); } - if super::vram::level_pages() { - // (the queue waits for these mappings before the copies: `vram::before_execute` below) - map_levels_with_texels(&r, &subs); + if super::vram::level_pages() && !map_levels_with_texels(&r, &subs) { + // The copies into unmapped tiles will be dropped. Upload the backed levels, + // and let the next refresh that selects this texture retry the same bytes. + LAST_CONTENT.lock().unwrap().remove(&(r.as_raw() as usize)); } batch.push((r, subs, states)); } @@ -1282,14 +1283,15 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { /// placed with lazy levels; any other: nothing to do. A level of zeros has no texels: a streamed /// texture's larger levels before the title has memory behind them (read as zeros, /// `read_committed`). It keeps no pages, reads as zeros as it would with them, and its copy goes -/// to tiles that are not mapped, which drops it (tiled resources tier 2). -unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) { +/// to tiles that are not mapped, which drops it (tiled resources tier 2). Returns whether all +/// levels with texels have pages. The upload queue waits for their mappings in `before_execute`. +unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> bool { if !super::vram::has_lazy_levels(r.as_raw() as usize) { - return; + return true; } // (one slice: its subresources are its levels) let present: Vec = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); - super::vram::map_levels(r, Some(&present)); + super::vram::map_levels(r, Some(&present)) } /// Whether every byte of `b` is zero (eight at a time: gigabytes a second where it is). @@ -2794,8 +2796,24 @@ mod tests { assert!(!VirtualAlloc((at + top) as *const c_void, size - top, MEM_COMMIT, PAGE_READWRITE).is_null()); std::ptr::copy_nonoverlapping(whole.as_ptr().add(top), (at + top) as *mut u8, size - top); let full = place_tex(at); + let full_key = full.as_raw() as usize; + super::super::vram::FAIL_LEVEL_BIND_FOR_TEST.with(|failure| failure.set(Some((full_key, 0)))); + refresh(queue.as_raw()); + assert_eq!(dev_pages() - p0, ((all - top_tiles) as usize) << 16, "the failed mapping left mip 0 without pages"); + assert!(read_sub(&full, 0).iter().all(|&b| b == 0), "the failed mip still reads as zeros"); + assert!(read_sub(&full, 1) == want[1].data, "the other mips still upload"); + + // Offer the texture again without changing any of its source bytes. + { + let mut textures = TEXTURES.lock().unwrap(); + let entry = textures.by_res.get_mut(&full_key).unwrap(); + assert!(!entry.pending); + entry.pending = true; + textures.pending_res.insert(full_key); + adjust_pending(1); + } refresh(queue.as_raw()); - assert_eq!(dev_pages() - p0, (all as usize) << 16, "mip 0's pages come with its texels; the other levels' are shared"); + assert_eq!(dev_pages() - p0, (all as usize) << 16, "retry maps mip 0 with the same source bytes; the other levels are shared"); for sub in 0..11u32 { assert!(read_sub(&full, sub) == want[sub as usize].data, "level {sub} once all of it is there"); } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index bdcfbd2e6f..4601117a00 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -547,6 +547,11 @@ pub(super) fn level_pages() -> bool { #[cfg(test)] pub(super) static LEVEL_PAGES_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +#[cfg(test)] +thread_local! { + pub(super) static FAIL_LEVEL_BIND_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + /// Of the textures with lazy levels there are now: how many, the tiles they stand for, and the /// tiles of them that have pages; and the level groups given pages so far. static LEVEL_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; @@ -1072,6 +1077,16 @@ impl Pages { sub: u32, range: std::ops::Range, ) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { + #[cfg(test)] + if FAIL_LEVEL_BIND_FOR_TEST.with(|failure| { + if failure.get() != Some((res.as_raw() as usize, sub)) { + return false; + } + failure.take(); + true + }) { + return None; + } let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); let timer = step(Step::Sweep); @@ -1921,35 +1936,48 @@ pub unsafe fn place_pages( place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, lazy, riid, ppv) } -/// The levels `levels` of `res` (None: all of them) get their pages if they have none yet: a -/// texture placed with lazy levels (any other: nothing to do). Returns the levels that got pages -/// by this call - the queue the texture is used on next has to wait for that (`before_execute`), -/// and what the pages held before is another texture's. -pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> Vec { +/// Give the requested levels of a lazy texture pages (None: all levels). Returns whether every +/// requested level has pages. Other textures have nothing to map. The queue that uses the +/// texture waits for the mappings in `before_execute`. +pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> bool { + if levels.is_some_and(|levels| levels.is_empty()) { + return true; + } let key = res.as_raw() as usize; let mut g = PAGES.lock().unwrap(); for (&dev_key, pages) in g.iter_mut() { let Some(pages) = pages.as_mut() else { continue }; let Some(t) = pages.targets.get(&key) else { continue }; - let Some(lv) = t.levels.as_ref().filter(|_| t.mapped) else { return Vec::new() }; + let Some(lv) = t.levels.as_ref() else { return true }; + if !t.mapped { + return false; + } let mut wanted: Vec = match levels { Some(l) => l.iter().map(|&x| lv.group_of(x)).collect(), None => (0..lv.groups.len()).collect(), }; wanted.sort_unstable(); wanted.dedup(); - let todo: Vec<(usize, u32, u32, u32, std::ops::Range)> = - wanted.into_iter().filter(|&k| !lv.groups[k].3).map(|k| (k, lv.groups[k].0, lv.groups[k].1, lv.groups[k].2, lv.levels_of(k))).collect(); + let todo: Vec<(usize, u32, u32, u32)> = wanted + .into_iter() + .filter_map(|k| { + let (_, first, count, mapped) = lv.groups[k]; + (!mapped).then(|| (k, lv.levels_of(k).start, first, count)) + }) + .collect(); if todo.is_empty() { - return Vec::new(); + return true; } let (va, console_bytes, total) = (t.va, t.console_bytes, t.total); let d = dev_key as *mut c_void; - let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return Vec::new() }; - let mut fresh = Vec::new(); - for (k, sub, first, n, levels) in todo { - let Some((used, used_extra, _)) = pages.bind_range(dev, res, None, va, console_bytes, total, sub, first as usize..(first + n) as usize) else { continue }; - let Some(t) = pages.targets.get_mut(&key) else { return fresh }; + let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return false }; + let mut complete = true; + for (k, sub, first, n) in todo { + let Some((used, used_extra, _)) = pages.bind_range(dev, res, None, va, console_bytes, total, sub, first as usize..(first + n) as usize) else { + complete = false; + continue; + }; + let Some(t) = pages.targets.get_mut(&key) else { return false }; t.used.extend(used); t.used_extra.extend(used_extra); if let Some(l) = t.levels.as_mut() { @@ -1961,11 +1989,10 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let (textures, stand, mapped, _) = level_stats(); crate::xlog_info!("D3D12.X: level pages: {textures} textures standing for {} MB have pages for {} MB ({groups} levels given pages so far)", stand >> 4, mapped >> 4); } - fresh.extend(levels); } - return fresh; + return complete; } - Vec::new() + true } /// Whether `resource` is a texture whose levels get their pages one by one (`map_levels`). From bafa2b28db0560270f3005b8f25c32c065e08b6d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:52:33 +0100 Subject: [PATCH 101/258] D3D12.X: per-draw mirror sync copies only pages the title wrote Port upstream PR #2478 (by KOLESNiii, commit 2bdfb908) cleanly onto amd-dev. sync_title_buffers previously copied the full drawn range of every mirrored buffer on every draw even when the title never rewrote it (#2389 / #2393). Track write-watched mirror source pages via GetWriteWatch (without reset) plus MIRROR_STALE bits handed off by title_textures' write-watch look (mirror_look_begin / mirror_pages_written), falling back to full-range copy if a look overlaps the draw or the source is not write-watched. Includes regression test. Part of #2393. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/list_x.rs | 214 +++++++++++++++++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 11 +- 2 files changed, 213 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 57dfaa9ac9..b9752afbb4 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3727,6 +3727,128 @@ fn mirrored(va: u64, bytes: usize) -> Option { MIRRORS.lock().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m)| m + (va - s) as usize) } +/// Per mirror (start, bytes, a bit per 4 KiB page from `start & !0xfff`): pages of its source +/// the title wrote that a look took off the write-watch (`mirror_pages_written`) and no draw has +/// copied since. A draw copies these and the pages still on the write-watch (`written_pages`). +static MIRROR_STALE: Mutex)>> = Mutex::new(Vec::new()); +/// odd while a look takes pages off the write-watch and has not handed them on yet: a draw +/// then (or across one) copies its whole range +static MIRROR_LOOK_SEQ: AtomicU64 = AtomicU64::new(0); +// the write-watch's answer for a draw's range (one per thread, like `title_textures`' look) +thread_local! { + static WRITTEN_BUF: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// The title's ranges with a mirror (start, end), which `title_textures`' look watches. +pub(super) fn mirror_sources() -> Vec<(usize, usize)> { + MIRRORS.lock().unwrap().iter().map(|&(s, l, _)| (s as usize, s as usize + l)).collect() +} + +/// Changes when a mirror is made (`mirror_sources` then has a new range). +pub(super) fn mirror_sources_gen() -> u64 { + MIRROR_BYTES.load(Ordering::Relaxed) +} + +/// A look is about to take written pages off the write-watch. +pub(super) fn mirror_look_begin() { + MIRROR_LOOK_SEQ.fetch_add(1, Ordering::SeqCst); +} + +/// The look took `dirty` (4 KiB pages, sorted) off the write-watch: those in a mirror's +/// source are copied at the mirror's next draw. +pub(super) fn mirror_pages_written(dirty: &[usize]) { + { + let mut g = MIRROR_STALE.lock().unwrap(); + for (s, l, bits) in g.iter_mut() { + let (s, e) = (*s as usize, *s as usize + *l); + let first = dirty.partition_point(|&p| p + 0x1000 <= s); + for &p in dirty[first..].iter().take_while(|&&p| p < e) { + let k = (p - (s & !0xfff)) >> 12; + bits[k / 64] |= 1 << (k % 64); + } + } + } + MIRROR_LOOK_SEQ.fetch_add(1, Ordering::SeqCst); +} + +/// The pages of `[a, end)` (from `a & !0xfff`, in the mirror of the buffer at `va`) a draw +/// copies: those on the write-watch (written since the last look) and those a look took off it +/// since the last copy (whose bits are cleared). None when the range is not write-watched. +unsafe fn written_pages(va: u64, a: usize, end: usize) -> Option> { + use windows_sys::Win32::System::Memory::GetWriteWatch; + let base = a & !0xfff; + let n = (end - base + 0xfff) >> 12; + let mut pages = vec![false; n]; + WRITTEN_BUF.with(|c| { + let mut buf = c.borrow_mut(); + if buf.len() < n { + buf.resize(n, std::ptr::null_mut()); + } + let (mut count, mut granularity) = (n, 0u32); + // (no reset: the look's to do, which hands the pages on) + if GetWriteWatch(0, base as *const c_void, n << 12, buf.as_mut_ptr(), &mut count, &mut granularity) != 0 || granularity != 0x1000 { + return None; + } + for &p in &buf[..count] { + pages[(p as usize - base) >> 12] = true; + } + Some(()) + })?; + let mut g = MIRROR_STALE.lock().unwrap(); + if let Some((s, _, bits)) = g.iter_mut().find(|(s, l, _)| va >= *s && end as u64 <= *s + *l as u64) { + let first = (base - (*s as usize & !0xfff)) >> 12; + for (k, page) in pages.iter_mut().enumerate() { + let j = first + k; + if bits[j / 64] >> (j % 64) & 1 != 0 { + *page = true; + bits[j / 64] &= !(1 << (j % 64)); + } + } + } + Some(pages) +} + +/// `[from, from + len)` of the title's buffer at `va` (`bytes` long) into its mirror at +/// `mirror`: only the pages the title wrote since they were last copied (#2393), all of it when +/// the source is not write-watched or a look ran meanwhile. +/// +/// (No `readable` first – for a range not resident or over 16 pages it walks the region with +/// `VirtualQuery`, a 1–9 ms stall of the render thread (#2392): the copy cannot fault, and a +/// page the title freed or protected since keeps what the mirror had.) +unsafe fn copy_written(va: u64, mirror: usize, bytes: u32, from: u64, len: u64) { + let from = from.min(bytes as u64); + let len = len.min(bytes as u64 - from) as usize; + if len == 0 { + return; + } + let (a, end) = ((va + from) as usize, (va + from) as usize + len); + let copy = |lo: usize, hi: usize| { + let (lo, hi) = (lo.max(a), hi.min(end)); + if lo < hi { + super::title_textures::copy_committed_region(lo, (mirror + (lo - va as usize)) as *mut u8, hi - lo); + } + }; + let seq = MIRROR_LOOK_SEQ.load(Ordering::SeqCst); + let Some(pages) = (seq % 2 == 0).then(|| written_pages(va, a, end)).flatten() else { return copy(a, end) }; + let base = a & !0xfff; + let mut k = 0; + while k < pages.len() { + if !pages[k] { + k += 1; + continue; + } + let first = k; + while k < pages.len() && pages[k] { + k += 1; + } + copy(base + (first << 12), base + (k << 12)); + } + // a look took pages off the write-watch meanwhile, which may not have been handed on yet + if MIRROR_LOOK_SEQ.load(Ordering::SeqCst) != seq { + copy(a, end); + } +} + /// The mirror address of the title's buffer at `va`; its range's mirror is made (and filled /// once) the first time. unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { @@ -3756,6 +3878,8 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { None => u.alloc(len, 0x1_0000)? as usize, }; std::ptr::copy_nonoverlapping(start as *const u8, p as *mut u8, len); + let pages = (((start as usize + len + 0xfff) & !0xfff) - (start as usize & !0xfff)) >> 12; + MIRROR_STALE.lock().unwrap().push((start, len, vec![0; pages.div_ceil(64)])); g.push((start, len, p)); let total = MIRROR_BYTES.fetch_add(len as u64, Ordering::Relaxed) + len as u64; if g.len() <= 8 || g.len().is_power_of_two() { @@ -3783,16 +3907,7 @@ pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, } v }; - // (no `readable` first – for a range not resident or over 16 pages it walks the region with - // `VirtualQuery`, a 1–9 ms stall of the render thread (#2392): the copy cannot fault, and a - // page the title freed or protected since keeps what the mirror had) - let copy = |va: u64, mirror: usize, bytes: u32, from: u64, len: u64| { - let from = from.min(bytes as u64); - let len = len.min(bytes as u64 - from) as usize; - if len > 0 { - super::title_textures::copy_committed_region((va + from) as usize, (mirror + from as usize) as *mut u8, len); - } - }; + let copy = |va: u64, mirror: usize, bytes: u32, from: u64, len: u64| copy_written(va, mirror, bytes, from, len); // the vertices read: [lo, hi) let (lo, hi) = match (indexed, ib) { (Some((first, count, base)), Some((va, bytes, format))) => { @@ -7395,6 +7510,85 @@ mod tests { } } + /// The per-draw sync copies only the pages of a write-watched source the title wrote + /// (#2393): none after a look found it unchanged; a page written since the look at the next + /// draw (still on the write-watch); a page written and then taken off the write-watch by a + /// look at the draw after that look (handed on by `mirror_pages_written`). A source that is + /// not write-watched is copied at every draw, as before. + #[test] + fn the_mirror_sync_copies_only_the_pages_the_title_wrote() { + use windows_sys::Win32::System::Memory::{GetWriteWatch, VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + if crate::gpu::uma::get().is_none() { + crate::gpu::recomp::runner::skip_test("no unified memory"); + return; + } + unsafe { + let (len, bytes, stride) = (0x1_0000usize, 0x3000u32, 16u32); + let list = 0x7e57_0000_2393usize as *mut c_void; + // a look as `title_textures` makes it: written pages off the write-watch, handed on + let look = |src: *mut u8| { + mirror_look_begin(); + let mut buf = vec![std::ptr::null_mut(); len >> 12]; + let (mut n, mut granularity) = (buf.len(), 0u32); + assert_eq!(GetWriteWatch(1, src as *const c_void, len, buf.as_mut_ptr(), &mut n, &mut granularity), 0); + let dirty: Vec = buf[..n].iter().map(|&p| p as usize).collect(); + mirror_pages_written(&dirty); + }; + // the draw, with the mirror's pages set to `mark` first; again when another test's + // look overlapped it (a draw then copies its whole range) + let draw = |m: *mut u8, mark: u8| loop { + std::ptr::write_bytes(m, mark, bytes as usize); + let seq = MIRROR_LOOK_SEQ.load(Ordering::SeqCst); + sync_title_buffers(list, None, 0, bytes / stride, 1); + if seq % 2 == 0 && MIRROR_LOOK_SEQ.load(Ordering::SeqCst) == seq { + break; + } + }; + let page = |m: *mut u8, k: usize| *m.add(k << 12 | 0x123); + + let src = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) as *mut u8; + assert!(!src.is_null()); + std::ptr::write_bytes(src, 0x11, bytes as usize); + assert_ne!(gpu_va(list, src as u64, bytes as usize, "test vertex buffer", true), src as u64); + let m = mirrored(src as u64, bytes as usize).unwrap() as *mut u8; + with_bindings(list, |b| { + b.vertex_titles.insert(0, (src as u64, bytes, stride)); + }); + // the title's writes before the mirror was made: on the write-watch until a look, + // copied once at the draw after it + look(src); + draw(m, 0xee); + assert_eq!((page(m, 0), page(m, 2)), (0x11, 0x11), "pages written before the look are copied once"); + draw(m, 0xee); + assert_eq!((page(m, 0), page(m, 1), page(m, 2)), (0xee, 0xee, 0xee), "unchanged since: nothing copied"); + *src.add(0x1000 | 0x123) = 0x22; + draw(m, 0xee); + assert_eq!((page(m, 0), page(m, 1), page(m, 2)), (0xee, 0x22, 0xee), "the page written since the look is copied"); + look(src); + *src.add(0x2000 | 0x123) = 0x33; + look(src); + draw(m, 0xee); + assert_eq!((page(m, 0), page(m, 2)), (0xee, 0x33), "the page a look took off the write-watch is copied at the next draw"); + draw(m, 0xee); + assert_eq!(page(m, 2), 0xee, "and only once"); + + // not write-watched: every draw copies + let plain = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + assert!(!plain.is_null()); + std::ptr::write_bytes(plain, 0x44, bytes as usize); + assert_ne!(gpu_va(list, plain as u64, bytes as usize, "test vertex buffer", true), plain as u64); + let pm = mirrored(plain as u64, bytes as usize).unwrap() as *mut u8; + with_bindings(list, |b| { + b.vertex_titles.insert(0, (plain as u64, bytes, stride)); + }); + draw(pm, 0xee); + assert_eq!((page(pm, 0), page(pm, 2)), (0x44, 0x44), "a source that is not write-watched is copied"); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + // (the ranges stay allocated: the mirror table is never emptied) + } + } + #[test] fn occlusion_tracks_dropped_draws_and_active_counter() { let mut occ = Occlusion::default(); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 1d984f4cd9..2ce33e3ae8 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -430,8 +430,9 @@ static TEXTURES: Mutex = Mutex::new(Table::new()); static REFRESH: Mutex<()> = Mutex::new(()); static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); -/// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen)` -static WATCH_CACHE: Mutex>)>> = Mutex::new(None); +/// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen, +/// list_x::mirror_sources_gen)` +static WATCH_CACHE: Mutex>)>> = Mutex::new(None); /// the queue uploads go to, per device static QUEUES: Mutex> = Mutex::new(BTreeMap::new()); static UPLOADS: AtomicU64 = AtomicU64::new(0); @@ -795,6 +796,7 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { super::sparse::mapped_gen(), TEXTURES_GEN.load(Ordering::Acquire), crate::hle::kernelx::graphics_reservations_gen(), + super::list_x::mirror_sources_gen(), ); { let g = WATCH_CACHE.lock().unwrap(); @@ -811,6 +813,8 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().by_res.values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); wanted.extend(super::sparse::mapped_ranges()); wanted.extend(super::sparse::gpu_view::sources()); + // the sources of buffer mirrors: a draw copies only the pages written (`list_x::copy_written`) + wanted.extend(super::list_x::mirror_sources()); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); computed @@ -878,6 +882,7 @@ unsafe fn refresh_once(queue: *mut c_void) { if buf.len() < 16384 { buf.resize(16384, std::ptr::null_mut()); } + super::list_x::mirror_look_begin(); for &(base, size) in ranges.iter() { take_written(base, size, &mut buf, &mut dirty, &mut page); } @@ -886,6 +891,8 @@ unsafe fn refresh_once(queue: *mut c_void) { // (`XCL_PAGE_ALIAS`), a write through one view counting for all of them crate::hle::kernelx::guards::take_dirty(&mut dirty, page as usize); dirty.sort_unstable(); + // pages of buffer mirrors' sources, now off the write-watch: their next draw copies them + super::list_x::mirror_pages_written(&dirty); dirty.len() }); super::sparse::note_watch(watch_t0.elapsed(), dirty_len); From 28ec004d8e9e426f58486fdbf6c908329c0633da Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:53:56 +0100 Subject: [PATCH 102/258] D3D12.X: clear LAST_CONTENT on unmap/remap and guard present RTV tracking Fix two cache-safe runtime bugs (#2460 and #2456): 1. title_textures.rs (#2460): clear LAST_CONTENT when unmapping superseded textures (keep / retire_overlapping) and when remapping uncovered textures in forget(). Under XCL_TEXTURE_LEVEL_PAGES=1, retaining the old content hash caused same_as_last_upload to suppress re-upload and skip map_levels_with_texels, leaving uncovered streamed textures permanently unmapped/black. 2. present.rs (#2456): guard note_rtv and note_rt0 with IN_PRESENT so Compositor::record does not leak DXGI swap-chain back-buffer COM references into RTVS (which prevented ResizeBuffers on multi-plane/gameplay transitions with 0x887A0001). Includes unit test. Fixes #2460, #2456. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/present.rs | 18 ++++++++++++++++-- crates/xcl/src/hle/d3d12x/title_textures.rs | 6 +++++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index ccab1a7318..48858707d9 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -210,7 +210,7 @@ unsafe fn release(p: usize) { } pub unsafe fn note_rtv(handle: usize, res: *mut c_void) { - if !enabled() { + if !enabled() || IN_PRESENT.with(|c| c.get()) { return; } let mut g = RTVS.lock().unwrap(); @@ -272,7 +272,7 @@ pub fn rt0_resource(list: usize) -> Option { } pub fn note_rt0(list: usize, handle: usize) { - if !enabled() { + if !enabled() || IN_PRESENT.with(|c| c.get()) { return; } LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(list, handle); @@ -2000,4 +2000,18 @@ mod frame_dump_tests { assert_eq!(obj.refs.load(Ordering::Acquire), 1); } } + + #[test] + fn note_rtv_and_rt0_ignore_internal_present_calls() { + let handle = 0x7900_2456usize; + let list = 0x7900_2457usize; + let prev = IN_PRESENT.with(|c| c.replace(true)); + unsafe { + note_rtv(handle, 0x1000 as *mut c_void); + note_rt0(list, handle); + } + IN_PRESENT.with(|c| c.set(prev)); + assert_eq!(rtv_resource(handle), None, "internal present RTV must not be recorded"); + assert_eq!(rt0_resource(list), None, "internal present RT0 must not be recorded"); + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2ce33e3ae8..936339b754 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -517,6 +517,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, clone_resources(&unmap_ptrs) }; for r in &to_unmap { + LAST_CONTENT.lock().unwrap().remove(&(r.as_raw() as usize)); super::vram::unmap_superseded(r); } TEXTURES_GEN.fetch_add(1, Ordering::Release); @@ -658,6 +659,7 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { (retired, clone_resources(&unmap_ptrs)) }; for r in &to_unmap { + LAST_CONTENT.lock().unwrap().remove(&(r.as_raw() as usize)); super::vram::unmap_superseded(r); } if retired > 0 { @@ -678,10 +680,12 @@ pub fn forget(res: usize) -> Option { (removed, unsafe { clone_resources(&remap_ptrs) }, state) }; for r in &to_remap { + let key = r.as_raw() as usize; + LAST_CONTENT.lock().unwrap().remove(&key); unsafe { super::vram::remap_if_unmapped(r); // (lazy levels: one the GPU wrote is not uploaded again, so all of it has pages) - if super::vram::level_pages() && TEXTURES.lock().unwrap().by_res.get(&(r.as_raw() as usize)).is_some_and(|e| e.gpu_written) { + if super::vram::level_pages() && TEXTURES.lock().unwrap().by_res.get(&key).is_some_and(|e| e.gpu_written) { super::vram::map_levels(r, None); } } From 8cb8d9321e770f03b6e9526591dbe658566ccf70 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:55:05 +0100 Subject: [PATCH 103/258] D3D12.X: quarantine unpinned sparse tiles and avoid STATE lock in place_buffer Fix two tile-lifetime and pointer-reuse races in sparse.rs (#2457): - Queue unpinned unused tiles from release_if_unused into pending_quarantine instead of pushing straight to free, avoiding queue.Signal inside res_release while ensuring flush_pending_quarantine attaches self.fence and active title-queue fences before reuse (draining in before_execute, take_tile, and flush_parked). - Release STATE across dev_create_reserved_resource in place_buffer so concurrent final Release -> forget_buffer cannot queue a reused COM pointer in FORGOTTEN and later evict the newly created live buffer. Includes regression test gpu_unpinned_unused_tile_waits_in_quarantine_before_free. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/sparse.rs | 120 +++++++++++++++++-- crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 1 + 2 files changed, 114 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 0efae3038a..b71ef897bf 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -236,6 +236,9 @@ struct State { parked: FxHashMap, /// unmapped parked pool tiles awaiting `self.queue` and in-flight title queues before entering `free` quarantined: VecDeque, + /// unpinned unused pool tiles queued from `forget_in` (cannot signal queues under D3D12 release locks) + /// until `flush_pending_quarantine` places them behind GPU fences + pending_quarantine: Vec<(u32, u32)>, /// per-title-queue fences used to mark in-flight GPU work (`note_queue`) queue_fences: FxHashMap, /// placed buffers → the pool tiles they use @@ -559,6 +562,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { pinned: FxHashMap::default(), parked: FxHashMap::default(), quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -608,6 +612,7 @@ impl State { } unsafe fn take_tile(&mut self) -> Option<((u32, u32), bool)> { + self.flush_pending_quarantine(); self.drain_quarantined(); if self.free.is_empty() && self.flush_parked() { self.drain_quarantined(); @@ -1421,17 +1426,44 @@ impl State { } } - /// a pool tile no window maps, none is parked on and no buffer uses goes back to the free list + /// Queue a pool tile that no window maps, none is parked on, and no buffer pins for GPU fence + /// quarantine. Never pushes straight to `free` or signals queues here (called from `forget_in` + /// during D3D12 `Release`); `flush_pending_quarantine` attaches completion fences before reuse. fn release_if_unused(&mut self, tile: (u32, u32)) { if !self.pinned.contains_key(&tile) && !self.mapped.values().any(|e| e.pool == tile) && !self.parked.values().any(|&p| p == tile) && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) + && !self.pending_quarantine.contains(&tile) + && !self.free.contains(&tile) { - self.free.push(tile); + self.pending_quarantine.push(tile); } } + /// Move any `pending_quarantine` tiles (unpinned when a placed buffer was released) into the + /// GPU fence quarantine behind `self.fence` and every known title queue. + unsafe fn flush_pending_quarantine(&mut self) -> bool { + if self.pending_quarantine.is_empty() { + return false; + } + let tiles: Vec<(u32, u32)> = self + .pending_quarantine + .drain(..) + .filter(|tile| { + !self.pinned.contains_key(tile) + && !self.mapped.values().any(|e| e.pool == *tile) + && !self.parked.values().any(|&p| p == *tile) + && !self.quarantined.iter().any(|b| b.tiles.contains(tile)) + }) + .collect(); + if tiles.is_empty() { + return false; + } + self.quarantine_tiles(tiles); + true + } + unsafe fn note_queue(&mut self, q: &ID3D12CommandQueue) -> bool { let key = q.as_raw() as usize; if self.queue_fences.contains_key(&key) { @@ -1527,6 +1559,15 @@ impl State { self.unmap_tiles(&r, b, &ts); } self.signal(); + for tile in self.pending_quarantine.drain(..) { + if !self.pinned.contains_key(&tile) + && !self.mapped.values().any(|e| e.pool == tile) + && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) + && !tiles.contains(&tile) + { + tiles.push(tile); + } + } self.quarantine_tiles(tiles); true } @@ -1572,8 +1613,9 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: s.note_queue(queue); // the title's work sees what was decommitted unmapped, as it was let flushed = s.flush_parked(); + let quarantined = s.flush_pending_quarantine(); let drained = s.drain_quarantined(); - if flushed || drained { + if flushed || quarantined || drained { s.retire_free_pools(); } let t_locked = std::time::Instant::now(); @@ -1662,16 +1704,19 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: /// description): a reserved resource over the window's tiles there, starting at the 64 KiB /// below `va` (returned: its distance from there). pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> { - let mut g = lock_state(); - let s = g.as_mut()?; let start = va & !(TILE - 1); let delta = va - start; let bytes = desc.Width as usize; if bytes == 0 { return None; } - s.window_index(start)?; - s.window_index(va.checked_add(bytes)?.checked_sub(1)?)?; + let last = va.checked_add(bytes)?.checked_sub(1)?; + { + let g = lock_state(); + let s = g.as_ref()?; + s.window_index(start)?; + s.window_index(last)?; + } let mut d = *desc; d.Width = (delta + bytes) as u64; d.Alignment = 0; @@ -1681,10 +1726,14 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D if state & (D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32) != 0 { d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; } + // Create the reserved resource without holding STATE so concurrent final Release -> forget_buffer + // cannot queue a reused COM pointer in FORGOTTEN and later evict this live buffer (#2457). let hr = super::real::dev_create_reserved_resource(this, &d as *const _ as usize, state as usize, 0, riid, ppv); if hr < 0 || ppv.is_null() || (*ppv).is_null() { return None; } + let mut g = lock_state(); + let s = g.as_mut()?; // its tiles: the window's video memory at the same addresses; probe actual OS commitment // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes s.ensure_mapped(start, delta + bytes, |t| query_tile_holes(t)); @@ -1865,6 +1914,7 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -2073,6 +2123,7 @@ mod tests { pinned: FxHashMap::default(), parked: FxHashMap::default(), quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -2170,6 +2221,7 @@ mod tests { pinned: FxHashMap::default(), parked: FxHashMap::default(), quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -2295,6 +2347,7 @@ mod tests { pinned: FxHashMap::default(), parked: FxHashMap::default(), quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), @@ -2576,4 +2629,57 @@ mod tests { println!("early: {n} pages: commit {:.1} ms, decommit {:.1} ms", commit.as_secs_f64() * 1e3, decommit.as_secs_f64() * 1e3); } } + + /// Releasing a placed buffer that was the last pin on an already-unmapped tile must queue the + /// tile in `pending_quarantine` (never directly in `free`) and keep it out of `free` until + /// `flush_pending_quarantine` + active title-queue fences complete (#2457). + #[test] + fn gpu_unpinned_unused_tile_waits_in_quarantine_before_free() { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + unsafe { + let (base, mut s) = test_state_with_reserved(1); + let title_queue: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence"); + let _release_gate = SignalOnDrop(gate.clone(), 1); + assert!(s.note_queue(&title_queue)); + + s.commit_range(base, TILE); + let tile = s.mapped[&base].pool; + const BUF: usize = 0xDEAD_BEE0; + s.pinned.insert(tile, 1); + s.buffers.insert(BUF, vec![tile]); + + // Decommit and flush while still pinned by BUF: tile is unmapped from window, NOT freed. + s.decommit_range(base, TILE); + assert!(s.flush_parked()); + assert!(!s.free.contains(&tile)); + assert!(s.quarantined.is_empty()); + + // Stall title_queue behind `gate` to simulate in-flight GPU work reading BUF. + title_queue.Wait(&gate, 1).expect("wait on gate"); + + // Buffer release unpins tile: must enter pending_quarantine, NOT free. + forget_in(&mut s, BUF); + assert!(!s.pinned.contains_key(&tile)); + assert!(!s.free.contains(&tile), "unpinned tile must not bypass quarantine into free"); + assert_eq!(s.pending_quarantine, vec![tile]); + + // Flushing pending_quarantine attaches title_queue fence; tile stays quarantined until gate signals. + assert!(s.flush_pending_quarantine()); + assert!(s.pending_quarantine.is_empty()); + assert!(!s.drain_quarantined(), "tile must remain quarantined while title queue is blocked"); + assert!(!s.free.contains(&tile)); + + gate.Signal(1).expect("signal gate"); + let start = std::time::Instant::now(); + while !s.drain_quarantined() && start.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(s.free.contains(&tile), "tile should enter free once title queue fence completes"); + + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs index 5c749c6514..557255080c 100644 --- a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -583,6 +583,7 @@ mod tests { pinned: FxHashMap::default(), parked: FxHashMap::default(), quarantined: VecDeque::new(), + pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), buffers: FxHashMap::default(), to_zero: Vec::new(), From ddc8a67e4a68490580f329a775be7b8cf7d52487 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:55:05 +0100 Subject: [PATCH 104/258] D3D12.X: bind console_list heaps before root sig and fix ClearUAV handle Fix three descriptor-heap and view bugs in console_list.rs (#2461): - Call ensure_dispatch_heaps before SetComputeRootSignature so SetDescriptorHeaps never invalidates bound root-signature state (D3D12 #1419). - Bind the shared view heap in ensure_dispatch_heaps unconditionally when present (not only under XCL_HEAP_WINDOWS) so ResourceDescriptorHeap texture/UAV indexing always sees it, and guard zero window VAs before SetComputeRootUnorderedAccessView. - Prefer c.pc_gpu_uav when both CPU and GPU ClearUAV slots are hosted in GLOBAL so inline RAM copies (CopyDescriptorsSimple) never clear with an uninitialized g.pc_gpu_uav handle. Includes unit test clear_uav_prefers_cpu_slot_shared_gpu_handle_for_inline_copies. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/console_list.rs | 47 ++++++++++++++++++++--- 1 file changed, 41 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index e5969e4615..33f5a277be 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -764,7 +764,7 @@ unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Ve if let Some(d) = &dev { super::console_heap::shared_sampler_heap(d); } super::console_heap::global_sampler_heap() }); - let view = crate::gpu::recomp::pso::heap_windows().then(super::console_heap::global_heap).flatten(); + let view = super::console_heap::global_heap(); let (view, sampler) = match dev.as_ref().map(|d| d.as_raw() as usize) { Some(dev_raw) => (heap_on_device(view, dev_raw), heap_on_device(sampler, dev_raw)), None => (view, sampler), @@ -772,6 +772,18 @@ unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Ve ensure_dispatch_heaps_with(list, bound, has_sampler, view, sampler); } +/// Choose the GPU descriptor handle for `ClearUnorderedAccessView*` on a console command list. +/// When both slots are hosted in the shared `GLOBAL` heap, an inline RAM `memcpy` +/// (`CopyDescriptorsSimple`) copies the console descriptor words without initializing `g`'s PC +/// UAV slot, so the live PC UAV lives at `c.pc_gpu_uav` (#2461). +fn clear_uav_gpu_handle(g: &super::console_heap::Slot, c: &super::console_heap::Slot) -> u64 { + if c.shared_srv != 0 && g.shared_srv != 0 && c.pc_gpu_uav != 0 { + c.pc_gpu_uav + } else { + g.pc_gpu_uav + } +} + unsafe fn ensure_uav_clear_heap(list: &ID3D12GraphicsCommandList, bound: &mut Vec, has_sampler: &mut bool) { let mut dev: Option = None; let _ = list.GetDevice(&mut dev); @@ -897,11 +909,12 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let res = q(2) as *mut c_void; let (gpu, cpu) = (super::console_heap::slot(q(0)), super::console_heap::slot(q(1))); match (gpu, cpu, ID3D12Resource::from_raw_borrowed(&res)) { - (Some(g), Some(c), Some(r)) if g.pc_gpu_uav != 0 => { - if g.shared_srv != 0 { + (Some(g), Some(c), Some(r)) if clear_uav_gpu_handle(&g, &c) != 0 => { + let gpu_uav = clear_uav_gpu_handle(&g, &c); + if g.shared_srv != 0 || (c.shared_srv != 0 && gpu_uav == c.pc_gpu_uav) { ensure_uav_clear_heap(&list, &mut bound_heaps, &mut has_sampler_heap); } - let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: g.pc_gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); + let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); if get(1) != 0 { let f = values.map(f32::from_bits); list.ClearUnorderedAccessViewFloat(gh, ch, r, &f, &[]); @@ -973,17 +986,19 @@ pub unsafe fn close(obj: *mut c_void) -> Result { io[crate::gpu::recomp::IO_GROUP_LIMIT] = limit; let io_at = uma_copy(st, bytemuck_u32(&io)).ok_or("UMA: io")?; let res_at = uma_copy(st, &[0u8; 256]).ok_or("UMA: res")?; + // Bind descriptor heaps before the root signature so SetDescriptorHeaps + // never invalidates root signature state (D3D12 #1419 / #2461). + ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap); // the pipeline's own root signature when it has static samplers let own = super::real::pso_root_signature(real).or(((*p).rs != 0).then_some((*p).rs)).map(|r| r as *mut c_void); match own.as_ref().and_then(|r| ID3D12RootSignature::from_raw_borrowed(r)) { Some(r) => list.SetComputeRootSignature(r), None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?), } - ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap); list.SetComputeRootUnorderedAccessView(0, va(io_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); for k in 0..4 { - list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().unwrap_or(uma_va)); + list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().filter(|&v| v != 0).unwrap_or(uma_va)); } let raw = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; @@ -1264,4 +1279,24 @@ mod tests { list.Close().unwrap(); } } + + #[test] + fn clear_uav_prefers_cpu_slot_shared_gpu_handle_for_inline_copies() { + let slot = |shared_srv, pc_gpu_uav| super::super::console_heap::Slot { + at: 0, + k: 0, + index: 0, + pc_srv: 0, + pc_uav: 0x100, + pc_gpu_uav, + shared_srv, + sampler: false, + }; + // Both hosted in GLOBAL (inline CopyDescriptorsSimple): use CPU slot's initialized GPU handle. + assert_eq!(clear_uav_gpu_handle(&slot(0x2000, 0x3000), &slot(0x1000, 0x4000)), 0x4000); + // Unhosted shader-visible heap (no shared_srv): keep g.pc_gpu_uav. + assert_eq!(clear_uav_gpu_handle(&slot(0, 0x3000), &slot(0x1000, 0x4000)), 0x3000); + // CPU slot not in GLOBAL: keep g.pc_gpu_uav. + assert_eq!(clear_uav_gpu_handle(&slot(0x2000, 0x3000), &slot(0, 0)), 0x3000); + } } From 5568d655c6ca7db71f0b11faeeafb150e39e5cd7 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:05:50 +0100 Subject: [PATCH 105/258] D3D12.X: fix make_scaled_args_buffer hang via backing retention and heap UAVs Fix the 0x887a0006 GPU hang / VA 0x0 fault observed in xcl make_scaled_args_buffer (DRED signature 15 15 0 >6 15 0) on AMD RDNA4 and NVIDIA: 1. Tie UMA arena blocks (io/consts/table), indirect argument scratch buffers, and prelude allocators to the actual alloc_pool PC backing allocator instead of the title allocator. Previously real::alloc_reset called console_list::allocator_reset(title_alloc) even when alloc_pool::title_reset put the old backing allocator aside because recordings were still held or executing on the GPU, freeing and overwriting in-flight SCALE_ARGS_HLSL consts (corrupting stride/count) and recycling or dropping in-flight dst scratch buffers. Move console_list::allocator_reset into reset_pc_allocator and alloc_release alongside dispatch_chain::allocator_reset, and resolve the backing allocator in bind::reset and bind::inherit_for_split. 2. Switch make_scaled_args_buffer, guard_dispatch_args, and batched prelude passes to read UMA/sparse windows through the shared descriptor heap raw window UAVs (ResourceDescriptorHeap[MEM_HEAP_BASE + win], calling ensure_view_heap before SetComputeRootSignature) whenever console_heap::window_views_ready() is active, and pass scalar arguments inline via 32-bit root constants (b0) instead of UMA arena root UAVs. This eliminates raw root UAV reads against CreateReservedResource sparse windows (so unmapped NULL tiles safely read as zero instead of faulting) and removes per-draw consts UMA allocations. 3. Guard zero GPU VAs in real::uma_va_of, real::uma_window_buffer, bind::uma_va_in, and reject < 256 addresses in align_root_uav so a root UAV base can never round down to 0x0. 4. Add regression tests for alloc_pool backing retention, zero/sub-256 root UAV rejection, and mapped + unmapped 4 GiB CreateReservedResource tile execution on AMD RDNA4. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 621 +++++++++++++++++++++- crates/xcl/src/hle/d3d12x/console_heap.rs | 8 + crates/xcl/src/hle/d3d12x/real.rs | 21 +- 3 files changed, 623 insertions(+), 27 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 85ecb596fd..c0f16f044b 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -69,7 +69,8 @@ unsafe fn emit_abi_bindings(list: &ID3D12GraphicsCommandList, gfx: bool, rs: &ID fn uma_va_in(u: &crate::gpu::uma::Uma, windows: &[u64], p: usize) -> Option { let k = u.window_of(p)?; - Some(*windows.get(k)? + (p - u.window(k).0) as u64) + let base = *windows.get(k)?; + (base != 0).then(|| base + (p - u.window(k).0) as u64) } #[derive(Default)] @@ -276,12 +277,24 @@ pub(super) fn note_gpu_write(list: *mut c_void) { }); } +/// Resolve the PC backing allocator that actually owns `list`'s recording (`alloc_pool` can swap +/// a title allocator to a new PC allocator while recordings on the old backing are still in flight, +/// so UMA arena blocks and scratch buffers must stay pinned to the backing allocator until +/// `reset_pc_allocator` genuinely resets it). +fn backing_allocator(list: *mut c_void, allocator: usize) -> usize { + if allocator == 0 || !super::alloc_pool::enabled() { + return allocator; + } + super::alloc_pool::recording_backing(list as usize).unwrap_or_else(|| super::alloc_pool::current(allocator)) +} + /// The list was created or reset onto `allocator` with `initial_pso`: the previous /// recording's memory is the previous allocator's until that one is reset, and pipeline /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { + let backing = backing_allocator(list, allocator); let (old, blocks, res_bufs, prelude) = with(list, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); + let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.pso = initial_pso; s.layout = None; @@ -352,11 +365,16 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { /// deferred mid-list split (`to` records into `allocator` with its own fresh UMA arena while /// `from` retains its previously allocated blocks until `allocator` resets). pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { + let backing = if allocator != 0 && super::alloc_pool::enabled() { + super::alloc_pool::current(allocator) + } else { + allocator + }; let (layout, args, layout_gfx, args_gfx, rs_gfx, rs_cs, pso, heaps) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.rs_cs, s.pso, s.heaps) }); let (old, blocks, res_bufs, prelude) = with(to, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); + let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.layout = layout; s.args = args; @@ -1143,6 +1161,168 @@ void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { } "#; +const _: () = assert!(crate::gpu::recomp::MEM_HEAP_BASE == 4); + +/// Descriptor-heap + inline root-constants form of `SCALE_ARGS_HLSL`: reads `src` and `cnt` +/// through the shared descriptor heap's raw window UAVs (`MEM_HEAP_BASE + win`, created with +/// `CreateUnorderedAccessView` on each reserved/committed window buffer so unmapped sparse tiles +/// safely read as zero instead of faulting on a raw root UAV) and passes all scalar parameters +/// inline in `b0` (zero UMA arena allocation). +pub(super) const SCALE_ARGS_HEAP_HLSL: &str = r#"cbuffer Args : register(b0) { + uint count, stride, offset, split, cap, src_slot, src_off, has_cnt, cnt_slot, cnt_off; +}; +RWByteAddressBuffer dst : register(u0); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + if (tid >= count) return; + RWByteAddressBuffer src = ResourceDescriptorHeap[src_slot]; + uint live = count; + if (has_cnt != 0u) { + RWByteAddressBuffer cnt = ResourceDescriptorHeap[cnt_slot]; + live = min(count, cnt.Load(cnt_off)); + } + uint s = src_off + tid * stride, d = tid * stride, m = d + count * stride; + for (uint i = 0u; i < stride; i += 4u) { + uint w = src.Load(s + i); + dst.Store(d + i, w); + dst.Store(m + i, w); + } + uint3 g = src.Load3(s + offset); + uint n = 0u; + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { + n = min(g.x, cap); + n = g.y > cap / n ? cap : n * g.y; + n = g.z > cap / n ? cap : n * g.z; + } + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); +} +"#; + +/// Descriptor-heap + inline root-constants form of `GUARD_ARGS_HLSL`. +pub(super) const GUARD_ARGS_HEAP_HLSL: &str = r#"cbuffer Args : register(b0) { + uint src_slot, src_off, most, lim_off; +}; +RWByteAddressBuffer dst : register(u0); +RWByteAddressBuffer lim : register(u1); +[numthreads(1, 1, 1)] +void main() { + RWByteAddressBuffer src = ResourceDescriptorHeap[src_slot]; + uint3 g = src.Load3(src_off); + uint3 out_g = uint3(0u, 0u, 0u); + uint limit = 0u; + if (g.x != 0u && g.y != 0u && g.z != 0u && all(g <= most)) { + if (g.x <= most / g.y) { + if (g.x * g.y <= most / g.z) { + if (g.x > 65535u && g.y == 1u && g.z <= 65535u) { + uint rows = (g.x - 1u) / 65535u + 1u; + if (rows <= 65535u) { + out_g = uint3(65535u, rows, g.z); + limit = g.x; + } else { + out_g = min(g, 65535u.xxx); + } + } else { + out_g = min(g, 65535u.xxx); + } + } + } + } + dst.Store3(0, out_g); + if (lim_off != 0u) { + lim.Store(lim_off, limit); + } +} +"#; + +/// Descriptor-heap form of `PRELUDE_GUARD_HLSL` (`ResourceDescriptorHeap[MEM_HEAP_BASE + win]`). +pub(super) const PRELUDE_GUARD_HEAP_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + uint total = jobs.Load(0); + if (tid >= total) return; + uint b = 16u + tid * 32u; + uint src_win = jobs.Load(b); + uint src_off = jobs.Load(b + 4u); + uint most = jobs.Load(b + 8u); + uint dst_off = jobs.Load(b + 12u); + uint lim_win = jobs.Load(b + 16u); + uint lim_off = jobs.Load(b + 20u); + RWByteAddressBuffer src = ResourceDescriptorHeap[NonUniformResourceIndex(4u + src_win)]; + uint3 g = src.Load3(src_off); + uint3 out_g = uint3(0u, 0u, 0u); + uint limit = 0u; + if (g.x != 0u && g.y != 0u && g.z != 0u && all(g <= most)) { + if (g.x <= most / g.y) { + if (g.x * g.y <= most / g.z) { + if (g.x > 65535u && g.y == 1u && g.z <= 65535u) { + uint rows = (g.x - 1u) / 65535u + 1u; + if (rows <= 65535u) { + out_g = uint3(65535u, rows, g.z); + limit = g.x; + } else { + out_g = min(g, 65535u.xxx); + } + } else { + out_g = min(g, 65535u.xxx); + } + } + } + } + dst.Store3(dst_off, out_g); + if (lim_off != 0xFFFFFFFFu) { + RWByteAddressBuffer lim = ResourceDescriptorHeap[NonUniformResourceIndex(4u + lim_win)]; + lim.Store(lim_off, limit); + } +} +"#; + +/// Descriptor-heap form of `PRELUDE_SCALE_HLSL` (`ResourceDescriptorHeap[MEM_HEAP_BASE + win]`). +pub(super) const PRELUDE_SCALE_HEAP_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +[numthreads(64, 1, 1)] +void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { + uint b = gid.x * 48u; + uint count = jobs.Load(b); + uint stride = jobs.Load(b + 4u); + uint offset = jobs.Load(b + 8u); + uint split = jobs.Load(b + 12u); + uint cap = jobs.Load(b + 16u); + uint src_win = jobs.Load(b + 20u); + uint src_off = jobs.Load(b + 24u); + uint dst_off = jobs.Load(b + 28u); + uint has_cnt = jobs.Load(b + 32u); + uint cnt_win = jobs.Load(b + 36u); + uint cnt_off = jobs.Load(b + 40u); + RWByteAddressBuffer src = ResourceDescriptorHeap[NonUniformResourceIndex(4u + src_win)]; + uint live = count; + if (has_cnt != 0u) { + RWByteAddressBuffer cnt = ResourceDescriptorHeap[NonUniformResourceIndex(4u + cnt_win)]; + live = min(count, cnt.Load(cnt_off)); + } + for (uint tid = gtid.x; tid < count; tid += 64u) { + uint s = src_off + tid * stride; + uint d = dst_off + tid * stride; + uint m = d + count * stride; + for (uint i = 0u; i < stride; i += 4u) { + uint w = src.Load(s + i); + dst.Store(d + i, w); + dst.Store(m + i, w); + } + uint3 g = src.Load3(s + offset); + uint n = 0u; + if (tid < live && g.x != 0u && g.y != 0u && g.z != 0u) { + n = min(g.x, cap); + n = g.y > cap / n ? cap : n * g.y; + n = g.z > cap / n ? cap : n * g.z; + } + dst.Store3(d + offset, uint3(n, 1u, 1u)); + dst.Store3(m + offset, uint3(n * split, 1u, 1u)); + } +} +"#; + /// `XCL_INDIRECT_PRELUDE=0`: run indirect argument clamp/scale passes inline instead of hoisting /// them into a batched prelude command list submitted right before the recording. fn indirect_prelude_on() -> bool { @@ -1150,20 +1330,46 @@ fn indirect_prelude_on() -> bool { *ON.get_or_init(|| std::env::var("XCL_INDIRECT_PRELUDE").map_or(true, |v| v.trim() != "0")) } -/// Map a 4-byte-aligned UMA host address + byte span to `(window_index, byte_offset)` within -/// the 4 UMA windows (`u2..u5`), ensuring `byte_offset + span` fits in 32-bit HLSL byte offsets. +/// Top byte bound of a raw window UAV created by `runner::raw_window_uav`. +const RAW_WINDOW_UAV_MAX: usize = (1usize << 32) - 32; + +/// Map a 4-byte-aligned UMA host address + byte span to `(heap_slot, byte_offset)` within the +/// shared descriptor heap's window UAVs (`MEM_HEAP_BASE + win`), respecting `raw_window_uav`'s +/// 32-byte top margin on 4 GiB windows. +fn uma_heap_slot_off(u: &crate::gpu::uma::Uma, p: usize, span: usize) -> Option<(u32, u32)> { + if p % 4 != 0 || span == 0 { + return None; + } + let k = u.window_of(p)?; + if k >= crate::gpu::uma::MAX_HEAP_WINDOWS { + return None; + } + let (base, size) = u.window(k); + let off = p.checked_sub(base)?; + let end = off.checked_add(span)?; + if end > size.min(RAW_WINDOW_UAV_MAX) { + return None; + } + Some((crate::gpu::recomp::MEM_HEAP_BASE + k as u32, off as u32)) +} + +/// Map a 4-byte-aligned UMA host address + byte span to `(window_index, byte_offset)` for +/// prelude jobs (up to `MAX_HEAP_WINDOWS` when shared heap window views are active, else 4). fn uma_win_off(u: &crate::gpu::uma::Uma, p: usize, span: usize) -> Option<(u32, u32)> { if p % 4 != 0 || span == 0 { return None; } let k = u.window_of(p)?; - if k >= 4 { + let heap_mode = super::console_heap::window_views_ready(); + let max_wins = if heap_mode { crate::gpu::uma::MAX_HEAP_WINDOWS } else { 4 }; + if k >= max_wins { return None; } let (base, size) = u.window(k); let off = p.checked_sub(base)?; let end = off.checked_add(span)?; - if end > size || end > u32::MAX as usize { + let limit = if heap_mode { size.min(RAW_WINDOW_UAV_MAX) } else { size.min(u32::MAX as usize) }; + if end > limit { return None; } Some((k as u32, off as u32)) @@ -1241,6 +1447,68 @@ unsafe fn prelude_scale_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignat prelude_pipeline(dev, PRELUDE_SCALE_HLSL, PRELUDE_SCALE_DRED_LABEL, &CACHE) } +unsafe fn prelude_heap_root_signature(dev: &ID3D12Device) -> Result { + let params: [D3D12_ROOT_PARAMETER1; 2] = std::array::from_fn(|reg| D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: reg as u32, + RegisterSpace: 0, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: 0, + pStaticSamplers: std::ptr::null(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + let mut blob: Option = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None).map_err(|e| format!("prelude heap root signature serialize: {e}"))?; + let blob = blob.ok_or("prelude heap root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("prelude heap root signature create: {e}")) +} + +unsafe fn prelude_heap_pipeline(dev: &ID3D12Device, hlsl: &str, label: &str, cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let key = dev.as_raw() as usize; + if let Some(pair) = cache.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let rs = prelude_heap_root_signature(dev)?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("{label} heap pso create: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from(label)); + super::dred::label_text(pso.as_raw() as usize, || label.to_string()); + cache.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + +unsafe fn prelude_guard_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_heap_pipeline(dev, PRELUDE_GUARD_HEAP_HLSL, PRELUDE_GUARD_DRED_LABEL, &CACHE) +} + +unsafe fn prelude_scale_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_heap_pipeline(dev, PRELUDE_SCALE_HEAP_HLSL, PRELUDE_SCALE_DRED_LABEL, &CACHE) +} + /// Allocate `bytes` in `State::prelude_scratch` (disjoint from inline ping-pong scratch so the /// prelude leaves these buffers in `INDIRECT_ARGUMENT` for the entire main segment). unsafe fn alloc_prelude_scratch(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64, usize), String> { @@ -1388,11 +1656,18 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { } }; + let shared_heap = super::console_heap::window_views_ready().then(super::console_heap::global_heap).flatten(); + if let Some(ref heap) = shared_heap { + list.SetDescriptorHeaps(&[Some(heap.clone())]); + } + // 2. Emit batched guard dispatches grouped by prelude scratch buffer. if !guards.is_empty() { - let (rs, pso) = prelude_guard_pipeline(&dev)?; + let (rs, pso) = if shared_heap.is_some() { prelude_guard_heap_pipeline(&dev)? } else { prelude_guard_pipeline(&dev)? }; list.SetComputeRootSignature(&rs); - bind_windows(&list); + if shared_heap.is_none() { + bind_windows(&list); + } list.SetPipelineState(&pso); for (buf_idx, buf) in bufs.iter().enumerate() { let batch: Vec<&PreludeGuardJob> = guards.iter().filter(|j| j.buf_idx == buf_idx).collect(); @@ -1416,9 +1691,11 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { // 3. Emit batched scale dispatches grouped by prelude scratch buffer. if !scales.is_empty() { - let (rs, pso) = prelude_scale_pipeline(&dev)?; + let (rs, pso) = if shared_heap.is_some() { prelude_scale_heap_pipeline(&dev)? } else { prelude_scale_pipeline(&dev)? }; list.SetComputeRootSignature(&rs); - bind_windows(&list); + if shared_heap.is_none() { + bind_windows(&list); + } list.SetPipelineState(&pso); for (buf_idx, buf) in bufs.iter().enumerate() { let batch: Vec<&PreludeScaleJob> = scales.iter().filter(|j| j.buf_idx == buf_idx).collect(); @@ -1514,8 +1791,8 @@ fn most_groups() -> u32 { /// require >= 16-byte alignment; UMA window buffers are 64 KiB-aligned so `va & !255` stays in /// the same buffer and sparse tile). fn align_root_uav(va: u64) -> Result<(u64, u32), String> { - if va % 4 != 0 { - return Err(format!("indirect buffer address {va:#x} is not 4-byte aligned")); + if va < 256 || va % 4 != 0 { + return Err(format!("invalid indirect buffer address {va:#x}")); } Ok((va & !255, (va & 255) as u32)) } @@ -1544,6 +1821,11 @@ unsafe fn guard_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSigna args_pipeline(dev, GUARD_ARGS_HLSL, GUARD_ARGS_DRED_LABEL, true, &CACHE) } +unsafe fn guard_indirect_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + heap_args_pipeline(dev, GUARD_ARGS_HEAP_HLSL, GUARD_ARGS_DRED_LABEL, 4, &[0, 1], &CACHE) +} + /// `XCL_INDIRECT_GUARD=0`: indirect dispatches run the groups memory holds, whatever they are. fn indirect_guard() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -1584,11 +1866,34 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis } } } + let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, 256)?; + let lim_off = (crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32; + let dst_va = dst.GetGPUVirtualAddress() + dst_off; + if super::console_heap::window_views_ready() { + if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, 12) { + let (rs, pso) = guard_indirect_heap_pipeline(&dev)?; + let consts = [src_slot, src_off, most_groups(), lim_off]; + super::list_x::ensure_view_heap(this); + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, consts.len() as u32, consts.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.SetComputeRootUnorderedAccessView(2, dispatch_io_va); + list.Dispatch(1, 1, 1); + emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + with(this, |s| { + s.scratch[slot].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + return Ok((dst, dst_off)); + } + } let (rs, pso) = guard_indirect_pipeline(&dev)?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; let (src_base, src_off) = align_root_uav(src_va)?; - let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, 256)?; - let lim_off = (crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32; let consts = [src_off, most_groups(), 0, lim_off]; let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); @@ -1599,7 +1904,7 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis list.SetPipelineState(&pso); list.SetComputeRootUnorderedAccessView(0, consts_va); list.SetComputeRootUnorderedAccessView(1, src_base); - list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress() + dst_off); + list.SetComputeRootUnorderedAccessView(2, dst_va); list.SetComputeRootUnorderedAccessView(3, dispatch_io_va); list.Dispatch(1, 1, 1); // Transition scratch to INDIRECT_ARGUMENT and flush the `IO_GROUP_LIMIT` store in `dispatch_io_va`. @@ -1617,8 +1922,82 @@ unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSigna args_pipeline(dev, SCALE_ARGS_HLSL, SCALE_ARGS_DRED_LABEL, true, &CACHE) } +unsafe fn scale_indirect_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + heap_args_pipeline(dev, SCALE_ARGS_HEAP_HLSL, SCALE_ARGS_DRED_LABEL, 10, &[0], &CACHE) +} + type ArgsPipelines = Mutex>>; +/// Root signature for the descriptor-heap + inline root-constants internal argument passes: +/// param 0 = `num_consts` inline 32-bit constants at `b0`, followed by root UAVs for committed +/// scratch/io outputs, with `CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` for safe raw window UAV reads. +unsafe fn heap_args_root_signature(dev: &ID3D12Device, num_consts: u32, uav_regs: &[u32]) -> Result { + let mut params = Vec::with_capacity(1 + uav_regs.len()); + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, + RegisterSpace: 0, + Num32BitValues: num_consts, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + for ® in uav_regs { + params.push(D3D12_ROOT_PARAMETER1 { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER1_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: reg, + RegisterSpace: 0, + Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }); + } + let desc = D3D12_VERSIONED_ROOT_SIGNATURE_DESC { + Version: D3D_ROOT_SIGNATURE_VERSION_1_1, + Anonymous: D3D12_VERSIONED_ROOT_SIGNATURE_DESC_0 { + Desc_1_1: D3D12_ROOT_SIGNATURE_DESC1 { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + NumStaticSamplers: 0, + pStaticSamplers: std::ptr::null(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, + }, + }, + }; + let mut blob: Option = None; + D3D12SerializeVersionedRootSignature(&desc, &mut blob, None).map_err(|e| format!("heap args root signature serialize: {e}"))?; + let blob = blob.ok_or("heap args root signature blob")?; + dev.CreateRootSignature(0, std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize())) + .map_err(|e| format!("heap args root signature create: {e}")) +} + +unsafe fn heap_args_pipeline(dev: &ID3D12Device, hlsl: &str, label: &str, num_consts: u32, uav_regs: &[u32], cache: &'static ArgsPipelines) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + let key = dev.as_raw() as usize; + if let Some(pair) = cache.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { + return Ok(pair); + } + let dxil = crate::gpu::recomp::dxc::compile_cached(hlsl, "main", "cs_6_6")?.0; + let rs = heap_args_root_signature(dev, num_consts, uav_regs)?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const c_void, BytecodeLength: dxil.len() }, + ..Default::default() + }; + let res_pso: Result = dev.CreateComputePipelineState(&cdesc); + std::mem::ManuallyDrop::drop(&mut cdesc.pRootSignature); + let pso = res_pso.map_err(|e| format!("{label} heap pso create: {e}"))?; + let _ = pso.SetName(&windows::core::HSTRING::from(label)); + super::dred::label_text(pso.as_raw() as usize, || label.to_string()); + cache.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, (rs.clone(), pso.clone())); + Ok((rs, pso)) +} + /// Minimal compute root signature for XCL's internal argument-rewrite passes: only the root UAVs /// the shader declares (`u0, u2, u3`, plus `u4` when `with_count` is set) and no heap flags, so /// every root parameter is unconditionally bound before Dispatch. @@ -1808,6 +2187,35 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman } } } + let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, commands.saturating_mul(2))?; + let dst_va = dst.GetGPUVirtualAddress() + dst_off; + if super::console_heap::window_views_ready() { + if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, commands as usize) { + let cnt_loc = match count { + Some(p) => uma_heap_slot_off(u, p, 4).map(|(sl, off)| (1u32, sl, off)), + None => Some((0u32, src_slot, 0u32)), + }; + if let Some((has_cnt, cnt_slot, cnt_off)) = cnt_loc { + let (rs, pso) = scale_indirect_heap_pipeline(&dev)?; + let consts = [max, stride, mesh_offset, split, cap, src_slot, src_off, has_cnt, cnt_slot, cnt_off]; + super::list_x::ensure_view_heap(this); + // the title's writes of the arguments before this (`fresh_indirect_arguments`) + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, consts.len() as u32, consts.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + with(this, |s| { + s.scratch[slot].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + return Ok((dst, dst_off)); + } + } + } let (rs, pso) = scale_indirect_pipeline(&dev)?; let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; let (src_base, src_off) = align_root_uav(src_va)?; @@ -1821,7 +2229,6 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman } None => None, }; - let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, commands.saturating_mul(2))?; let consts = [max, stride, mesh_offset, split, cap, src_off, 0, count_bound.is_some() as u32, count_bound.map_or(0, |(_, off)| off)]; let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); @@ -1835,7 +2242,7 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman list.SetPipelineState(&pso); list.SetComputeRootUnorderedAccessView(0, consts_va); list.SetComputeRootUnorderedAccessView(1, src_base); - list.SetComputeRootUnorderedAccessView(2, dst.GetGPUVirtualAddress() + dst_off); + list.SetComputeRootUnorderedAccessView(2, dst_va); list.SetComputeRootUnorderedAccessView(3, cnt_base); list.Dispatch(max.div_ceil(64), 1, 1); emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); @@ -4260,6 +4667,8 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) assert!(align_root_uav(0x1_0000_0001).is_err()); assert!(align_root_uav(0x1_0000_0002).is_err()); assert!(align_root_uav(0x1_0000_0003).is_err()); + assert!(align_root_uav(0).is_err(), "zero VA must never pass as a root UAV base"); + assert!(align_root_uav(0xFC).is_err(), "sub-256 VA must never round down to 0x0"); } #[test] @@ -4675,4 +5084,180 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) let _ = alloc; } } + + /// When `alloc_pool` maps a list to a PC backing allocator distinct from the title allocator, + /// `bind::reset` must pin the recording's UMA blocks to the PC backing allocator so resetting + /// the title allocator (or a newer swapped backing) cannot free in-flight `io`/`consts` early. + #[test] + fn bind_reset_pins_resources_to_alloc_pool_backing() { + let list = 0x7E57_9001usize as *mut c_void; + let title_alloc = 0x7E57_9010usize; + let backing_a = 0x7E57_9020usize; + let backing_b = 0x7E57_9030usize; + super::super::alloc_pool::created_on(list as usize, backing_a, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + reset(list, title_alloc, 0); + assert_eq!(with(list, |s| s.allocator), backing_a); + with(list, |s| s.uma.push(0xDEAD_1000)); + // Next recording on a different backing retires the previous UMA block under `backing_a`. + super::super::alloc_pool::created_on(list as usize, backing_b, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + reset(list, title_alloc, 0); + assert_eq!(with(list, |s| s.allocator), backing_b); + assert!(console_list::take_pending_for_test(title_alloc).is_empty(), "must not attach to title allocator"); + assert!(console_list::take_pending_for_test(backing_b).is_empty(), "must not attach to newer backing"); + assert_eq!(console_list::take_pending_for_test(backing_a), vec![0xDEAD_1000]); + forget(list); + super::super::alloc_pool::forget_list(list as usize); + } + + /// `SCALE_ARGS_HEAP_HLSL` and `GUARD_ARGS_HEAP_HLSL` read from a real 4 GiB reserved buffer's + /// raw UAV in `ResourceDescriptorHeap`: a mapped tile produces exact scaled/folded outputs, + /// while an unmapped NULL tile reads safely as zero with no GPU page fault. + #[test] + fn gpu_heap_args_pipelines_handle_mapped_and_unmapped_reserved_tiles() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + const TILE: u64 = 0x1_0000; + const GIB: u64 = 1 << 30; + unsafe { + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let dev = dev.unwrap(); + let res_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4 * GIB, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut win: Option = None; + if dev.CreateReservedResource(&res_desc, D3D12_RESOURCE_STATE_COMMON, None, &mut win).is_err() { + crate::gpu::recomp::runner::skip_test("no 4 GiB reserved buffer"); + return; + } + let win = win.unwrap(); + let mut tile_heap: Option = None; + dev.CreateHeap( + &D3D12_HEAP_DESC { + SizeInBytes: TILE, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, + }, + &mut tile_heap, + ) + .unwrap(); + let tile_heap = tile_heap.unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + // Map ONLY tile 0; tile 1 (offset 0x1_0000) stays intentionally UNMAPPED (NULL tile). + let coord = D3D12_TILED_RESOURCE_COORDINATE { X: 0, ..Default::default() }; + let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, ..Default::default() }; + let flag = D3D12_TILE_RANGE_FLAG_NONE; + let zero = 0u32; + let one = 1u32; + queue.UpdateTileMappings(&win, 1, Some(&coord), Some(®ion), &tile_heap, 1, Some(&flag), Some(&zero), Some(&one), D3D12_TILE_MAPPING_FLAG_NONE); + + let dh: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: crate::gpu::recomp::MEM_HEAP_BASE + 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }) + .unwrap(); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let slot = crate::gpu::recomp::MEM_HEAP_BASE; + let cpu = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dh.GetCPUDescriptorHandleForHeapStart().ptr + slot as usize * inc }; + dev.CreateUnorderedAccessView(&win, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(4 * GIB)), cpu); + + let make_buf = |bytes: u64, heap_type: D3D12_HEAP_TYPE, uav: bool, state: D3D12_RESOURCE_STATES| -> ID3D12Resource { + let d = 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: if uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: heap_type, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, state, None, &mut r).unwrap(); + r.unwrap() + }; + let up = make_buf(256, D3D12_HEAP_TYPE_UPLOAD, false, D3D12_RESOURCE_STATE_GENERIC_READ); + let dst = make_buf(1024, D3D12_HEAP_TYPE_DEFAULT, true, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + let rb = make_buf(1024, D3D12_HEAP_TYPE_READBACK, false, D3D12_RESOURCE_STATE_COPY_DEST); + + let mut p = std::ptr::null_mut(); + up.Map(0, None, Some(&mut p)).unwrap(); + std::ptr::write_bytes(p as *mut u8, 0, 256); + let u32s = std::slice::from_raw_parts_mut(p as *mut u32, 64); + // Offset 0x00: guard input (115_200, 1, 1); Offset 0x40: scale input [0x77, 15, 2, 1] + u32s[0..3].copy_from_slice(&[115_200, 1, 1]); + u32s[16..20].copy_from_slice(&[0x77, 15, 2, 1]); + up.Unmap(0, None); + + let (scale_rs, scale_pso) = scale_indirect_heap_pipeline(&dev).expect("scale_indirect_heap_pipeline"); + let (guard_rs, guard_pso) = guard_indirect_heap_pipeline(&dev).expect("guard_indirect_heap_pipeline"); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + + list.CopyBufferRegion(&win, 0, &up, 0, 256); + emit_transition(&list, &win, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetDescriptorHeaps(&[Some(dh.clone())]); + + let dst_va = dst.GetGPUVirtualAddress(); + // 1. Guard on mapped tile 0 (offset 0) -> dst[0x000] + lim at dst[0x020] + let g_mapped = [slot, 0u32, MOST_GROUPS, 32u32]; + list.SetComputeRootSignature(&guard_rs); + list.SetPipelineState(&guard_pso); + list.SetComputeRoot32BitConstants(0, 4, g_mapped.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.SetComputeRootUnorderedAccessView(2, dst_va); + list.Dispatch(1, 1, 1); + // 2. Guard on UNMAPPED tile 1 (offset 0x1_0000) -> dst[0x100] (must read 0 without fault) + let g_unmapped = [slot, TILE as u32, MOST_GROUPS, 32u32]; + list.SetComputeRoot32BitConstants(0, 4, g_unmapped.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va + 0x100); + list.SetComputeRootUnorderedAccessView(2, dst_va + 0x100); + list.Dispatch(1, 1, 1); + // 3. Scale on mapped tile 0 (offset 0x40, cap 10, split 2) -> dst[0x200] + let s_mapped = [1u32, 16, 4, 2, 10, slot, 0x40, 0, slot, 0]; + list.SetComputeRootSignature(&scale_rs); + list.SetPipelineState(&scale_pso); + list.SetComputeRoot32BitConstants(0, 10, s_mapped.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va + 0x200); + list.Dispatch(1, 1, 1); + // 4. Scale on UNMAPPED tile 1 (offset 0x1_0000, count from UNMAPPED tile 1) -> dst[0x300] + let s_unmapped = [1u32, 16, 4, 2, 10, slot, TILE as u32, 1, slot, TILE as u32 + 16]; + list.SetComputeRoot32BitConstants(0, 10, s_unmapped.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va + 0x300); + list.Dispatch(1, 1, 1); + + emit_transition(&list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE); + list.CopyBufferRegion(&rb, 0, &dst, 0, 1024); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, &dev, None, 10_000).unwrap(); + + rb.Map(0, None, Some(&mut p)).unwrap(); + let out = std::slice::from_raw_parts(p as *const u32, 256); + assert_eq!(&out[0..3], &[65_535, 2, 1], "mapped guard fold"); + assert_eq!(out[8], 115_200, "mapped guard IO_GROUP_LIMIT"); + assert_eq!(&out[0x100 / 4..0x100 / 4 + 3], &[0, 0, 0], "unmapped guard reads zero safely"); + assert_eq!(&out[0x200 / 4..0x200 / 4 + 8], &[0x77, 10, 1, 1, 0x77, 20, 1, 1], "mapped scale compute+mesh"); + assert_eq!(&out[0x300 / 4..0x300 / 4 + 8], &[0, 0, 1, 1, 0, 0, 1, 1], "unmapped scale reads zero safely"); + rb.Unmap(0, None); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 592787c64a..879b90fb71 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -220,6 +220,7 @@ unsafe fn null_views(dev: &ID3D12Device, cpu: u64, inc: u32) { } static WINDOW_VIEWS_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +static WINDOW_VIEWS_READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Whether the memory windows could not be put in the shared heap (`set_window_views`): /// translated shaders then switch over root UAVs (`pso::heap_windows`). @@ -227,6 +228,12 @@ pub fn window_views_failed() -> bool { WINDOW_VIEWS_FAILED.load(std::sync::atomic::Ordering::Relaxed) } +/// Whether the memory windows' raw UAV descriptors are published at `MEM_HEAP_BASE + k` in +/// the shared shader-visible descriptor heap (`set_window_views` succeeded). +pub fn window_views_ready() -> bool { + WINDOW_VIEWS_READY.load(std::sync::atomic::Ordering::Acquire) +} + /// The memory windows' buffers `(resource, bytes)` as raw UAVs at `MEM_HEAP_BASE + k` of the /// shared heap, made now if need be (`Options::heap_windows`: shaders take window k from there). /// Active windows (`bytes > 0`) in wider layouts (8 / 16) must all have a valid buffer; unused @@ -262,6 +269,7 @@ unsafe fn set_window_views_checked(dev: &ID3D12Device, windows: &[(usize, usize) device.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&crate::gpu::recomp::runner::raw_window_uav(0)), at); true }; + WINDOW_VIEWS_READY.store(ok, std::sync::atomic::Ordering::Release); if !ok { WINDOW_VIEWS_FAILED.store(true, std::sync::atomic::Ordering::Relaxed); crate::xlog_warn!("memory windows: could not bind {count} window(s) (64-bit atomics on heap views: {atomics64}) in the shared descriptor heap"); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 3378516fe6..bfdca8982b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -209,14 +209,16 @@ pub(super) fn uma_window_buffer(p: usize, len: usize) -> Option<(usize, u64)> { if p - base + len > size { return None; } - Some((UMA_BUFFER.read().ok()?.get(k)?.0, (p - base) as u64)) + let buf = UMA_BUFFER.read().ok()?.get(k)?.0; + (buf != 0).then(|| (buf, (p - base) as u64)) } /// GPU virtual address of a UMA address (None: not in UMA or not open on the GPU). pub fn uma_va_of(p: usize) -> Option { let u = crate::gpu::uma::get()?; let k = u.window_of(p)?; - Some(*uma_window_vas().get(k)? + (p - u.window(k).0) as u64) + let base = *uma_window_vas().get(k)?; + (base != 0).then(|| base + (p - u.window(k).0) as u64) } /// What the start-up check of the coherent UMA windows found (`check_uma_import`): empty – not @@ -7652,6 +7654,7 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let n = f(this); if n == 0 { dispatch_chain::allocator_reset(this as usize); + super::console_list::allocator_reset(this); super::alloc_pool::forget(this as usize); super::list_x::on_allocator_release(this as usize); } @@ -7663,21 +7666,21 @@ pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); let hr = f(raw); - if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } + if hr >= 0 { + // Only now is the GPU done with recordings backed by `raw` (`alloc_pool` may have put + // an older backing allocator aside during a title `Reset` while its submits still run). + dispatch_chain::allocator_reset(raw as usize); + super::console_list::allocator_reset(raw); + } hr } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { // (lists may still hold recordings on it that the title submits again: `alloc_pool`) - let hr = match super::alloc_pool::title_reset(this) { + match super::alloc_pool::title_reset(this) { Some(hr) => hr, None => reset_pc_allocator(this), - }; - if hr >= 0 { - // the GPU is done with what lists recorded from this allocator used - super::console_list::allocator_reset(this); } - hr } // --------------------------------------------------------------------------------------- From 71c14d1e2c2196710449e54c791f8fcbf325d76f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:20:32 +0100 Subject: [PATCH 106/258] D3D12.X: clear dispatch_chain SHARED scratch and rotate DRED marks on list resets Fix #2459 and #2462 on wrapped and console command list lifecycle paths: 1. #2459 (list_x.rs, console_list.rs, real/dispatch_chain.rs): Call dispatch_chain::list_reset on list_x::on_create, list_x::on_release, list_x::clear_segment_state, list_x::try_split_for_wait (fresh segment branch), and console_list::cl_reset / cl_release so recycled COM pointers, spare split segments, and reset console lists cannot inherit stale SHARED split-compute scratch weak refs from prior recordings. 2. #2462 (list_x.rs): Call dred::reset (and dred::mark_pipeline when an initial/bound PSO is present) on list_x::reset_pc, list_x::kickoff_x, and list_x::record_deferred, which invoke PC Reset directly and previously bypassed real::cl_reset. Prevents unbounded dred::MARKS growth under XCL_DRED=1 and stale Frame-1 pipeline labels on wrapped lists. 3. Add unit tests verifying SHARED scratch cleanup across on_create, clear_segment_state, on_release, console_list::cl_reset, and console_list::cl_release. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/console_list.rs | 33 +++++++++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 34 +++++++++++++++++++ .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 10 ++++++ 3 files changed, 76 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 33f5a277be..b73e882ff6 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -433,6 +433,7 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { if left == 0 { if let Some(st) = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&obj)) { free_uma(&st.uma); + super::real::dispatch_chain::list_reset(st.pc); let release: unsafe extern "system" fn(usize) -> u32 = std::mem::transmute(pc_vtable_call(st.pc, 2)); release(st.pc); } @@ -477,7 +478,11 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, ps } with_list(obj, |st| new_chunk(obj, st)); let f: unsafe extern "system" fn(usize, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(pc_vtable_call(pc, 10)); - f(pc, allocator, pc_pso(pso)) + let hr = f(pc, allocator, pc_pso(pso)); + if hr >= 0 { + super::real::dispatch_chain::list_reset(pc); + } + hr } unsafe extern "system" fn cl_dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { @@ -1299,4 +1304,30 @@ mod tests { // CPU slot not in GLOBAL: keep g.pc_gpu_uav. assert_eq!(clear_uav_gpu_handle(&slot(0x2000, 0x3000), &slot(0, 0)), 0x3000); } + + #[test] + fn cl_reset_and_cl_release_clear_dispatch_chain_shared_scratch() { + unsafe extern "system" fn fake_release(_this: usize) -> u32 { 0 } + unsafe extern "system" fn fake_reset(_this: usize, _alloc: *mut c_void, _pso: *mut c_void) -> HRESULT { S_OK } + let mut vt = [0usize; 16]; + vt[2] = fake_release as usize; + vt[10] = fake_reset as usize; + #[repr(C)] + struct FakePc { vt: *const usize } + let pc_obj = Box::new(FakePc { vt: vt.as_ptr() }); + let pc_ptr = &*pc_obj as *const FakePc as *mut c_void; + let pc_key = pc_ptr as usize; + let alloc = 0x7E57_C110usize as *mut c_void; + unsafe { + let cl = create_with_allocator(pc_ptr, alloc); + super::super::real::dispatch_chain::seed_shared_for_test(pc_key, alloc as usize); + assert!(super::super::real::dispatch_chain::has_shared_for_test(pc_key)); + assert_eq!(cl_reset(cl, alloc, std::ptr::null_mut()), S_OK); + assert!(!super::super::real::dispatch_chain::has_shared_for_test(pc_key), "cl_reset must clear dispatch_chain SHARED"); + + super::super::real::dispatch_chain::seed_shared_for_test(pc_key, alloc as usize); + assert_eq!(cl_release(cl), 0); + assert!(!super::super::real::dispatch_chain::has_shared_for_test(pc_key), "cl_release must clear dispatch_chain SHARED"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index f2e685ed34..1a5014e20a 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -898,6 +898,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C let key = list as usize; // (of a list that was here before and whose release was not seen: the GPU may still use it) release_copy_scratch(key); + real::dispatch_chain::list_reset(key); let old = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); @@ -937,6 +938,7 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C pub(super) fn on_release(list: usize) { super::alloc_pool::forget_list(list); release_copy_scratch(list); + real::dispatch_chain::list_reset(list); super::title_textures::list_reset(list); super::format_alias::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); @@ -961,6 +963,7 @@ pub(super) fn on_release(list: usize) { /// Clear per-recording sync/write tracking on a split segment moved into `title_list`'s spare pool. pub(super) fn clear_segment_state(list: usize) { + real::dispatch_chain::list_reset(list); super::title_textures::list_reset(list); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { s.occlusion = Occlusion::default(); @@ -2830,6 +2833,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { continue; } reset_copy_scratch(seg); + super::dred::reset(seg); if !heaps.is_empty() { pc::(seg, 28)(seg, heaps.len() as u32, heaps.as_ptr()); } @@ -2958,6 +2962,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ }; // the next segment is a recording of its own (reset or made here, not through `cl_reset`) + real::dispatch_chain::list_reset(next_pc as usize); super::dred::reset(next_pc); if init_pso != 0 { super::dred::mark_pipeline(next_pc, bound_pso, init_pso); @@ -3611,6 +3616,11 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } reset_copy_scratch(target); + // `KickoffX` calls PC `Reset` directly (bypassing `real::cl_reset`), so rotate DRED markers here. + super::dred::reset(target); + if bound_pso != 0 { + super::dred::mark_pipeline(target, bound_pso, init_pso); + } let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(target as usize))).map(|s| s.bindings.clone()); if let Some(b) = bindings { restore_bindings(target, &b, ty); @@ -4466,6 +4476,11 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 } reset_copy_scratch(this); + // `reset_pc` calls PC `Reset` directly (bypassing `real::cl_reset`), so rotate DRED markers here. + super::dred::reset(this); + if pso != 0 { + super::dred::mark_pipeline(this, pso, resolved); + } super::format_alias::list_reset(this as usize); reset_own_alloc(this); let is_bundle = { @@ -8048,4 +8063,23 @@ mod tests { assert_eq!(thread_dims_to_groups([1920, 1080, 3], [8, 8, 1]), Some([240, 135, 3])); assert_eq!(thread_dims_to_groups([1, 1, 1], [0, 0, 0]), Some([1, 1, 1])); } + + #[test] + fn dispatch_chain_shared_scratch_clears_on_create_release_and_segment_clear() { + let list = 0x7E57_D150usize; + let alloc = 0x7E57_D160usize; + // 1. on_create clears any stale SHARED entry at a recycled COM pointer. + real::dispatch_chain::seed_shared_for_test(list, alloc); + assert!(real::dispatch_chain::has_shared_for_test(list)); + unsafe { on_create(list as *mut c_void, alloc, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + assert!(!real::dispatch_chain::has_shared_for_test(list)); + // 2. clear_segment_state clears SHARED when a split segment returns to spares. + real::dispatch_chain::seed_shared_for_test(list, alloc); + clear_segment_state(list); + assert!(!real::dispatch_chain::has_shared_for_test(list)); + // 3. on_release clears SHARED when the list is released. + real::dispatch_chain::seed_shared_for_test(list, alloc); + on_release(list); + assert!(!real::dispatch_chain::has_shared_for_test(list)); + } } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 1128543c90..0cbd9ce9c1 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -200,6 +200,16 @@ pub(in crate::hle::d3d12x) fn list_reset(list: usize) { SHARED.lock().unwrap().remove(&list); } +#[cfg(test)] +pub(in crate::hle::d3d12x) fn seed_shared_for_test(list: usize, allocator: usize) { + SHARED.lock().unwrap().insert(list, (allocator, std::sync::Weak::new())); +} + +#[cfg(test)] +pub(in crate::hle::d3d12x) fn has_shared_for_test(list: usize) -> bool { + SHARED.lock().unwrap().contains_key(&list) +} + /// `to` records right after `from` on the same allocator: its chains go on in `from`'s scratch. pub(in crate::hle::d3d12x) fn list_follows(from: usize, to: usize) { let mut shared = SHARED.lock().unwrap(); From 372a433db50ca34a3a8118c99239a338541ae002 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:24:22 +0100 Subject: [PATCH 107/258] HLE: fix xg_xs vtable length, invalid-offset sentinel, and Z modes Fix three xg_xs ABI mismatches found against console XGTextureAddressComputer: - Extend XGTextureAddressComputer vtable to 13 slots (0..=12), wiring slot 12 to is_tiled_resource (returning 1 for 64KB_UNDEFINED_SWIZZLE / tiled-resource bit 27, 0 otherwise) so slot-12 callers never read past the vtable. - Return u64::MAX (not 0) from GetMipLevelOffsetBytes and GetTexelElementOffsetBytes on invalid plane/mip/slice arguments so errors are distinct from offset 0. - Accept all 7 GFX10 depth/stencil Z swizzle modes (4, 8, 12, 16, 20, 24, 28) in depth-buffer validation (returning E_NOTIMPL for unmodelled Z modes instead of E_INVALIDARG, while still rejecting non-Z modes with E_INVALIDARG). Includes unit tests covering the 13-slot vtable, u64::MAX sentinels, and Z-mode validation. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/xg.rs | 70 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 65 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index 0eec7dc16e..c7464b049c 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -108,6 +108,15 @@ pub struct Texture { pub empty: bool, /// D3D12_RESOURCE_DIMENSION dimension: u32, + /// tiled resource (D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE or console tiled flag bit 27) + tiled_resource: bool, +} + +/// Whether `mode` is one of the 7 GFX10 depth/stencil Z swizzle modes accepted by +/// `XGValidateDepthStencilSwizzleMode` (`4KB_Z`, `64KB_Z`, `4KB_Z_T`, `VAR_Z`, `4KB_Z_X`, +/// `64KB_Z_X`, `VAR_Z_X`). +pub fn is_depth_stencil_swizzle_mode(mode: u32) -> bool { + matches!(mode, 4 | 8 | 12 | 16 | 20 | 24 | 28) } /// (log2 bytes per element, pixels per element side) of a DXGI format; None for the 96-bit @@ -187,7 +196,7 @@ impl Texture { // is left empty. Render target + depth flags: a render target in a Z mode, unless the // format has a stencil let depth_buffer = ds && mips == 1 && (planar || !rt); - if depth_buffer && mode != 24 { + if depth_buffer && !is_depth_stencil_swizzle_mode(mode) { return Err(E_INVALIDARG); } let depth_format = planar || matches!(format, 39 | 40 | 53 | 55); @@ -232,7 +241,8 @@ impl Texture { Plane { usage, offset: at, kind } }) .collect(); - Ok(Texture { planes, main: main_at, mips, empty, dimension: dim }) + let tiled_resource = layout == 2 || (flags & (1 << 27)) != 0; + Ok(Texture { planes, main: main_at, mips, empty, dimension: dim, tiled_resource }) } /// A 3D texture: one plane of texels, 4KB_S unless the layout names a mode or it is a UAV @@ -265,7 +275,8 @@ impl Texture { let chain = Chain::new_3d(l, width as u32, height, depth, side, mips); let first_tail = chain.levels.iter().position(|m| m.tail.is_some()).unwrap_or(chain.levels.len()); let s = Surface { chain, mode, bpe: 1 << e, side, width: width as u32, height, array: 1, depth, first_tail }; - Ok(Texture { planes: vec![Plane { usage: 1, offset: 0, kind: PlaneKind::Surface(s) }], main: 0, mips, empty: false, dimension: 4 }) + let tiled_resource = layout == 2 || (flags & (1 << 27)) != 0; + Ok(Texture { planes: vec![Plane { usage: 1, offset: 0, kind: PlaneKind::Surface(s) }], main: 0, mips, empty: false, dimension: 4, tiled_resource }) } pub fn size(&self) -> u64 { @@ -359,6 +370,7 @@ impl Surface { match mode { 0 | 1 | 2 | 5 | 6 | 9 | 10 | 17 | 18 | 21 | 22 | 25 | 26 | 27 => {} 24 if e <= 3 && !bc => {} + 4 | 8 | 12 | 16 | 20 | 28 if e <= 3 && !bc => return Err(E_NOTIMPL), 28 | 31 => return Err(E_NOTIMPL), _ => return Err(E_INVALIDARG), } @@ -500,6 +512,8 @@ fn vtbl() -> &'static [usize] { let (stub, _) = crate::stubs::make_stub_info("xg_xs.dll", &format!("XGTextureAddressComputer::#{i}"), E_NOTIMPL as u32 as u64); v.push(stub); } + // Slot 12: IsTiledResource (returns bool/u32 from the resource's tiled-resource flag). + v.push(is_tiled_resource as usize); Box::leak(v.into_boxed_slice()) }) } @@ -589,7 +603,7 @@ unsafe extern "system" fn get_alignment(p: *mut c_void) -> u64 { unsafe extern "system" fn get_mip_offset(p: *mut c_void, plane: u32, mip: u32) -> u64 { match tex(p).plane_surface(plane) { Some((s, at)) if (mip as usize) < s.chain.levels.len() => at + s.mip_offset(mip as usize), - _ => 0, + _ => u64::MAX, } } @@ -599,10 +613,14 @@ unsafe extern "system" fn get_texel_offset(p: *mut c_void, plane: u32, mip: u32, } match tex(p).plane_surface(plane) { Some((s, at)) if (mip as usize) < s.chain.levels.len() && slice < s.slices(mip as usize).0 => at + s.element_offset(mip as usize, x as usize, y as usize, slice as usize), - _ => 0, + _ => u64::MAX, } } +unsafe extern "system" fn is_tiled_resource(p: *mut c_void) -> u32 { + u32::from(tex(p).tiled_resource) +} + unsafe extern "system" fn not_implemented(_p: *mut c_void) -> HRESULT { E_NOTIMPL } @@ -783,4 +801,46 @@ mod tests { assert_eq!((t.size(), t.alignment()), (rgb10a2.size(), rgb10a2.alignment())); } } + + #[test] + fn computer_vtable_has_13_slots_and_invalid_offsets_return_u64_max() { + assert_eq!(vtbl().len(), 13, "XGTextureAddressComputer exposes slots 0..=12"); + let d = desc(64, 64, 1, 2, 28, 0x109); + let mut comp = std::ptr::null_mut(); + assert_eq!(unsafe { XGCreateTextureComputer(d.as_ptr(), &mut comp) }, S_OK); + assert!(!comp.is_null()); + unsafe { + assert_eq!(get_mip_offset(comp, 99, 0), u64::MAX); + assert_eq!(get_mip_offset(comp, 0, 99), u64::MAX); + assert_eq!(get_texel_offset(comp, 99, 0, 0, 0, 0, 0, std::ptr::null_mut()), u64::MAX); + assert_eq!(get_texel_offset(comp, 0, 99, 0, 0, 0, 0, std::ptr::null_mut()), u64::MAX); + assert_eq!(get_texel_offset(comp, 0, 0, 0, 0, 99, 0, std::ptr::null_mut()), u64::MAX); + assert_eq!(is_tiled_resource(comp), 0); + assert_eq!(release(comp), 0); + } + let tiled = desc(64, 64, 1, 1, 28, 2); + let mut comp_tiled = std::ptr::null_mut(); + assert_eq!(unsafe { XGCreateTextureComputer(tiled.as_ptr(), &mut comp_tiled) }, S_OK); + unsafe { + assert_eq!(is_tiled_resource(comp_tiled), 1); + assert_eq!(release(comp_tiled), 0); + } + } + + #[test] + fn depth_stencil_swizzle_modes_distinguish_valid_z_modes_from_invalid() { + for z in [4u32, 8, 12, 16, 20, 24, 28] { + assert!(is_depth_stencil_swizzle_mode(z), "Z mode {z} must be valid"); + } + assert!(!is_depth_stencil_swizzle_mode(25)); + // Valid but unmodelled Z modes return E_NOTIMPL on depth buffers, while non-Z modes return E_INVALIDARG. + for z in [4u32, 8, 12, 16, 20, 28] { + let mut d = desc(256, 256, 1, 1, 40, 0x100 | z); + d[0x30..0x34].copy_from_slice(&2u32.to_le_bytes()); // ALLOW_DEPTH_STENCIL + assert_eq!(Texture::new(&d).err(), Some(E_NOTIMPL), "Z mode {z} should return E_NOTIMPL"); + } + let mut bad = desc(256, 256, 1, 1, 40, 0x100 | 25); + bad[0x30..0x34].copy_from_slice(&2u32.to_le_bytes()); + assert_eq!(Texture::new(&bad).err(), Some(E_INVALIDARG), "non-Z mode 25 must fail with E_INVALIDARG"); + } } From 032c661ae53376f39fb84ef9509fe76bb017e526 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:24:22 +0100 Subject: [PATCH 108/258] GPU: optimize GFX10 2D detile and tile with block slabs and contiguous runs Accelerate GFX10 2D texture detiling and tiling in Layout::detile/tile and Chain::detile_level/tile_level: - Precompute run_elems per Layout: the largest power-of-two horizontal element run inside block_w whose in-block byte offsets advance contiguously by +e with zero interference from oy/oz/hx/hy/hz (respecting base_xor at runtime), copying 16-32B chunks instead of individual 1-4B elements. - Traverse one tiled block (by, bx) at a time so each 4 KiB / 64 KiB block stays L1-resident and complete blocks bypass per-element bounds checks and block arithmetic, with safe element-wise fallback on truncated sources. Includes regression test tile_level_matches_element_by_element_and_exploits_contiguous_runs across all 14 modes, 5 element sizes, 10 pipe configs, mip tails, and base_xor. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/tiling.rs | 336 ++++++++++++++++++++++++++++------- 1 file changed, 267 insertions(+), 69 deletions(-) diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index b9fa1abdd3..0ac818b320 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -66,6 +66,9 @@ pub struct Layout { /// XORed into every in-block byte offset: the pipe / bank swizzle a T# base address carries /// in its low bits (`base & (block_bytes - 1)`), 0 otherwise pub base_xor: usize, + /// largest power-of-two horizontal element run inside a block whose byte offsets advance + /// contiguously by `+e` with zero interference from `oy`/`oz`/`hx`/`hy`/`hz` + run_elems: usize, ox: &'static [u32], oy: &'static [u32], oz: &'static [u32], @@ -108,7 +111,7 @@ impl Layout { if mode == 0 { let bw = 256 >> elem_log2; let ox: &'static [u32] = (0..bw as u32).map(|x| x << elem_log2).collect::>().leak(); - return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: &[0], oz: &[0], hx: &[0], hy: &[0], hz: &[0] }); + return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, run_elems: bw, ox, oy: &[0], oz: &[0], hx: &[0], hy: &[0], hz: &[0] }); } let blk = block_log2(mode)?; let bits = pattern_bits(PATTERNS, mode, elem_log2, cfg)?; @@ -161,6 +164,29 @@ impl Layout { let used = bits[..blk as usize].iter().fold(0u32, |m, &b| m | ((b >> shift) & 0xFFFF) as u32) >> l.min(16); table(1 << (32 - used.leading_zeros()), shift, l) }; + let ox = table(bw, 0, 0); + let oy = table(bh, 16, 0); + let oz = table(bd, 32, 0); + let hx = high(wl, 0); + let hy = high(hl, 16); + let hz = high(dl, 32); + let other_bits = oy.iter().chain(oz).chain(hx).chain(hy).chain(hz).fold(0u32, |a, &b| a | b); + let mut run_elems = 1usize; + while run_elems * 2 <= bw { + let next = run_elems * 2; + let mask = ((next << elem_log2) - 1) as u32; + if (other_bits & mask) != 0 { + break; + } + let ok = (0..bw).all(|x| { + let base = ox[x & !(next - 1)]; + (base & mask) == 0 && ox[x] == base + (((x & (next - 1)) << elem_log2) as u32) + }); + if !ok { + break; + } + run_elems = next; + } Layout { mode, elem_log2, @@ -169,12 +195,13 @@ impl Layout { block_d: bd, block_bytes: 1 << blk, base_xor: 0, - ox: table(bw, 0, 0), - oy: table(bh, 16, 0), - oz: table(bd, 32, 0), - hx: high(wl, 0), - hy: high(hl, 16), - hz: high(dl, 32), + run_elems, + ox, + oy, + oz, + hx, + hy, + hz, } } @@ -204,34 +231,215 @@ impl Layout { block * self.block_bytes + (xor as usize ^ self.base_xor) } + /// Effective horizontal contiguous run width in elements, respecting any `base_xor` low bits. + #[inline] + fn effective_run(&self) -> usize { + if self.base_xor == 0 { + self.run_elems + } else { + let lim = (1usize << self.base_xor.trailing_zeros()) >> self.elem_log2; + self.run_elems.min(lim).max(1) + } + } + /// tiled → linear rows (`w << elem_log2` bytes each); bytes past the end of `src` read as 0 pub fn detile(&self, src: &[u8], w: usize, h: usize) -> Vec { let e = 1usize << self.elem_log2; let mut out = vec![0u8; w * h * e]; - for y in 0..h { - for x in 0..w { - let o = self.offset(x, y, w); - if let Some(s) = src.get(o..o + e) { - let d = (y * w + x) * e; - out[d..d + e].copy_from_slice(s); - } - } - } + self.detile_2d(src, &mut out, 0, w, h, w, (0, 0), 0); out } /// linear rows → tiled (the inverse of `detile`) pub fn tile(&self, linear: &[u8], w: usize, h: usize) -> Vec { - let e = 1usize << self.elem_log2; let mut out = vec![0u8; self.size(w, h)]; - for y in 0..h { - for x in 0..w { - let o = self.offset(x, y, w); - let s = (y * w + x) * e; - out[o..o + e].copy_from_slice(&linear[s..s + e]); + self.tile_2d(&mut out, linear, 0, w, h, w, (0, 0), 0); + out + } + + /// Block-slab 2D detile with contiguous horizontal run copies (`src` tiled -> `out` linear). + /// Iterating one tiled block `(by, bx)` at a time keeps each 4 KiB / 64 KiB block hot in L1 + /// cache and eliminates per-element block arithmetic and bounds checks on complete blocks. + #[allow(clippy::too_many_arguments)] + fn detile_2d(&self, src: &[u8], out: &mut [u8], base_off: usize, w: usize, h: usize, pitch: usize, origin: (usize, usize), slice: usize) { + if w == 0 || h == 0 { + return; + } + let e = 1usize << self.elem_log2; + if self.mode == 0 && self.base_xor == 0 && origin == (0, 0) { + let row = w * e; + let pitch_blocks = pitch.div_ceil(self.block_w); + for y in 0..h { + let o = base_off + (y / self.block_h) * pitch_blocks * self.block_bytes + self.oy[y % self.block_h] as usize; + let n = src.len().saturating_sub(o).min(row) / e * e; + if n > 0 { + out[y * row..][..n].copy_from_slice(&src[o..o + n]); + } + } + return; + } + let pitch_blocks = pitch.div_ceil(self.block_w); + let z = self.oz[slice % self.block_d] ^ self.hz[(slice / self.block_d) % self.hz.len()]; + let run = self.effective_run(); + let run_bytes = run * e; + let row_bytes = w * e; + let (ox0, oy0) = origin; + let bx_start = ox0 / self.block_w; + let bx_end = (ox0 + w - 1) / self.block_w; + let by_start = oy0 / self.block_h; + let by_end = (oy0 + h - 1) / self.block_h; + + for by in by_start..=by_end { + let y_lo = (by * self.block_h).max(oy0) - oy0; + let y_hi = ((by + 1) * self.block_h).min(oy0 + h) - oy0; + let hy = self.hy[by % self.hy.len()] ^ z; + let row_blocks = by * pitch_blocks; + for bx in bx_start..=bx_end { + let x_lo = (bx * self.block_w).max(ox0) - ox0; + let x_hi = ((bx + 1) * self.block_w).min(ox0 + w) - ox0; + let block_base = base_off + (row_blocks + bx) * self.block_bytes; + let b_xor = self.hx[bx % self.hx.len()] ^ hy ^ self.base_xor as u32; + let xi_lo = x_lo + ox0 - bx * self.block_w; + let xi_hi = x_hi + ox0 - bx * self.block_w; + if block_base.checked_add(self.block_bytes).is_some_and(|end| end <= src.len()) { + let blk = &src[block_base..block_base + self.block_bytes]; + if run > 1 { + let aligned_lo = (xi_lo + run - 1) & !(run - 1); + let aligned_hi = xi_hi & !(run - 1); + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + let mut xi = xi_lo; + let mut x = x_lo; + let pre = aligned_lo.min(xi_hi); + while xi < pre { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + e].copy_from_slice(&blk[o..o + e]); + xi += 1; + x += 1; + } + while xi < aligned_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + run_bytes].copy_from_slice(&blk[o..o + run_bytes]); + xi += run; + x += run; + } + while xi < xi_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + e].copy_from_slice(&blk[o..o + e]); + xi += 1; + x += 1; + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = (x_off ^ y_xor) as usize; + let d = (x_lo + dx) * e; + dst_row[d..d + e].copy_from_slice(&blk[o..o + e]); + } + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = block_base + (x_off ^ y_xor) as usize; + if let Some(s) = src.get(o..o + e) { + let d = (x_lo + dx) * e; + dst_row[d..d + e].copy_from_slice(s); + } + } + } + } + } + } + } + + /// Block-slab 2D tile with contiguous horizontal run copies (`linear` -> `dst` tiled). + #[allow(clippy::too_many_arguments)] + fn tile_2d(&self, dst: &mut [u8], linear: &[u8], base_off: usize, w: usize, h: usize, pitch: usize, origin: (usize, usize), slice: usize) { + if w == 0 || h == 0 { + return; + } + let e = 1usize << self.elem_log2; + if self.mode == 0 && self.base_xor == 0 && origin == (0, 0) { + let row = w * e; + let pitch_blocks = pitch.div_ceil(self.block_w); + for y in 0..h { + let o = base_off + (y / self.block_h) * pitch_blocks * self.block_bytes + self.oy[y % self.block_h] as usize; + dst[o..o + row].copy_from_slice(&linear[y * row..][..row]); + } + return; + } + let pitch_blocks = pitch.div_ceil(self.block_w); + let z = self.oz[slice % self.block_d] ^ self.hz[(slice / self.block_d) % self.hz.len()]; + let run = self.effective_run(); + let run_bytes = run * e; + let row_bytes = w * e; + let (ox0, oy0) = origin; + let bx_start = ox0 / self.block_w; + let bx_end = (ox0 + w - 1) / self.block_w; + let by_start = oy0 / self.block_h; + let by_end = (oy0 + h - 1) / self.block_h; + + for by in by_start..=by_end { + let y_lo = (by * self.block_h).max(oy0) - oy0; + let y_hi = ((by + 1) * self.block_h).min(oy0 + h) - oy0; + let hy = self.hy[by % self.hy.len()] ^ z; + let row_blocks = by * pitch_blocks; + for bx in bx_start..=bx_end { + let x_lo = (bx * self.block_w).max(ox0) - ox0; + let x_hi = ((bx + 1) * self.block_w).min(ox0 + w) - ox0; + let block_base = base_off + (row_blocks + bx) * self.block_bytes; + let b_xor = self.hx[bx % self.hx.len()] ^ hy ^ self.base_xor as u32; + let xi_lo = x_lo + ox0 - bx * self.block_w; + let xi_hi = x_hi + ox0 - bx * self.block_w; + let blk = &mut dst[block_base..block_base + self.block_bytes]; + if run > 1 { + let aligned_lo = (xi_lo + run - 1) & !(run - 1); + let aligned_hi = xi_hi & !(run - 1); + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let src_row = &linear[y * row_bytes..(y + 1) * row_bytes]; + let mut xi = xi_lo; + let mut x = x_lo; + let pre = aligned_lo.min(xi_hi); + while xi < pre { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + e].copy_from_slice(&src_row[x * e..x * e + e]); + xi += 1; + x += 1; + } + while xi < aligned_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + run_bytes].copy_from_slice(&src_row[x * e..x * e + run_bytes]); + xi += run; + x += run; + } + while xi < xi_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + e].copy_from_slice(&src_row[x * e..x * e + e]); + xi += 1; + x += 1; + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let src_row = &linear[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = (x_off ^ y_xor) as usize; + let s = (x_lo + dx) * e; + blk[o..o + e].copy_from_slice(&src_row[s..s + e]); + } + } + } } } - out } } @@ -378,6 +586,7 @@ impl Chain { /// element (x, y) of level `l` in array slice `slice` (from the slice's start): the slice /// is z of the 2D patterns – the XOR modes take pipe bits from it + #[cfg(test)] fn element_at(&self, l: &MipLevel, x: usize, y: usize, slice: usize) -> usize { l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch) } @@ -425,59 +634,16 @@ impl Chain { /// bytes past the end of `src` read as 0 pub fn detile_level(&self, src: &[u8], i: usize, slice: usize) -> Vec { let l = self.levels[i]; - let t = &self.layout; - let e = 1usize << t.elem_log2; + let e = 1usize << self.layout.elem_log2; let mut out = vec![0u8; l.width * l.height * e]; - if t.mode == 0 && t.base_xor == 0 && l.origin == (0, 0) { - // linear: a row's elements are contiguous, so it is copied whole (the elements that - // are all in `src`, as below) – a video plane of 3840×2160 is 2160 copies, not 8 M - let row = l.width * e; - for y in 0..l.height { - let o = self.element_at(&l, 0, y, slice); - let n = src.len().saturating_sub(o).min(row) / e * e; - if n > 0 { - out[y * row..][..n].copy_from_slice(&src[o..o + n]); - } - } - return out; - } - // `element_at` (`Layout::offset_z`) split: what depends on x alone once per level, what - // depends on y (and the slice) once per row – per element only two lookups and an XOR. - // Element by element it was most of a retail game's render thread while it streamed - // textures the CPU writes. - let hi = |tab: &[u32], c: usize, b: usize| tab[(c / b) % tab.len()]; - let pitch_blocks = l.pitch.div_ceil(t.block_w); - let columns: Vec<(usize, u32)> = (0..l.width) - .map(|x| { - let x = x + l.origin.0; - (x / t.block_w, t.ox[x % t.block_w] ^ hi(&t.hx, x, t.block_w)) - }) - .collect(); - let z = t.oz[slice % t.block_d] ^ hi(&t.hz, slice, t.block_d); - for (y, row) in out.chunks_exact_mut(l.width * e).enumerate() { - let y = y + l.origin.1; - let row_blocks = (y / t.block_h) * pitch_blocks; - let yz = t.oy[y % t.block_h] ^ hi(&t.hy, y, t.block_h) ^ z; - for (&(block_x, x), dst) in columns.iter().zip(row.chunks_exact_mut(e)) { - let o = l.offset + (row_blocks + block_x) * t.block_bytes + ((x ^ yz) as usize ^ t.base_xor); - if let Some(s) = src.get(o..o + e) { - dst.copy_from_slice(s); - } - } - } + self.layout.detile_2d(src, &mut out, l.offset, l.width, l.height, l.pitch, l.origin, slice); out } /// linear rows of level `i` → its place in array slice `slice` (`dst`, `slice_bytes` long) pub fn tile_level(&self, dst: &mut [u8], i: usize, slice: usize, linear: &[u8]) { let l = self.levels[i]; - let e = 1usize << self.layout.elem_log2; - for y in 0..l.height { - for x in 0..l.width { - let o = self.element_at(&l, x, y, slice); - dst[o..o + e].copy_from_slice(&linear[(y * l.width + x) * e..][..e]); - } - } + self.layout.tile_2d(dst, linear, l.offset, l.width, l.height, l.pitch, l.origin, slice); } } @@ -872,5 +1038,37 @@ mod tests { assert!(!g.contains_key(&(false, 9, 5, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }))); assert!(!g.contains_key(&(true, 10, 2, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }))); } + + #[test] + fn tile_level_matches_element_by_element_and_exploits_contiguous_runs() { + // Standard 2D modes with 1..4B elements must detect multi-element contiguous runs. + assert!(Layout::new(5, 0, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap().run_elems >= 4); + assert!(Layout::new(10, 2, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap().run_elems >= 2); + for mode in MODES { + for e in 0..5u32 { + for cfg in configs() { + let mut lay = Layout::new(mode, e, cfg).unwrap(); + lay.base_xor = (lay.block_bytes / 2) & !((1 << e) - 1); + let c = Chain::new(lay, 77, 45, 1, 7); + let es = 1usize << e; + for (k, l) in c.levels.iter().enumerate() { + let lin: Vec = (0..l.width * l.height * es).map(|i| ((i * 53 + k * 17) % 251) as u8 | 1).collect(); + for slice in [0usize, 3] { + let mut got = vec![0u8; c.slice_bytes]; + let mut want = vec![0u8; c.slice_bytes]; + c.tile_level(&mut got, k, slice, &lin); + for y in 0..l.height { + for x in 0..l.width { + let o = c.element_at(l, x, y, slice); + want[o..o + es].copy_from_slice(&lin[(y * l.width + x) * es..][..es]); + } + } + assert!(got == want, "tile_level mismatch: mode {mode} e {e} {cfg:?} level {k} slice {slice}"); + } + } + } + } + } + } } From c3ed184772f041bcfe5bfdf4464e5d8e99f34e13 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:24:22 +0100 Subject: [PATCH 109/258] D3D12.X: hash only written pages of title textures (#2484) Port per-page content hashing (#2484 by ChAlanA) onto the indexed dirty_and_pending + parallel hash_and_detile_all upload pipeline: - Track per-page hashes (PageHashes) in LAST_CONTENT and propagate overlapping dirty pages from refresh_once into Upload. - For previously uploaded textures with known dirty pages, upload_all checks changed_pages_since_last_upload first (reading and hashing only those deduplicated clamped 4 KiB pages outside LAST_CONTENT) and skips unchanged textures without reading or detiling the full resource. - For first/pending uploads, hash_and_detile_all populates PageHashes directly from the single already-read title_bytes buffer, preserving #2470 lazy-mip retry and #2460 invalidations plus invalidating LAST_CONTENT in recheck_gpu_view_sources. Includes all 5 per-page dirty/unaligned/remap/dedup unit tests. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 455 +++++++++++++++++--- 1 file changed, 400 insertions(+), 55 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 936339b754..4017b90c91 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -38,8 +38,15 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address its bytes are read from, layout, states) of an upload -type Upload = (usize, usize, Arc, Vec); +/// Upload parameters for a pending or CPU-dirtied texture. +struct Upload { + device: usize, + src: usize, + tex: Arc, + states: Vec, + dirty_pages: Option>, + page_size: usize, +} struct Entry { device: usize, @@ -167,9 +174,9 @@ impl Table { } /// Collect active textures that are pending or overlap any sorted dirty page in `dirty`, - /// clearing `pending` on returned entries and returning `(res_list, pending_cleared)`. - fn dirty_and_pending(&mut self, dirty: &[usize], page: usize) -> (Vec, usize) { - let mut hits: Vec = Vec::with_capacity(self.pending_res.len() + 16); + /// clearing `pending` on returned entries and returning `((res, was_pending) list, pending_cleared)`. + fn dirty_and_pending(&mut self, dirty: &[usize], page: usize) -> (Vec<(usize, bool)>, usize) { + let mut hits: Vec<(usize, bool)> = Vec::with_capacity(self.pending_res.len() + 16); let mut cleared = 0usize; for res in std::mem::take(&mut self.pending_res) { if let Some(e) = self.by_res.get_mut(&res) { @@ -177,7 +184,7 @@ impl Table { e.pending = false; cleared += 1; } - hits.push(res); + hits.push((res, true)); } } if !dirty.is_empty() && page > 0 { @@ -194,19 +201,20 @@ impl Table { let q_lo = lo.saturating_sub(SMALL_SRC_MAX); for (&(_, res), &end) in self.by_src_small.range((q_lo, 0)..(hi, 0)) { if end > lo { - hits.push(res); + hits.push((res, false)); } } } for (&res, &(src, end)) in &self.by_src_large { let idx = dirty.partition_point(|&p| p.saturating_add(page) <= src); if dirty.get(idx).is_some_and(|&p| p < end) { - hits.push(res); + hits.push((res, false)); } } } - hits.sort_unstable(); - hits.dedup(); + // Keep `was_pending == true` when a resource was both pending and dirty-hit. + hits.sort_unstable_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(&a.1))); + hits.dedup_by_key(|x| x.0); (hits, cleared) } @@ -547,7 +555,7 @@ fn recheck_gpu_view_sources() { if SEEN.swap(gen, Ordering::AcqRel) == gen { return; } - let mut changed = false; + let mut remapped = Vec::new(); // (the shadowed textures too: one comes back when the texture over it goes) let mut g = TEXTURES.lock().unwrap(); let t = &mut *g; @@ -555,7 +563,7 @@ fn recheck_gpu_view_sources() { for (&res, e) in t.by_res.iter_mut() { let old_src = e.src; if recheck_source(e) { - changed = true; + remapped.push(res); reindex.push((res, old_src, e.src, e.tex.size() as usize, e.gpu_written, e.pending)); } } @@ -563,11 +571,17 @@ fn recheck_gpu_view_sources() { t.unindex_active(res, old_src); t.index_active(res, new_src, size, gpu_written, pending); } - for e in t.shadowed.values_mut() { - changed |= recheck_source(e); + for (&res, e) in t.shadowed.iter_mut() { + if recheck_source(e) { + remapped.push(res); + } } drop(g); - if changed { + if !remapped.is_empty() { + let mut last = LAST_CONTENT.lock().unwrap(); + for res in remapped { + last.remove(&res); + } TEXTURES_GEN.fetch_add(1, Ordering::Release); } } @@ -947,18 +961,39 @@ unsafe fn refresh_once(queue: *mut c_void) { } // textures made since the last submit and those with a written page; a reference each // while they are uploaded + let page_size = (page as usize).max(0x1000); let todo: Vec<(ID3D12Resource, Upload)> = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); let mut t = TEXTURES.lock().unwrap(); - let (hits, cleared) = t.dirty_and_pending(&dirty, page as usize); + let (hits, cleared) = t.dirty_and_pending(&dirty, page_size); if cleared > 0 { PENDING.fetch_sub(cleared, Ordering::Relaxed); } hits.into_iter() - .filter_map(|res| { + .filter_map(|(res, was_pending)| { let e = t.by_res.get(&res)?; + let dirty_pages = if was_pending { + None + } else { + let end = e.src.saturating_add(e.tex.size() as usize); + let lo = dirty.partition_point(|&p| p.saturating_add(page_size) <= e.src); + let hi = lo + dirty[lo..].partition_point(|&p| p < end); + (lo < hi).then(|| dirty[lo..hi].to_vec()) + }; let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p).map(|r| { + ( + r.clone(), + Upload { + device: e.device, + src: e.src, + tex: Arc::clone(&e.tex), + states: e.states.clone(), + dirty_pages, + page_size, + }, + ) + }) }) .collect() }); @@ -966,8 +1001,15 @@ unsafe fn refresh_once(queue: *mut c_void) { upload_all(todo); } -/// texture → `content_hash` of its memory at its last upload -static LAST_CONTENT: Mutex> = Mutex::new(BTreeMap::new()); +struct PageHashes { + src: usize, + size: usize, + page_size: usize, + hashes: Vec, +} + +/// texture → per-page `content_hash` of its memory at its last upload +static LAST_CONTENT: Mutex> = Mutex::new(BTreeMap::new()); static UNCHANGED: AtomicU64 = AtomicU64::new(0); /// `XCL_TEXTURE_SKIP_UNCHANGED=0` uploads a texture whenever its pages were written, as before. @@ -976,10 +1018,110 @@ fn unchanged_skip() -> bool { *ON.get_or_init(|| std::env::var("XCL_TEXTURE_SKIP_UNCHANGED").map_or(true, |v| v.trim() != "0")) } -/// Whether texture `res` was last uploaded from memory with hash `h`; `h` is remembered as its -/// content from here on (the caller uploads it when this is false). -fn same_as_last_upload(res: usize, h: u64) -> bool { - LAST_CONTENT.lock().unwrap().insert(res, h) == Some(h) +/// Aligned base of the first page covering `[src, src + size)` and the number of `page_size` pages. +fn page_count(src: usize, size: usize, page_size: usize) -> (usize, usize) { + if size == 0 || page_size == 0 { + return (src, 0); + } + let first_page = src - (src % page_size); + let end = src.saturating_add(size); + let count = end.saturating_sub(first_page).div_ceil(page_size); + (first_page, count) +} + +/// Page indices of `[src, src + size)` whose bytes changed since `res`'s last upload, or `None` +/// if all checked pages match. When `dirty_pages` is `Some` and `(src, size, page_size)` matches +/// the recorded `PageHashes`, only those dirty pages are read and hashed (outside `LAST_CONTENT`). +fn changed_pages_with<'a, F>( + res: usize, + src: usize, + size: usize, + dirty_pages: Option<&[usize]>, + page_size: usize, + mut read_range: F, +) -> Option> +where + F: FnMut(usize, usize) -> std::borrow::Cow<'a, [u8]>, +{ + let (first_page, count) = page_count(src, size, page_size); + let end = src.saturating_add(size); + + if let Some(pages) = dirty_pages { + let matched = { + let g = LAST_CONTENT.lock().unwrap(); + g.get(&res).is_some_and(|e| e.src == src && e.size == size && e.page_size == page_size && e.hashes.len() == count) + }; + if matched { + if count == 0 { + return None; + } + let mut indices: Vec = pages + .iter() + .filter_map(|&p| { + let pg = p - (p % page_size); + if pg < first_page { + return None; + } + let k = (pg - first_page) / page_size; + (k < count).then_some(k) + }) + .collect(); + indices.sort_unstable(); + indices.dedup(); + + let mut computed = Vec::with_capacity(indices.len()); + for k in indices { + let pg = first_page + k * page_size; + let lo = pg.max(src); + let hi = pg.saturating_add(page_size).min(end); + let bytes = read_range(lo, hi - lo); + computed.push((k, content_hash(&bytes))); + } + + let mut g = LAST_CONTENT.lock().unwrap(); + if let Some(entry) = g.get_mut(&res).filter(|e| e.src == src && e.size == size && e.page_size == page_size && e.hashes.len() == count) { + let mut changed = Vec::new(); + for (k, h) in computed { + if entry.hashes[k] != h { + entry.hashes[k] = h; + changed.push(k); + } + } + return if changed.is_empty() { None } else { Some(changed) }; + } + } + } + + let mut hashes = Vec::with_capacity(count); + if count > 0 { + let bytes = read_range(src, size); + for k in 0..count { + let pg = first_page + k * page_size; + let lo = pg.max(src); + let hi = pg.saturating_add(page_size).min(end); + hashes.push(content_hash(&bytes[lo - src..hi - src])); + } + } + + let mut g = LAST_CONTENT.lock().unwrap(); + if let Some(entry) = g.get_mut(&res).filter(|e| e.src == src && e.size == size && e.page_size == page_size && e.hashes.len() == count) { + let mut changed = Vec::new(); + for (k, h) in hashes.into_iter().enumerate() { + if entry.hashes[k] != h { + entry.hashes[k] = h; + changed.push(k); + } + } + if changed.is_empty() { None } else { Some(changed) } + } else { + g.insert(res, PageHashes { src, size, page_size, hashes }); + Some((0..count).collect()) + } +} + +/// Per-page change check backed by `title_bytes` for `upload_all`. +unsafe fn changed_pages_since_last_upload(res: usize, src: usize, size: usize, dirty_pages: Option<&[usize]>, page_size: usize) -> Option> { + changed_pages_with(res, src, size, dirty_pages, page_size, |at, len| title_bytes(at, len)) } /// A 64-bit hash of `b` for "the same bytes as before" (four lanes of multiply-rotate over @@ -1080,12 +1222,12 @@ unsafe fn seed_stream_recheck(todo: &[(ID3D12Resource, Upload)], watched: &[(usi return; } let mut seeded = Vec::new(); - for (r, (_, src, tex, _)) in todo { - let size = tex.size() as usize; - if size == 0 || range_is_fully_watched(*src, size, watched) { + for (r, u) in todo { + let size = u.tex.size() as usize; + if size == 0 || range_is_fully_watched(u.src, size, watched) { continue; } - let fp = sample_fingerprint(*src, size); + let fp = sample_fingerprint(u.src, size); seeded.push((r.as_raw() as usize, StreamRecheck { base_frame: frame, stage: 0, last_fp: fp })); } if !seeded.is_empty() { @@ -1234,21 +1376,33 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { let mut bytes = 0usize; let mut device = 0usize; let skip_unchanged = unchanged_skip(); - while let Some((_, (dev, _, tex, _))) = todo.peek() { - if !batch_fits(picked.len(), bytes, device, *dev, tex.size() as usize) { + while let Some((_, u)) = todo.peek() { + if !batch_fits(picked.len(), bytes, device, u.device, u.tex.size() as usize) { break; } - let (r, (dev, va, tex, states)) = todo.next().unwrap(); - device = dev; - bytes += tex.size() as usize; - picked.push((r, va, tex, states)); + let (r, u) = todo.next().unwrap(); + let size = u.tex.size() as usize; + let mut already_checked = false; + if skip_unchanged && u.dirty_pages.is_some() { + if changed_pages_since_last_upload(r.as_raw() as usize, u.src, size, u.dirty_pages.as_deref(), u.page_size).is_none() { + let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || (n.is_power_of_two() && n >= 1024) { + crate::xlog_info!("title textures: {n} uploads left out so far – the texture's memory held what it held at its last upload"); + } + continue; + } + already_checked = true; + } + device = u.device; + bytes += size; + picked.push((r, u.src, u.tex, u.states, u.page_size, already_checked)); } if picked.is_empty() { continue; } let prepared = hash_and_detile_all(&picked, bytes, skip_unchanged); let mut batch = Vec::with_capacity(picked.len()); - for ((r, va, _, states), subs) in picked.into_iter().zip(prepared) { + for ((r, va, _, states, _, _), subs) in picked.into_iter().zip(prepared) { let Some(subs) = subs else { continue; }; @@ -1650,18 +1804,19 @@ fn detile_pool() -> &'static DetilePool { /// Read each texture once, optionally skip unchanged content (`LAST_CONTENT`), and detile from the /// same buffer — using the persistent detile worker pool when the batch reaches `PARALLEL_BYTES`. unsafe fn hash_and_detile_all( - picked: &[(ID3D12Resource, usize, Arc, Vec)], + picked: &[(ID3D12Resource, usize, Arc, Vec, usize, bool)], bytes: usize, skip_unchanged: bool, ) -> Vec>> { - let items: Vec<(usize, usize, &xg::Texture)> = picked.iter().map(|(r, va, tex, _)| (r.as_raw() as usize, *va, &**tex)).collect(); + let items: Vec<(usize, usize, &xg::Texture, usize, bool)> = + picked.iter().map(|(r, va, tex, _, page_size, checked)| (r.as_raw() as usize, *va, &**tex, *page_size, *checked)).collect(); let threads = if bytes < PARALLEL_BYTES { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8) }; let threads = threads.min(items.len()); - let work = |res: usize, va: usize, tex: &xg::Texture| -> Option> { - let mem = title_bytes(va, tex.size() as usize); - if skip_unchanged { - let h = content_hash(&mem); - if same_as_last_upload(res, h) { + let work = |res: usize, va: usize, tex: &xg::Texture, page_size: usize, already_checked: bool| -> Option> { + let size = tex.size() as usize; + let mem = title_bytes(va, size); + if skip_unchanged && !already_checked { + if changed_pages_with(res, va, size, None, page_size, |at, len| std::borrow::Cow::Borrowed(&mem[at - va..at - va + len])).is_none() { let n = UNCHANGED.fetch_add(1, Ordering::Relaxed) + 1; if n == 1 || (n.is_power_of_two() && n >= 1024) { crate::xlog_info!("title textures: {n} uploads left out so far – the texture's memory held what it held at its last upload"); @@ -1672,14 +1827,14 @@ unsafe fn hash_and_detile_all( Some(subresources_from_bytes(&mem, tex)) }; if threads <= 1 { - return items.iter().map(|&(res, va, tex)| work(res, va, tex)).collect(); + return items.iter().map(|&(res, va, tex, ps, checked)| work(res, va, tex, ps, checked)).collect(); } let next = std::sync::atomic::AtomicUsize::new(0); let out: Vec>>> = (0..items.len()).map(|_| Mutex::new(None)).collect(); detile_pool().run(threads, &|| loop { let k = next.fetch_add(1, Ordering::Relaxed); - let Some(&(res, va, tex)) = items.get(k) else { break }; - if let Some(subs) = work(res, va, tex) { + let Some(&(res, va, tex, ps, checked)) = items.get(k) else { break }; + if let Some(subs) = work(res, va, tex, ps, checked) { *out[k].lock().unwrap() = Some(subs); } }); @@ -1765,13 +1920,21 @@ mod tests { /// texture that was forgotten (released, or its address registered again) is uploaded again. #[test] fn a_texture_with_unchanged_memory_is_left_out_until_it_is_forgotten() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; let (a, b) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); + forget(a); + forget(b); let mut mem = vec![0u8; 3 << 20]; mem[5] = 1; + let src = mem.as_ptr() as usize; + let size = mem.len(); + let (_, count) = page_count(src, size, PAGE); + let all_pages: Vec = (0..count).collect(); let h = content_hash(&mem); - assert!(!same_as_last_upload(a, h), "the first upload is not left out"); - assert!(same_as_last_upload(a, h), "the same bytes again: left out"); - assert!(!same_as_last_upload(b, h), "another texture over the same bytes has its own first upload"); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), Some(all_pages.clone()), "the first upload is not left out"); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), None, "the same bytes again: left out"); + assert_eq!(changed_pages_with(b, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), Some(all_pages.clone()), "another texture over the same bytes has its own first upload"); // one byte anywhere, also in the tail that is not a whole 32-byte step for at in [0usize, 31, 32, (3 << 20) - 1] { let mut m = mem.clone(); @@ -1779,17 +1942,199 @@ mod tests { assert_ne!(content_hash(&m), h, "byte {at} changed"); } mem[(3 << 20) - 1] = 9; - let h2 = content_hash(&mem); - assert!(!same_as_last_upload(a, h2), "changed memory is uploaded"); - assert!(same_as_last_upload(a, h2)); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), Some(vec![count - 1]), "changed memory is uploaded"); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), None); // the length is part of the content: a prefix of zeros is not the whole assert_ne!(content_hash(&[0u8; 64]), content_hash(&[0u8; 96])); forget(a); - assert!(!same_as_last_upload(a, h2), "forgotten: its next upload is a first one"); + assert_eq!(changed_pages_with(a, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), Some(all_pages), "forgotten: its next upload is a first one"); forget(a); forget(b); } + #[test] + fn dirty_page_unchanged_skips_and_reads_only_that_page() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0001usize; + forget(res); + let mem = vec![0x5Au8; 8 * PAGE]; + let src = 0x10_0000usize; + let mut bytes_read = 0usize; + let got = changed_pages_with(res, src, mem.len(), None, PAGE, |at, len| { + bytes_read += len; + Cow::Borrowed(&mem[at - src..at - src + len]) + }); + assert_eq!(got, Some((0..8).collect())); + assert_eq!(bytes_read, mem.len()); + + bytes_read = 0; + let mut calls = Vec::new(); + let dirty = [src + 3 * PAGE]; + let got = changed_pages_with(res, src, mem.len(), Some(&dirty), PAGE, |at, len| { + bytes_read += len; + calls.push((at, len)); + Cow::Borrowed(&mem[at - src..at - src + len]) + }); + assert_eq!(got, None, "unchanged dirty page must skip upload"); + assert_eq!(bytes_read, PAGE, "only the single 4096-byte dirty page must be read"); + assert_eq!(calls, vec![(src + 3 * PAGE, PAGE)]); + forget(res); + } + + #[test] + fn dirty_page_one_modified_byte_updates_only_that_page_hash() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0002usize; + forget(res); + let mut mem = vec![0x11u8; 6 * PAGE]; + let src = 0x20_0000usize; + assert_eq!( + changed_pages_with(res, src, mem.len(), None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + Some((0..6).collect()) + ); + + mem[2 * PAGE + 123] ^= 0x01; + mem[4 * PAGE + 77] ^= 0x01; + let mut bytes_read = 0usize; + let dirty2 = [src + 2 * PAGE]; + let got = changed_pages_with(res, src, mem.len(), Some(&dirty2), PAGE, |at, len| { + bytes_read += len; + Cow::Borrowed(&mem[at - src..at - src + len]) + }); + assert_eq!(got, Some(vec![2])); + assert_eq!(bytes_read, PAGE); + + assert_eq!( + changed_pages_with(res, src, mem.len(), Some(&dirty2), PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + None + ); + let dirty4 = [src + 4 * PAGE]; + assert_eq!( + changed_pages_with(res, src, mem.len(), Some(&dirty4), PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + Some(vec![4]) + ); + forget(res); + } + + #[test] + fn unaligned_src_and_tail_bytes_hash_exact_clamped_spans() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0003usize; + forget(res); + let src = 0x30_0500usize; + let size = 0x2307usize; + assert_eq!(page_count(src, size, PAGE), (0x30_0000, 3)); + assert_eq!(page_count(src, 0, PAGE), (src, 0)); + + let mut mem = vec![0x33u8; size]; + assert_eq!( + changed_pages_with(res, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + Some(vec![0, 1, 2]) + ); + + let mut calls = Vec::new(); + assert_eq!( + changed_pages_with(res, src, size, Some(&[0x30_0000]), PAGE, |at, len| { + calls.push((at, len)); + Cow::Borrowed(&mem[at - src..at - src + len]) + }), + None + ); + assert_eq!(calls, vec![(src, 0xB00)]); + + mem[size - 1] ^= 0xFF; + calls.clear(); + assert_eq!( + changed_pages_with(res, src, size, Some(&[0x30_2000]), PAGE, |at, len| { + calls.push((at, len)); + Cow::Borrowed(&mem[at - src..at - src + len]) + }), + Some(vec![2]) + ); + assert_eq!(calls, vec![(0x30_2000, 0x807)]); + + mem[0] ^= 0xFF; + calls.clear(); + assert_eq!( + changed_pages_with(res, src, size, Some(&[0x30_0000]), PAGE, |at, len| { + calls.push((at, len)); + Cow::Borrowed(&mem[at - src..at - src + len]) + }), + Some(vec![0]) + ); + assert_eq!(calls, vec![(src, 0xB00)]); + assert_eq!( + changed_pages_with(res, src, size, None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + None + ); + forget(res); + } + + #[test] + fn remapped_src_and_forget_force_full_upload_even_with_identical_bytes() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0004usize; + forget(res); + let mem = vec![0u8; 4 * PAGE]; + let src1 = 0x40_0000usize; + let src2 = 0x50_0000usize; + + assert_eq!( + changed_pages_with(res, src1, mem.len(), None, PAGE, |at, len| Cow::Borrowed(&mem[at - src1..at - src1 + len])), + Some(vec![0, 1, 2, 3]) + ); + assert_eq!( + changed_pages_with(res, src1, mem.len(), Some(&[src1]), PAGE, |at, len| Cow::Borrowed(&mem[at - src1..at - src1 + len])), + None + ); + + assert_eq!( + changed_pages_with(res, src2, mem.len(), Some(&[src2]), PAGE, |at, len| Cow::Borrowed(&mem[at - src2..at - src2 + len])), + Some(vec![0, 1, 2, 3]) + ); + assert_eq!( + changed_pages_with(res, src2, mem.len(), Some(&[src2 + PAGE]), PAGE, |at, len| Cow::Borrowed(&mem[at - src2..at - src2 + len])), + None + ); + + forget(res); + assert_eq!( + changed_pages_with(res, src2, mem.len(), Some(&[src2]), PAGE, |at, len| Cow::Borrowed(&mem[at - src2..at - src2 + len])), + Some(vec![0, 1, 2, 3]) + ); + forget(res); + } + + #[test] + fn duplicate_dirty_pages_produce_unique_changed_indices() { + use std::borrow::Cow; + const PAGE: usize = 0x1000; + let res = 0x7E57_2395_0005usize; + forget(res); + let mut mem = vec![0u8; 4 * PAGE]; + let src = 0x60_0000usize; + assert_eq!( + changed_pages_with(res, src, mem.len(), None, PAGE, |at, len| Cow::Borrowed(&mem[at - src..at - src + len])), + Some(vec![0, 1, 2, 3]) + ); + + mem[PAGE + 10] = 0xAA; + mem[3 * PAGE + 20] = 0xBB; + let dirty = [src + 3 * PAGE, src + PAGE, src + PAGE + 0x100, src + 3 * PAGE + 0x200, src + PAGE]; + let mut bytes_read = 0usize; + let got = changed_pages_with(res, src, mem.len(), Some(&dirty), PAGE, |at, len| { + bytes_read += len; + Cow::Borrowed(&mem[at - src..at - src + len]) + }); + assert_eq!(got, Some(vec![1, 3])); + assert_eq!(bytes_read, 2 * PAGE); + forget(res); + } + /// Real uploads, dirty-page detection and a source changing after registration: /// bookkeeping alone cannot show that the bytes the GPU sees follow the mirror. #[test] @@ -2975,19 +3320,19 @@ mod tests { // Only pending entry fires with no dirty pages. let (hits, cleared) = t.dirty_and_pending(&[], 0x1000); - assert_eq!(hits, vec![0x200]); + assert_eq!(hits, vec![(0x200, true)]); assert_eq!(cleared, 1); // Dirty pages hitting small, large, and gpu_written return only small + large. let dirty = [0x2000_1000, 0x2021_0000, 0x2030_0000]; let (hits, cleared) = t.dirty_and_pending(&dirty, 0x1000); - assert_eq!(hits, vec![0x100, 0x300]); + assert_eq!(hits, vec![(0x100, false), (0x300, false)]); assert_eq!(cleared, 0); // Marking small as gpu_written removes it from dirty scans. assert!(t.mark_gpu_written(0x100)); let (hits, _) = t.dirty_and_pending(&dirty, 0x1000); - assert_eq!(hits, vec![0x300]); + assert_eq!(hits, vec![(0x300, false)]); } #[test] From 1dcfde8c03fd0fbce6716fba85a758c45fecb5c5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:23:18 +0100 Subject: [PATCH 110/258] D3D12.X: gate tiny <4 KiB GetCachedBlob stubs as cold compiles Some drivers (notably AMD RDNA4) return <= 1 KiB metadata stub headers from ID3D12PipelineState::GetCachedBlob() containing no compiled GPU ISA, so CreateComputePipelineState / CreateGraphicsPipelineState still performs a full cold compile when given one. Previously compute_container and translated_graphics_pso_once treated any non-empty cached blob as a fast ISA hit, bypassing BIG_COMPILES / MEDIUM_COMPILES gating and XCL_PSO_MAX_KB and allowing concurrent large compute compiles to spike commit past 40 GB. Require >= 4 KiB (MIN_ISA_CACHED_BLOB_BYTES) before treating a GetCachedBlob payload as compiled ISA when caching, reloading from driver/, or bypassing compile-slot gating. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 80 +++++++++++++++++++++++-------- 1 file changed, 60 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bfdca8982b..f9ee1b54bb 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4433,10 +4433,20 @@ fn gate_note(huge_size: bool, gated: bool, waited: std::time::Duration) -> Strin } } -/// A cached-blob attempt should be quick and must not take a cold-compile slot. Its retry -/// without the rejected blob is a cold compile and does take one. -fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { - !has_cached_blob +/// Minimum `GetCachedBlob` size (4 KiB) to treat a cached PSO blob as containing compiled +/// driver ISA rather than a tiny metadata stub header (some drivers emit <= 1 KiB stub blobs +/// that still trigger a full cold compile on reload). +const MIN_ISA_CACHED_BLOB_BYTES: usize = 4096; + +fn cached_blob_has_isa(blob: Option<&[u8]>) -> bool { + blob.is_some_and(|b| b.len() >= MIN_ISA_CACHED_BLOB_BYTES) +} + +/// A cached-blob attempt with compiled driver ISA should be quick and must not take a +/// cold-compile slot. Tiny stub blobs (`< MIN_ISA_CACHED_BLOB_BYTES`) and retries without +/// a rejected blob are cold compiles and do take one. +fn gate_compute_driver_compile(has_isa_cached_blob: bool) -> bool { + !has_isa_cached_blob } /// Before a big driver compile in the background: its turn – unwanted builds wait for both @@ -4630,6 +4640,13 @@ mod big_compile_tests { fn only_a_cold_compute_compile_takes_a_slot() { assert!(!gate_compute_driver_compile(true), "the cached-blob attempt bypasses the gate"); assert!(gate_compute_driver_compile(false), "a cold attempt, including a retry, is gated"); + assert!(!cached_blob_has_isa(None), "missing blob has no compiled ISA"); + assert!(!cached_blob_has_isa(Some(&[])), "empty blob has no compiled ISA"); + assert!(!cached_blob_has_isa(Some(&[0u8; 930])), "tiny driver stub header must stay gated as cold compile"); + assert!(!cached_blob_has_isa(Some(&[0u8; MIN_ISA_CACHED_BLOB_BYTES - 1])), "sub-4 KiB blob must stay gated"); + assert!(cached_blob_has_isa(Some(&[0u8; MIN_ISA_CACHED_BLOB_BYTES])), ">= 4 KiB blob counts as compiled ISA"); + assert!(gate_compute_driver_compile(cached_blob_has_isa(Some(&[0u8; 930])))); + assert!(!gate_compute_driver_compile(cached_blob_has_isa(Some(&[0u8; MIN_ISA_CACHED_BLOB_BYTES])))); } #[test] @@ -4851,10 +4868,17 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL let disk = driver_cache::path_for(dxil, copy.Flags.0, chained); let from_disk = cached.is_none(); if from_disk { - cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + cached = disk + .as_deref() + .and_then(driver_cache::load) + .filter(|b| cached_blob_has_isa(Some(b))) + .map(std::sync::Arc::new); } - if let Some(b) = &cached { - copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + let has_isa_blob = cached_blob_has_isa(cached.as_deref().map(Vec::as_slice)); + if has_isa_blob { + if let Some(b) = &cached { + copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + } } if skip_listed(record) { static N: AtomicU64 = AtomicU64::new(0); @@ -4864,19 +4888,19 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL } return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); } - if (cached.is_none() || cap_holds_for_cached()) && over_build_cap(dxil.len(), build_cap_bytes()) { - crate::xlog_warn!("D3D12.X: compute PSO of record {record:016x} ({} B DXIL) not built: over XCL_PSO_MAX_KB{}", dxil.len(), if cached.is_none() { " and without a saved blob" } else { " (it has a saved blob)" }); + if (!has_isa_blob || cap_holds_for_cached()) && over_build_cap(dxil.len(), build_cap_bytes()) { + crate::xlog_warn!("D3D12.X: compute PSO of record {record:016x} ({} B DXIL) not built: over XCL_PSO_MAX_KB{}", dxil.len(), if !has_isa_blob { " and without a saved blob" } else { " (it has a saved blob)" }); return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); } // in the background, a few at a time and within the commit headroom the program asks for let (mut hr, mut in_driver) = driver_compile_identified( "compute", dxil.len(), - gate_compute_driver_compile(cached.is_some()), - Some((record, cached.is_some())), + gate_compute_driver_compile(has_isa_blob), + Some((record, has_isa_blob)), || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); - if hr < 0 && cached.is_some() { + if hr < 0 && has_isa_blob { // a blob the driver does not take (another root signature at the same address…): compiled if driver_cache::refused(hr) { forget_compute_blob(key); @@ -5200,11 +5224,12 @@ unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option> { } else { let p = ID3D12PipelineState::from_raw_borrowed(&pso)?; let blob = p.GetCachedBlob().ok()?; - return Some(std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec()); + let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec(); + return cached_blob_has_isa(Some(&bytes)).then_some(bytes); }; let blob = ID3DBlob::from_raw(raw); let bytes = std::slice::from_raw_parts(blob.GetBufferPointer() as *const u8, blob.GetBufferSize()).to_vec(); - (!bytes.is_empty()).then_some(bytes) + cached_blob_has_isa(Some(&bytes)).then_some(bytes) } /// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute @@ -5691,11 +5716,16 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let disk = driver_cache::graphics_path(gkey.0, gkey.1); let from_disk = cached.is_none(); if from_disk { - cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + cached = disk + .as_deref() + .and_then(driver_cache::load) + .filter(|b| cached_blob_has_isa(Some(b))) + .map(std::sync::Arc::new); } + let has_isa_blob = cached_blob_has_isa(cached.as_deref().map(Vec::as_slice)); let build = create_graphics_pso_cached( &mut copy, - cached.as_deref().map(Vec::as_slice), + has_isa_blob.then(|| cached.as_deref().map(Vec::as_slice)).flatten(), rect_gs.is_some(), || { forget_graphics_blob(gkey); @@ -5703,7 +5733,10 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const driver_cache::note(false, disk.as_deref()); } }, - |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), f), + |label, has_cached, f| { + let gated_cached = has_cached && has_isa_blob; + driver_compile_identified(label, bytes, gate_compute_driver_compile(gated_cached), Some((ps_hash, gated_cached)), f) + }, |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), ); let hr = build.hr; @@ -6474,10 +6507,17 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let cdisk = driver_cache::path(&tp.cs, 0); let cfrom_disk = ccached.is_none(); if cfrom_disk { - ccached = cdisk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + ccached = cdisk + .as_deref() + .and_then(driver_cache::load) + .filter(|b| cached_blob_has_isa(Some(b))) + .map(std::sync::Arc::new); } - if let Some(b) = &ccached { - cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + let chas_isa_blob = cached_blob_has_isa(ccached.as_deref().map(Vec::as_slice)); + if chas_isa_blob { + if let Some(b) = &ccached { + cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; + } } let iid = pc_iid(Kind::PipelineState); let mut compute: *mut c_void = std::ptr::null_mut(); From a87b439e07fb656f318ffa0e2a4a81df8e7b9d47 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:26:17 +0100 Subject: [PATCH 111/258] D3D12.X: wire memory-mapped ID3D12PipelineLibrary1 persistence (#2001) Port the memory-mapped ID3D12PipelineLibrary1 cache from #2001 onto amd-dev (enabled by default, opt-out via XCL_PSO_LIBRARY=0) so drivers whose GetCachedBlob() returns only tiny stub headers (e.g. AMD RDNA4) persist and reload real compiled GPU ISA across runs with zero heap duplication: - Add pso_library.rs (MappedBlob read-only mapping kept open for the library lifetime, MappedWriteFile zero-heap-copy serialization into generational gen-NNNNNNNN.plib files via .tmp atomic rename, skipping empty files and preserving existing .plib files on transient device/OOM failures). - Wire pso_lib load/store into translated_compute_pso_once (preserving note_compute_threads and note_bvh_traversal on hits), translated_graphics_pso_once, and finish_two_pass (trying both mesh stream and compute pass loads before acquiring big_compile_turn so warm hits skip compile slots completely). - Flush dirty pipeline library entries cleanly on WM_CLOSE, XCL_RUN_SECONDS exit, and normal main return, in addition to periodic background xcl-plib-save snapshots. - Deduplicate concurrent in-memory blob insertions (insert_cached_blob) and fix the missing by_submit field in pso_async::pso_queue_tests::dummy_pending. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/present.rs | 1 + crates/xcl/src/hle/d3d12x/pso_async.rs | 2 +- crates/xcl/src/hle/d3d12x/pso_library.rs | 622 ++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 702 ++++++++++++++++++++++- crates/xcl/src/host.rs | 2 + 6 files changed, 1311 insertions(+), 19 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/pso_library.rs diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 99944adb53..a90571f9f5 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -30,6 +30,7 @@ pub mod null; mod place_times; pub mod present; pub mod pso_async; +pub mod pso_library; pub mod real; mod shader_cache_session; pub mod sparse; diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 48858707d9..fd9fa17e3a 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -381,6 +381,7 @@ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) match msg { WM_CLOSE => { crate::xlog_info!("XCL window closed – ending the game process"); + super::real::flush_pipeline_library(); crate::report::write_final(None); crate::log::flush(); windows::Win32::System::Threading::ExitProcess(0); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 08e2d3024c..c4f87572ed 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1364,7 +1364,7 @@ mod pso_queue_tests { spared: Default::default(), bvh_traversal: Default::default(), deprioritized: std::sync::atomic::AtomicBool::new(deprioritized), - demand: Mutex::new(Demand { wanted, preload_thread: 0 }), + demand: Mutex::new(Demand { wanted, by_submit: false, preload_thread: 0 }), }) } diff --git a/crates/xcl/src/hle/d3d12x/pso_library.rs b/crates/xcl/src/hle/d3d12x/pso_library.rs new file mode 100644 index 0000000000..84ecae4a8e --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pso_library.rs @@ -0,0 +1,622 @@ +//! Memory-mapped `ID3D12PipelineLibrary` persistence (`XCL_PSO_LIBRARY=0`: off). +//! +//! Backing a driver pipeline library with a read-only Windows file mapping kept open for the +//! lifetime of `ID3D12PipelineLibrary` avoids duplicating hundreds of megabytes to >1 GiB of +//! private heap commit on load, and writing new snapshots through a separate file-backed mapping +//! into a fresh generation file (`gen-NNNNNNNN.plib`) avoids both `Vec` serialize spikes and +//! in-place replacement of an actively mapped file (which fails on Windows or triggers driver +//! device removal). + +use std::ffi::c_void; +use std::os::windows::ffi::OsStrExt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows::core::{Interface, HSTRING}; +use windows::Win32::Graphics::Direct3D12::*; +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, GetFileSizeEx, SetEndOfFile, SetFilePointerEx, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, + FILE_BEGIN, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_DELETE, FILE_SHARE_READ, + FILE_SHARE_WRITE, OPEN_EXISTING, +}; +use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, FILE_MAP_READ, FILE_MAP_WRITE, + MEMORY_MAPPED_VIEW_ADDRESS, PAGE_READONLY, PAGE_READWRITE, +}; + +const D3D12_ERROR_ADAPTER_NOT_FOUND_HR: i32 = 0x887E_0001u32 as i32; +const D3D12_ERROR_DRIVER_VERSION_MISMATCH_HR: i32 = 0x887E_0002u32 as i32; + +/// Whether the on-disk memory-mapped pipeline library is enabled (`XCL_PSO_LIBRARY=0` disables). +pub fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PSO_LIBRARY").map_or(true, |v| v.trim() != "0")) +} + +fn wide_path(path: &Path) -> Vec { + path.as_os_str().encode_wide().chain(std::iter::once(0)).collect() +} + +/// A read-only Windows file mapping kept open (file + section + mapped view) with zero private +/// heap copy. Dropping unmaps the view and closes both handles in reverse order. +pub struct MappedBlob { + path: PathBuf, + file: HANDLE, + mapping: HANDLE, + view: *const u8, + len: usize, +} + +// The view is strictly read-only and backed by immutable OS handles owned uniquely by `MappedBlob`. +unsafe impl Send for MappedBlob {} +unsafe impl Sync for MappedBlob {} + +impl MappedBlob { + /// Open `path` read-only with shared read/write/delete access and map its entire contents. + /// Returns `None` when the file does not exist, is empty, or cannot be mapped. + pub fn open(path: &Path) -> Option { + let wide = wide_path(path); + unsafe { + let file = CreateFileW( + wide.as_ptr(), + FILE_GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + std::ptr::null(), + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + std::ptr::null_mut(), + ); + if file == INVALID_HANDLE_VALUE || file.is_null() { + return None; + } + let mut size = 0i64; + if GetFileSizeEx(file, &mut size) == 0 || size <= 0 { + CloseHandle(file); + return None; + } + let Ok(len) = usize::try_from(size) else { + CloseHandle(file); + return None; + }; + let mapping = CreateFileMappingW(file, std::ptr::null(), PAGE_READONLY, 0, 0, std::ptr::null()); + if mapping.is_null() { + CloseHandle(file); + return None; + } + let view = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0); + if view.Value.is_null() { + CloseHandle(mapping); + CloseHandle(file); + return None; + } + Some(Self { + path: path.to_path_buf(), + file, + mapping, + view: view.Value as *const u8, + len, + }) + } + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn as_ptr(&self) -> *const c_void { + self.view as *const c_void + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn as_slice(&self) -> &[u8] { + unsafe { std::slice::from_raw_parts(self.view, self.len) } + } +} + +impl Drop for MappedBlob { + fn drop(&mut self) { + unsafe { + if !self.view.is_null() { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: self.view as *mut c_void }); + } + if !self.mapping.is_null() { + CloseHandle(self.mapping); + } + if !self.file.is_null() && self.file != INVALID_HANDLE_VALUE { + CloseHandle(self.file); + } + } + } +} + +/// A read-write Windows file mapping for serializing a pipeline library directly into file-backed +/// pages without allocating a matching heap `Vec`. +pub struct MappedWriteFile { + path: PathBuf, + file: HANDLE, + mapping: HANDLE, + view: *mut u8, + len: usize, + committed: bool, +} + +impl MappedWriteFile { + /// Create (or truncate) `path` with exact byte length `len` and map it writable. + pub fn create(path: &Path, len: usize) -> Option { + if len == 0 { + return None; + } + let size = i64::try_from(len).ok()?; + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let wide = wide_path(path); + unsafe { + let file = CreateFileW( + wide.as_ptr(), + FILE_GENERIC_READ | FILE_GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_DELETE, + std::ptr::null(), + CREATE_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + std::ptr::null_mut(), + ); + if file == INVALID_HANDLE_VALUE || file.is_null() { + return None; + } + let mut new_pos = 0i64; + if SetFilePointerEx(file, size, &mut new_pos, FILE_BEGIN) == 0 || SetEndOfFile(file) == 0 { + CloseHandle(file); + let _ = std::fs::remove_file(path); + return None; + } + let mapping = CreateFileMappingW( + file, + std::ptr::null(), + PAGE_READWRITE, + ((len as u64) >> 32) as u32, + (len as u64 & 0xFFFF_FFFF) as u32, + std::ptr::null(), + ); + if mapping.is_null() { + CloseHandle(file); + let _ = std::fs::remove_file(path); + return None; + } + let view = MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, len); + if view.Value.is_null() { + CloseHandle(mapping); + CloseHandle(file); + let _ = std::fs::remove_file(path); + return None; + } + Some(Self { + path: path.to_path_buf(), + file, + mapping, + view: view.Value as *mut u8, + len, + committed: false, + }) + } + } + + pub fn as_mut_ptr(&mut self) -> *mut c_void { + self.view as *mut c_void + } + + pub fn as_mut_slice(&mut self) -> &mut [u8] { + unsafe { std::slice::from_raw_parts_mut(self.view, self.len) } + } + + /// Unmap and close the file cleanly, keeping the written file on disk. + pub fn finish(mut self) -> PathBuf { + self.committed = true; + self.close_handles(); + self.path.clone() + } + + fn close_handles(&mut self) { + unsafe { + if !self.view.is_null() { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: self.view as *mut c_void }); + self.view = std::ptr::null_mut(); + } + if !self.mapping.is_null() { + CloseHandle(self.mapping); + self.mapping = std::ptr::null_mut(); + } + if !self.file.is_null() && self.file != INVALID_HANDLE_VALUE { + CloseHandle(self.file); + self.file = INVALID_HANDLE_VALUE; + } + } + } +} + +impl Drop for MappedWriteFile { + fn drop(&mut self) { + self.close_handles(); + if !self.committed { + let _ = std::fs::remove_file(&self.path); + } + } +} + +/// Generational `.plib` directory manager: each save writes a new `gen-NNNNNNNN.plib` through a +/// `.tmp` staging file so any earlier generation kept memory-mapped by `ID3D12PipelineLibrary` is +/// never truncated or replaced while open. +pub struct LibraryStore { + dir: PathBuf, + next_gen: AtomicU64, +} + +impl LibraryStore { + pub fn new(dir: PathBuf) -> Self { + let latest = latest_generation(&dir).map_or(0, |(g, _)| g); + Self { dir, next_gen: AtomicU64::new(latest + 1) } + } + + pub fn for_adapter(adapter_name: &str) -> Self { + let key = format!("{:016x}", crate::gpu::shader::fnv64(adapter_name.as_bytes())); + Self::new(crate::gpu::recomp::dxc::cache_dir().join("pso-library").join(key)) + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + /// Open the newest non-empty generation file as a read-only memory mapping and clean up older + /// unmapped generations from previous runs. + pub fn open_latest(&self) -> Option<(u64, MappedBlob)> { + let (gen, path) = latest_generation(&self.dir)?; + let blob = MappedBlob::open(&path)?; + self.next_gen.fetch_max(gen + 1, Ordering::AcqRel); + cleanup_older_generations(&self.dir, gen); + Some((gen, blob)) + } + + /// Write a fresh generation of `len` bytes using a file-backed writable mapping and commit it + /// atomically via rename. Never touches any earlier generation currently kept open. + pub fn write_generation(&self, len: usize, write_fn: impl FnOnce(&mut [u8]) -> bool) -> Option<(u64, PathBuf)> { + if len == 0 { + return None; + } + let gen = self.next_gen.fetch_add(1, Ordering::AcqRel); + let final_path = self.dir.join(generation_name(gen)); + let tmp_path = self.dir.join(format!("gen-{gen:08x}-{}.tmp", std::process::id())); + let mut mapped = MappedWriteFile::create(&tmp_path, len)?; + let ok = write_fn(mapped.as_mut_slice()); + if !ok { + drop(mapped); + return None; + } + let staged = mapped.finish(); + if std::fs::rename(&staged, &final_path).is_err() { + let _ = std::fs::remove_file(&staged); + return None; + } + Some((gen, final_path)) + } +} + +fn generation_name(gen: u64) -> String { + format!("gen-{gen:08x}.plib") +} + +fn parse_generation(file_name: &str) -> Option { + let hex = file_name.strip_prefix("gen-")?.strip_suffix(".plib")?; + if hex.is_empty() { + return None; + } + u64::from_str_radix(hex, 16).ok() +} + +fn latest_generation(dir: &Path) -> Option<(u64, PathBuf)> { + let entries = std::fs::read_dir(dir).ok()?; + let mut best: Option<(u64, PathBuf)> = None; + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue }; + let Some(gen) = parse_generation(name) else { continue }; + if !entry.metadata().ok().is_some_and(|m| m.len() > 0) { + continue; + } + if best.as_ref().is_none_or(|&(b, _)| gen > b) { + best = Some((gen, path)); + } + } + best +} + +fn cleanup_older_generations(dir: &Path, keep_gen: u64) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { continue }; + if parse_generation(name).is_some_and(|g| g < keep_gen) || name.ends_with(".tmp") { + let _ = std::fs::remove_file(path); + } + } +} + +/// Process-wide D3D12 pipeline library backed by a kept-open read-only `MappedBlob` and +/// generational zero-heap-copy serialization. +pub struct MmapPipelineLibrary { + lib: ID3D12PipelineLibrary1, + /// Kept alive for the entire lifetime of `lib` because D3D12 requires the initial blob memory + /// to remain valid until the `ID3D12PipelineLibrary` is destroyed. + _backing: Option, + store: LibraryStore, + dirty: AtomicU64, + saving: AtomicBool, + save_lock: Mutex<()>, + /// Synchronizes concurrent `StorePipeline` (shared read lock) against `GetSerializedSize` + + /// `Serialize` (exclusive write lock) so serialization never races a concurrent size growth. + lib_rw: RwLock<()>, +} + +// `ID3D12PipelineLibrary1` methods are free-threaded per the D3D12 specification; `_backing` is +// read-only and `save_lock` serializes disk snapshots. +unsafe impl Send for MmapPipelineLibrary {} +unsafe impl Sync for MmapPipelineLibrary {} + +impl MmapPipelineLibrary { + /// Open the latest memory-mapped pipeline library on `device`, falling back to a fresh empty + /// library if none exists or if the driver rejects the cached generation (driver/adapter mismatch). + pub unsafe fn open_or_create(device: &ID3D12Device, adapter_name: &str) -> Option { + if !enabled() { + return None; + } + let dev1: ID3D12Device1 = device.cast().ok()?; + let store = LibraryStore::for_adapter(adapter_name); + if let Some((gen, blob)) = store.open_latest() { + match dev1.CreatePipelineLibrary::(blob.as_slice()) { + Ok(lib) => { + crate::xlog_info!( + "D3D12.X: opened memory-mapped pipeline library gen-{gen:08x} ({:.1} MiB file-backed)", + blob.len() as f64 / (1024.0 * 1024.0) + ); + return Some(Self { + lib, + _backing: Some(blob), + store, + dirty: AtomicU64::new(0), + saving: AtomicBool::new(false), + save_lock: Mutex::new(()), + lib_rw: RwLock::new(()), + }); + } + Err(e) => { + let stale_path = blob.path().to_path_buf(); + let code = e.code().0; + drop(blob); + if !super::real::driver_cache::refused(code) { + // Transient failure (device removed/hung/reset or OOM): preserve the valid + // `.plib` on disk instead of starting an empty library that would later + // write a smaller generation superseding it. + crate::xlog_warn!( + "D3D12.X: pipeline library gen-{gen:08x} open failed transiently ({code:#x}) – preserving cached file" + ); + return None; + } + // Remove any driver-rejected generation (driver/adapter mismatch, corrupt + // E_INVALIDARG, etc.) so a broken file does not remain the latest generation. + let _ = std::fs::remove_file(&stale_path); + let _ = (D3D12_ERROR_DRIVER_VERSION_MISMATCH_HR, D3D12_ERROR_ADAPTER_NOT_FOUND_HR); + crate::xlog_info!( + "D3D12.X: pipeline library gen-{gen:08x} rejected ({code:#x}) – removed stale file and starting fresh library" + ); + } + } + } + // Pass an explicit NULL pointer with length 0 rather than `&[]`, whose dangling + // non-null slice pointer vkd3d-proton rejects with E_INVALIDARG. + let mut lib: Option = None; + (Interface::vtable(&dev1).CreatePipelineLibrary)( + Interface::as_raw(&dev1), + std::ptr::null(), + 0, + &ID3D12PipelineLibrary1::IID, + &mut lib as *mut _ as *mut _, + ) + .ok() + .ok()?; + let lib = lib?; + Some(Self { + lib, + _backing: None, + store, + dirty: AtomicU64::new(0), + saving: AtomicBool::new(false), + save_lock: Mutex::new(()), + lib_rw: RwLock::new(()), + }) + } + + pub unsafe fn load_compute(&self, key: &str, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> Option { + let name = HSTRING::from(key); + let _r = self.lib_rw.read().unwrap(); + self.lib.LoadComputePipeline(&name, desc).ok() + } + + pub unsafe fn load_graphics(&self, key: &str, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option { + let name = HSTRING::from(key); + let _r = self.lib_rw.read().unwrap(); + self.lib.LoadGraphicsPipeline(&name, desc).ok() + } + + pub unsafe fn load_stream(&self, key: &str, desc: &D3D12_PIPELINE_STATE_STREAM_DESC) -> Option { + let name = HSTRING::from(key); + let _r = self.lib_rw.read().unwrap(); + self.lib.LoadPipeline(&name, desc).ok() + } + + pub unsafe fn store(&self, key: &str, pso: &ID3D12PipelineState) -> bool { + let name = HSTRING::from(key); + let _r = self.lib_rw.read().unwrap(); + if self.lib.StorePipeline(&name, pso).is_ok() { + self.dirty.fetch_add(1, Ordering::Relaxed); + true + } else { + false + } + } + + pub fn dirty_count(&self) -> u64 { + self.dirty.load(Ordering::Relaxed) + } + + /// Serialize under `save_lock` (already held by caller), taking `lib_rw.write()` so no + /// `StorePipeline` can grow the library between `GetSerializedSize` and `Serialize`. + unsafe fn save_locked(&self, min_dirty: u64) -> Option { + let dirty_before = self.dirty.load(Ordering::Acquire); + if dirty_before < min_dirty { + return None; + } + let (size, saved) = { + let _w = self.lib_rw.write().unwrap(); + let size = self.lib.GetSerializedSize(); + let saved = if size > 0 { + self.store.write_generation(size, |buf| self.lib.Serialize(buf).is_ok()) + } else { + None + }; + (size, saved) + }; + if let Some((gen, _)) = saved { + self.dirty.fetch_sub(dirty_before.min(self.dirty.load(Ordering::Relaxed)), Ordering::Relaxed); + crate::xlog_info!( + "D3D12.X: saved pipeline library gen-{gen:08x} ({:.1} MiB, {} new pipelines)", + size as f64 / (1024.0 * 1024.0), + dirty_before + ); + } + saved.map(|(_, p)| p) + } + + /// Non-blocking periodic save: skips if another save is already in progress. Never replaces or + /// truncates the open `_backing` file. + pub unsafe fn save_if_dirty(&self, min_dirty: u64) -> Option { + if self.dirty.load(Ordering::Relaxed) < min_dirty { + return None; + } + if self.saving.swap(true, Ordering::AcqRel) { + return None; + } + let _guard = self.save_lock.lock().unwrap(); + let saved = self.save_locked(min_dirty); + self.saving.store(false, Ordering::Release); + saved + } + + /// Blocking shutdown flush (e.g. `WM_CLOSE` or `XCL_RUN_SECONDS`): waits for any in-flight + /// background save on `save_lock` to complete cleanly before flushing remaining dirty entries. + pub unsafe fn flush(&self) -> Option { + let _guard = self.save_lock.lock().unwrap(); + self.save_locked(1) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TempDir(PathBuf); + impl TempDir { + fn new(tag: &str) -> Self { + static SEQ: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!("xcl-pso-lib-{tag}-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Self(dir) + } + } + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn generation_parsing_and_latest_selection() { + assert_eq!(parse_generation("gen-00000001.plib"), Some(1)); + assert_eq!(parse_generation("gen-00000010.plib"), Some(0x10)); + assert_eq!(parse_generation("gen-00000002-1234.tmp"), None); + assert_eq!(parse_generation("gen-.plib"), None); + assert_eq!(parse_generation("other.plib"), None); + + let dir = TempDir::new("latest"); + std::fs::write(dir.0.join("gen-00000001.plib"), b"a").unwrap(); + std::fs::write(dir.0.join("gen-0000000a.plib"), b"bb").unwrap(); + std::fs::write(dir.0.join("gen-0000000b.plib"), b"").unwrap(); + std::fs::write(dir.0.join("gen-00000002.plib"), b"c").unwrap(); + std::fs::write(dir.0.join("gen-000000ff-99.tmp"), b"tmp").unwrap(); + let (gen, path) = latest_generation(&dir.0).unwrap(); + assert_eq!(gen, 0xA, "empty newer generation must be skipped in favor of last valid non-empty file"); + assert!(path.ends_with("gen-0000000a.plib")); + } + + #[test] + fn mapped_blob_rejects_empty_and_missing_files() { + let dir = TempDir::new("empty"); + assert!(MappedBlob::open(&dir.0.join("missing.plib")).is_none()); + let empty = dir.0.join("empty.plib"); + std::fs::write(&empty, b"").unwrap(); + assert!(MappedBlob::open(&empty).is_none()); + } + + #[test] + fn mapped_blob_reads_and_keeps_file_open_across_generation_save() { + let dir = TempDir::new("gen-save"); + let store = LibraryStore::new(dir.0.clone()); + + let payload1: Vec = (0..16_384usize).map(|i| (i.wrapping_mul(31) ^ 0x5A) as u8).collect(); + let (gen1, path1) = store + .write_generation(payload1.len(), |buf| { + buf.copy_from_slice(&payload1); + true + }) + .expect("gen1 write"); + assert_eq!(gen1, 1); + + // Open gen1 memory-mapped and keep its mapping open while saving gen2. + let (opened_gen, blob1) = store.open_latest().expect("open gen1"); + assert_eq!(opened_gen, 1); + assert_eq!(blob1.as_slice(), payload1.as_slice()); + + // Rejected/failed serialization must never overwrite gen1 or publish a new generation. + assert!(store.write_generation(0, |_| true).is_none()); + assert!(store.write_generation(1024, |_| false).is_none()); + + let payload2: Vec = (0..32_768usize).map(|i| (i.wrapping_mul(17) ^ 0xA5) as u8).collect(); + let (gen2, path2) = store + .write_generation(payload2.len(), |buf| { + buf.copy_from_slice(&payload2); + true + }) + .expect("gen2 write while gen1 mapped"); + assert!(gen2 > gen1); + assert_ne!(path1, path2); + + // gen1 mapping MUST remain completely valid and unmodified while open. + assert_eq!(blob1.as_slice(), payload1.as_slice()); + drop(blob1); + + // Re-opening latest selects gen2 and cleans up stale gen1. + let (opened_gen2, blob2) = store.open_latest().expect("open gen2"); + assert_eq!(opened_gen2, gen2); + assert_eq!(blob2.as_slice(), payload2.as_slice()); + assert!(!path1.exists(), "older generation should be cleaned up once unmapped"); + drop(blob2); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index f9ee1b54bb..ed34d52818 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4774,6 +4774,23 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); + let lib_key = pso_lib::compute_key(&dxil, &compiled.samplers, d.Flags.0); + let mut lib_copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); + lib_copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + lib_copy.CS = bytecode(&dxil); + lib_copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); + if pso_lib::try_load_compute(this, &lib_key, &lib_copy, riid, ppv) { + TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + note_pso_rs(*ppv, rs); + super::dred::label(*ppv as usize, &[("cs", Some(cs))]); + if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + } + note_compute_threads(*ppv as usize, cs); + note_bvh_traversal(*ppv as usize, cs); + note_translated_compute(S_OK, ppv); + return Some(Ok(S_OK)); + } let (hr, in_driver, reused) = compute_container(this, f, d, rs, &dxil, record, riid, ppv, false); if hr < 0 { // A huge program's verdict in the log itself: `note_translation_error` goes to the @@ -4794,6 +4811,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const return Some(Err(())); } TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + pso_lib::store_pipeline(this, &lib_key, *ppv); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { @@ -5206,6 +5224,32 @@ mod compute_blob_tests { assert!(super::compute_blob(key).is_none()); assert_eq!(super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1, before - 3); } + + #[test] + fn duplicate_blob_publishes_charge_budget_once_and_free_cleanly() { + let cache: super::Mutex>>, usize)>> = + super::Mutex::new(None); + // Four racing publishers of the same 16-byte key must charge 16 bytes, not 64. + assert!(super::insert_cached_blob(&cache, 64, 1, vec![0xAA; 16])); + for _ in 0..3 { + assert!(!super::insert_cached_blob(&cache, 64, 1, vec![0xBB; 16])); + } + assert_eq!(cache.lock().unwrap().as_ref().unwrap().1, 16); + // Three more distinct 16-byte keys must still fit inside the 64-byte budget. + for k in 2..=4 { + assert!(super::insert_cached_blob(&cache, 64, k, vec![k as u8; 16])); + } + assert_eq!(cache.lock().unwrap().as_ref().unwrap().1, 64); + assert!(!super::insert_cached_blob(&cache, 64, 5, vec![5; 16])); + // Removing all four keys returns accounted bytes to zero. + let mut g = cache.lock().unwrap(); + let (m, total) = g.as_mut().unwrap(); + for k in 1..=4 { + let b = m.remove(&k).unwrap(); + *total -= b.len(); + } + assert_eq!(*total, 0); + } } /// Read `GetCachedBlob` from either an adopted or raw PC `ID3D12PipelineState`. @@ -5232,6 +5276,28 @@ unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option> { cached_blob_has_isa(Some(&bytes)).then_some(bytes) } +fn insert_cached_blob( + cache: &Mutex>>, usize)>>, + limit: usize, + key: K, + bytes: Vec, +) -> bool { + if bytes.is_empty() { + return false; + } + let mut g = cache.lock().unwrap(); + let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); + let std::collections::hash_map::Entry::Vacant(slot) = m.entry(key) else { + return false; + }; + if *total + bytes.len() > limit { + return false; + } + *total += bytes.len(); + slot.insert(std::sync::Arc::new(bytes)); + true +} + /// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute /// passes owned by `TwoPassPso`). unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { @@ -5239,13 +5305,7 @@ unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: return; } let Some(bytes) = read_pso_cached_blob(pso) else { return }; - let mut g = COMPUTE_BLOBS.lock().unwrap(); - let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > COMPUTE_BLOBS_MAX { - return; - } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + insert_cached_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, key, bytes); } /// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), @@ -5270,13 +5330,7 @@ unsafe fn keep_graphics_blob(key: (u64, usize), pso: *mut c_void, dxil_len: usiz return; } let Some(bytes) = read_pso_cached_blob(pso) else { return }; - let mut g = GRAPHICS_BLOBS.lock().unwrap(); - let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > GRAPHICS_BLOBS_MAX { - return; - } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + insert_cached_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, key, bytes); } /// Deterministic FNV-1a digest of every field in a translated PC graphics PSO (shaders, static @@ -5704,6 +5758,24 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } pc_topology_type(&mut copy); let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); + let debug_override = debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) || debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash); + let lib_key = (!debug_override).then(|| pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers)); + if let Some(key) = lib_key.as_deref() { + if pso_lib::try_load_graphics(this, key, ©, riid, ppv) { + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + note_pso_rs(*ppv, rs); + super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); + TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); + if super::present::trace_frame() { + PSO_SHADERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps_hash)); + } + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: graphics PSO loaded from memory-mapped pipeline library (#{})", n + 1); + } + return Some(S_OK); + } + } if debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) { copy.DepthStencilState.StencilEnable = false.into(); } @@ -5760,6 +5832,14 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const return None; } let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if let Some(key) = lib_key { + let final_key = if rect_gs.is_some() && copy.GS.pShaderBytecode.is_null() { + pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref(), None, &samplers) + } else { + key + }; + pso_lib::store_pipeline(this, &final_key, *ppv); + } note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); @@ -6482,7 +6562,24 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; - // the mesh pass and its compute pass: one turn for both + let mesh_lib_key = pso_lib::stream_key(&stream.0, mesh_rs as usize, stream.shader_bytes()); + let cs_lib_key = pso_lib::compute_key(&tp.cs, &tp.samplers, 0); + // Try loading both halves from the memory-mapped pipeline library before acquiring any cold + // compile slot so warm runs bypass `big_compile_turn` and commit waits completely. + let mesh_loaded = pso_lib::try_load_stream(this, &mesh_lib_key, &stream.0, riid, ppv); + if mesh_loaded { + let mesh_pso = *ppv; + if let Some(compute) = pso_lib::try_load_compute_raw(this, &cs_lib_key, rs, &tp.cs) { + note_pso_rs(mesh_pso, mesh_rs); + TWO_PASS.write().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (loaded from memory-mapped library)"); + } + return S_OK; + } + } + // At least one half missed the pipeline library: take one turn for the cold compile(s). let bytes = stream.shader_bytes() + tp.cs.len(); let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); @@ -6490,12 +6587,29 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: if gate { crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated, waited {} ms", waited.elapsed().as_millis()); } - let hr = driver_compile(kind, stream.shader_bytes(), false, || finish_pso(this, fs, desc.as_ptr() as *const c_void, riid, ppv)); + let hr = if mesh_loaded { + S_OK + } else { + driver_compile(kind, stream.shader_bytes(), false, || finish_pso(this, fs, desc.as_ptr() as *const c_void, riid, ppv)) + }; if hr < 0 || ppv.is_null() || (*ppv).is_null() { note_translation_error(format!("the driver rejected the mesh pipeline from the console {kind} ({hr:#x})")); return E_INVALIDARG; } let mesh_pso = *ppv; + if !mesh_loaded { + pso_lib::store_pipeline(this, &mesh_lib_key, mesh_pso); + if let Some(compute) = pso_lib::try_load_compute_raw(this, &cs_lib_key, rs, &tp.cs) { + drop(_slot); + note_pso_rs(mesh_pso, mesh_rs); + TWO_PASS.write().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if n < 5 || n % 1000 == 0 { + crate::xlog_info!("D3D12.X: pipeline from the console {kind} in two passes (compute pass loaded from memory-mapped library)"); + } + return hr; + } + } let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); @@ -6524,7 +6638,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); - if hc < 0 && ccached.is_some() { + if hc < 0 && chas_isa_blob { if driver_cache::refused(hc) { forget_compute_blob(ckey); if cfrom_disk { @@ -6539,7 +6653,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: hc = retried; cin_driver += took; } - let creused = hc >= 0 && ccached.is_some() && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; + let creused = hc >= 0 && chas_isa_blob && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; if hc >= 0 && !creused && !compute.is_null() { keep_compute_blob(ckey, compute, tp.cs.len()); if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { @@ -6556,6 +6670,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: *ppv = std::ptr::null_mut(); return E_INVALIDARG; } + pso_lib::store_pipeline(this, &cs_lib_key, compute); note_pso_rs(mesh_pso, mesh_rs); TWO_PASS.write().unwrap().get_or_insert_with(HashMap::new).insert(mesh_pso as usize, std::sync::Arc::new(TwoPassPso { compute: compute as usize, compute_rs: rs as usize, mesh_rs: mesh_rs as usize, record: tp.record, mesh_groups_per_record: tp.mesh_groups_per_record, kind })); let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); @@ -9707,6 +9822,557 @@ void main() { } +/// Flush any newly compiled pipelines in the memory-mapped `ID3D12PipelineLibrary1` to a fresh +/// generational `.plib` file (called on clean shutdown; never truncates the open mapping). +pub fn flush_pipeline_library() { + pso_lib::flush_now(); +} + +/// Runtime wiring for `pso_library::MmapPipelineLibrary`: deterministic cross-run pipeline keys, +/// kept-open per-device library lookup, load/store helpers, and debounced background generational +/// persistence (zero heap copy, never replaces an actively mapped `.plib`). +mod pso_lib { + use super::*; + use crate::hle::d3d12x::pso_library::MmapPipelineLibrary; + use std::sync::Arc; + use std::time::{Duration, Instant}; + + /// Minimum newly stored pipelines before triggering a periodic background generation save. + const SAVE_BATCH_THRESHOLD: u64 = 32; + /// Minimum spacing between periodic background saves while pipelines are streaming in. + const SAVE_MIN_INTERVAL: Duration = Duration::from_secs(15); + /// Idle delay after the last stored pipeline before flushing any remaining tail (`>= 1` dirty). + const SAVE_IDLE_FLUSH: Duration = Duration::from_secs(5); + + struct LibState { + device: usize, + lib: Option>, + stored_keys: HashSet, + hits: u64, + stores: u64, + } + + static LIB_STATE: Mutex> = Mutex::new(None); + static LAST_STORE_MS: AtomicU64 = AtomicU64::new(0); + static LAST_SAVE_MS: AtomicU64 = AtomicU64::new(0); + static SAVER_STARTED: std::sync::Once = std::sync::Once::new(); + static EPOCH: OnceLock = OnceLock::new(); + + fn now_ms() -> u64 { + EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 + } + + /// Pure save-scheduling decision (unit-testable on CPU): + /// - Save immediately when `dirty >= SAVE_BATCH_THRESHOLD` and at least `SAVE_MIN_INTERVAL` + /// elapsed since the last save. + /// - Or save any tail (`dirty > 0`) once no new pipeline has been stored for `SAVE_IDLE_FLUSH`. + pub(super) fn should_background_save(dirty: u64, now_ms: u64, last_store_ms: u64, last_save_ms: u64) -> bool { + if dirty == 0 { + return false; + } + let since_save = now_ms.saturating_sub(last_save_ms); + let since_store = now_ms.saturating_sub(last_store_ms); + (dirty >= SAVE_BATCH_THRESHOLD && since_save >= SAVE_MIN_INTERVAL.as_millis() as u64) + || (last_store_ms > 0 && since_store >= SAVE_IDLE_FLUSH.as_millis() as u64 && since_save >= SAVE_IDLE_FLUSH.as_millis() as u64) + } + + fn ensure_saver_thread() { + SAVER_STARTED.call_once(|| { + let _ = std::thread::Builder::new().name("xcl-plib-save".into()).spawn(|| loop { + std::thread::sleep(Duration::from_secs(2)); + let lib = LIB_STATE.lock().unwrap().as_ref().and_then(|s| s.lib.clone()); + let Some(lib) = lib else { continue }; + let now = now_ms(); + let dirty = lib.dirty_count(); + if should_background_save(dirty, now, LAST_STORE_MS.load(Ordering::Acquire), LAST_SAVE_MS.load(Ordering::Acquire)) { + if unsafe { lib.save_if_dirty(1) }.is_some() { + LAST_SAVE_MS.store(now_ms(), Ordering::Release); + } + } + }); + }); + } + + unsafe fn library_for(device: *mut c_void) -> Option> { + if cfg!(test) || device.is_null() || !super::super::pso_library::enabled() { + return None; + } + let dev_key = device as usize; + { + let g = LIB_STATE.lock().unwrap(); + if let Some(s) = g.as_ref().filter(|s| s.device == dev_key) { + return s.lib.clone(); + } + } + let adapter = { + let s = ADAPTER.lock().unwrap().clone(); + if s.is_empty() { "default".to_string() } else { s } + }; + let opened = ID3D12Device::from_raw_borrowed(&device) + .and_then(|dev| MmapPipelineLibrary::open_or_create(dev, &adapter)) + .map(Arc::new); + let mut g = LIB_STATE.lock().unwrap(); + if let Some(s) = g.as_ref().filter(|s| s.device == dev_key) { + return s.lib.clone(); + } + let ret = opened.clone(); + *g = Some(LibState { + device: dev_key, + lib: opened, + stored_keys: HashSet::new(), + hits: 0, + stores: 0, + }); + if ret.is_some() { + ensure_saver_thread(); + } + ret + } + + pub(super) fn flush_now() { + let lib = LIB_STATE.lock().unwrap().as_ref().and_then(|s| s.lib.clone()); + if let Some(lib) = lib { + if unsafe { lib.flush() }.is_some() { + LAST_SAVE_MS.store(now_ms(), Ordering::Release); + } + } + } + + fn fnv_feed(h: &mut u64, bytes: &[u8]) { + for &b in bytes { + *h ^= b as u64; + *h = h.wrapping_mul(0x0000_0100_0000_01b3); + } + } + + fn samplers_digest(samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> u64 { + let mut h = 0xcbf2_9ce4_8422_2325u64; + fnv_feed(&mut h, &(samplers.len() as u64).to_le_bytes()); + for (w, cmp) in samplers { + for &x in w { + fnv_feed(&mut h, &x.to_le_bytes()); + } + fnv_feed(&mut h, &[*cmp as u8]); + } + h + } + + fn abi_rs_samplers_digest(rs: usize) -> u64 { + let g = ABI_RS_SAMPLERS.read().unwrap(); + let Some(map) = g.as_ref() else { + return 0; + }; + let Some((words, _)) = map.iter().find(|(_, &v)| v == rs) else { + return 0; + }; + let mut h = 0xcbf2_9ce4_8422_2325u64; + fnv_feed(&mut h, &(words.len() as u64).to_le_bytes()); + for &w in words { + fnv_feed(&mut h, &w.to_le_bytes()); + } + h + } + + /// Deterministic cross-run key for a translated compute pipeline. + pub(super) fn compute_key(dxil: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], flags: i32) -> String { + format!( + "c-{:016x}-{:x}-{:016x}-{:x}", + crate::gpu::shader::fnv64(dxil), + dxil.len(), + samplers_digest(samplers), + flags as u32 + ) + } + + /// Deterministic cross-run key for a sanitized translated graphics pipeline (depends on effective + /// blend/rasterizer/depth-stencil state, input layout semantics, formats, shaders, and samplers). + pub(super) unsafe fn graphics_key( + copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + vs_dxil: &[u8], + ps_dxil: Option<&[u8]>, + rect_gs: Option<&[u8]>, + samplers: &[crate::gpu::recomp::pso::StaticSampler], + ) -> String { + let mut h = 0xcbf2_9ce4_8422_2325u64; + let feed_u32 = |h: &mut u64, v: u32| fnv_feed(h, &v.to_le_bytes()); + let feed_u64 = |h: &mut u64, v: u64| fnv_feed(h, &v.to_le_bytes()); + let feed_slice = |h: &mut u64, s: Option<&[u8]>| match s { + Some(b) => { + feed_u64(h, crate::gpu::shader::fnv64(b)); + feed_u64(h, b.len() as u64); + } + None => feed_u64(h, 0), + }; + feed_slice(&mut h, Some(vs_dxil)); + feed_slice(&mut h, ps_dxil); + feed_slice(&mut h, rect_gs); + feed_u64(&mut h, samplers_digest(samplers)); + + // Sanitized BlendState (effective integer-RT BlendEnable/LogicOpEnable already applied) + feed_u32(&mut h, copy.BlendState.AlphaToCoverageEnable.0 as u32); + feed_u32(&mut h, copy.BlendState.IndependentBlendEnable.0 as u32); + for rt in ©.BlendState.RenderTarget { + feed_u32(&mut h, rt.BlendEnable.0 as u32); + feed_u32(&mut h, rt.LogicOpEnable.0 as u32); + feed_u32(&mut h, rt.SrcBlend.0 as u32); + feed_u32(&mut h, rt.DestBlend.0 as u32); + feed_u32(&mut h, rt.BlendOp.0 as u32); + feed_u32(&mut h, rt.SrcBlendAlpha.0 as u32); + feed_u32(&mut h, rt.DestBlendAlpha.0 as u32); + feed_u32(&mut h, rt.BlendOpAlpha.0 as u32); + feed_u32(&mut h, rt.LogicOp.0 as u32); + fnv_feed(&mut h, &[rt.RenderTargetWriteMask]); + } + feed_u32(&mut h, copy.SampleMask); + + // RasterizerState + let r = ©.RasterizerState; + feed_u32(&mut h, r.FillMode.0 as u32); + feed_u32(&mut h, r.CullMode.0 as u32); + feed_u32(&mut h, r.FrontCounterClockwise.0 as u32); + feed_u32(&mut h, r.DepthBias as u32); + feed_u32(&mut h, r.DepthBiasClamp.to_bits()); + feed_u32(&mut h, r.SlopeScaledDepthBias.to_bits()); + feed_u32(&mut h, r.DepthClipEnable.0 as u32); + feed_u32(&mut h, r.MultisampleEnable.0 as u32); + feed_u32(&mut h, r.AntialiasedLineEnable.0 as u32); + feed_u32(&mut h, r.ForcedSampleCount); + feed_u32(&mut h, r.ConservativeRaster.0 as u32); + + // DepthStencilState + let ds = ©.DepthStencilState; + feed_u32(&mut h, ds.DepthEnable.0 as u32); + feed_u32(&mut h, ds.DepthWriteMask.0 as u32); + feed_u32(&mut h, ds.DepthFunc.0 as u32); + feed_u32(&mut h, ds.StencilEnable.0 as u32); + fnv_feed(&mut h, &[ds.StencilReadMask, ds.StencilWriteMask]); + for face in [&ds.FrontFace, &ds.BackFace] { + feed_u32(&mut h, face.StencilFailOp.0 as u32); + feed_u32(&mut h, face.StencilDepthFailOp.0 as u32); + feed_u32(&mut h, face.StencilPassOp.0 as u32); + feed_u32(&mut h, face.StencilFunc.0 as u32); + } + + // InputLayout + let il = ©.InputLayout; + feed_u32(&mut h, il.NumElements); + if il.NumElements > 0 && !il.pInputElementDescs.is_null() { + for e in std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) { + if !e.SemanticName.0.is_null() { + let s = std::ffi::CStr::from_ptr(e.SemanticName.0 as *const std::ffi::c_char); + fnv_feed(&mut h, s.to_bytes_with_nul()); + } else { + fnv_feed(&mut h, &[0]); + } + feed_u32(&mut h, e.SemanticIndex); + feed_u32(&mut h, e.Format.0 as u32); + feed_u32(&mut h, e.InputSlot); + feed_u32(&mut h, e.AlignedByteOffset); + feed_u32(&mut h, e.InputSlotClass.0 as u32); + feed_u32(&mut h, e.InstanceDataStepRate); + } + } + + feed_u32(&mut h, copy.IBStripCutValue.0 as u32); + feed_u32(&mut h, copy.PrimitiveTopologyType.0 as u32); + feed_u32(&mut h, copy.NumRenderTargets); + for f in ©.RTVFormats { + feed_u32(&mut h, f.0 as u32); + } + feed_u32(&mut h, copy.DSVFormat.0 as u32); + feed_u32(&mut h, copy.SampleDesc.Count); + feed_u32(&mut h, copy.SampleDesc.Quality); + feed_u32(&mut h, copy.NodeMask); + feed_u32(&mut h, copy.Flags.0 as u32); + + let total = vs_dxil.len() + ps_dxil.map_or(0, <[u8]>::len) + rect_gs.map_or(0, <[u8]>::len); + format!("g-{h:016x}-{total:x}") + } + + /// Deterministic cross-run key for a translated mesh/GS pipeline state stream: hashes shader + /// bytecodes by content, root signature by static-sampler digest, and pointer-bearing subobjects + /// (`INPUT_LAYOUT`, `STREAM_OUTPUT`, `VIEW_INSTANCING`) by pointed-to content (never raw pointers). + pub(super) unsafe fn stream_key(stream_bytes: &[u8], mesh_rs: usize, shader_bytes: usize) -> String { + let mut h = 0xcbf2_9ce4_8422_2325u64; + fnv_feed(&mut h, &abi_rs_samplers_digest(mesh_rs).to_le_bytes()); + if let Some(subs) = stream_subobjects(stream_bytes) { + for (ty, payload) in subs { + fnv_feed(&mut h, &ty.to_le_bytes()); + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE.0 as u32 + || ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO.0 as u32 + { + continue; + } + if SHADER_SUBOBJECTS.iter().any(|t| t.0 as u32 == ty) { + if let Some(code) = payload_shader(payload) { + fnv_feed(&mut h, &crate::gpu::shader::fnv64(code).to_le_bytes()); + fnv_feed(&mut h, &(code.len() as u64).to_le_bytes()); + } else { + fnv_feed(&mut h, &0u64.to_le_bytes()); + } + continue; + } + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32 + && payload.len() >= std::mem::size_of::() + { + let il = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_INPUT_LAYOUT_DESC); + fnv_feed(&mut h, &il.NumElements.to_le_bytes()); + if il.NumElements > 0 && !il.pInputElementDescs.is_null() { + for e in std::slice::from_raw_parts(il.pInputElementDescs, il.NumElements as usize) { + if !e.SemanticName.0.is_null() { + fnv_feed(&mut h, std::ffi::CStr::from_ptr(e.SemanticName.0 as *const i8).to_bytes()); + } + fnv_feed(&mut h, &[0u8]); + fnv_feed(&mut h, &e.SemanticIndex.to_le_bytes()); + fnv_feed(&mut h, &e.Format.0.to_le_bytes()); + fnv_feed(&mut h, &e.InputSlot.to_le_bytes()); + fnv_feed(&mut h, &e.AlignedByteOffset.to_le_bytes()); + fnv_feed(&mut h, &e.InputSlotClass.0.to_le_bytes()); + fnv_feed(&mut h, &e.InstanceDataStepRate.to_le_bytes()); + } + } + continue; + } + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT.0 as u32 + && payload.len() >= std::mem::size_of::() + { + let so = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_STREAM_OUTPUT_DESC); + fnv_feed(&mut h, &so.NumEntries.to_le_bytes()); + fnv_feed(&mut h, &so.NumStrides.to_le_bytes()); + fnv_feed(&mut h, &so.RasterizedStream.to_le_bytes()); + if so.NumEntries > 0 && !so.pSODeclaration.is_null() { + for d in std::slice::from_raw_parts(so.pSODeclaration, so.NumEntries as usize) { + fnv_feed(&mut h, &d.Stream.to_le_bytes()); + if !d.SemanticName.0.is_null() { + fnv_feed(&mut h, std::ffi::CStr::from_ptr(d.SemanticName.0 as *const i8).to_bytes()); + } + fnv_feed(&mut h, &[0u8, d.StartComponent, d.ComponentCount, d.OutputSlot]); + fnv_feed(&mut h, &d.SemanticIndex.to_le_bytes()); + } + } + if so.NumStrides > 0 && !so.pBufferStrides.is_null() { + for &s in std::slice::from_raw_parts(so.pBufferStrides, so.NumStrides as usize) { + fnv_feed(&mut h, &s.to_le_bytes()); + } + } + continue; + } + if ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING.0 as u32 + && payload.len() >= std::mem::size_of::() + { + let vi = std::ptr::read_unaligned(payload.as_ptr() as *const D3D12_VIEW_INSTANCING_DESC); + fnv_feed(&mut h, &vi.ViewInstanceCount.to_le_bytes()); + fnv_feed(&mut h, &vi.Flags.0.to_le_bytes()); + if vi.ViewInstanceCount > 0 && !vi.pViewInstanceLocations.is_null() { + for l in std::slice::from_raw_parts(vi.pViewInstanceLocations, vi.ViewInstanceCount as usize) { + fnv_feed(&mut h, &l.ViewportArrayIndex.to_le_bytes()); + fnv_feed(&mut h, &l.RenderTargetArrayIndex.to_le_bytes()); + } + } + continue; + } + fnv_feed(&mut h, payload); + } + } + format!("s-{h:016x}-{shader_bytes:x}") + } + + unsafe fn deliver_adopted(pso: ID3D12PipelineState, _riid: *const GUID, ppv: *mut *mut c_void) -> bool { + if ppv.is_null() { + return false; + } + // `pso` is already an `ID3D12PipelineState` matching `pc_iid(Kind::PipelineState)`; do not + // pass console IIDs through PC COM `QueryInterface`. + let out = pso.into_raw(); + adopt(out, Kind::PipelineState); + *ppv = out; + true + } + + fn note_hit() { + if let Some(s) = LIB_STATE.lock().unwrap().as_mut() { + s.hits += 1; + if s.hits == 1 || s.hits % 500 == 0 { + crate::xlog_info!("D3D12.X: memory-mapped pipeline library hits: {}", s.hits); + } + } + } + + pub(super) unsafe fn try_load_compute( + device: *mut c_void, + key: &str, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + riid: *const GUID, + ppv: *mut *mut c_void, + ) -> bool { + let Some(lib) = library_for(device) else { return false }; + let Some(pso) = lib.load_compute(key, desc) else { return false }; + if deliver_adopted(pso, riid, ppv) { + note_hit(); + true + } else { + false + } + } + + pub(super) unsafe fn try_load_compute_raw( + device: *mut c_void, + key: &str, + rs: *mut c_void, + cs: &[u8], + ) -> Option<*mut c_void> { + let lib = library_for(device)?; + let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); + cdesc.CS = bytecode(cs); + let pso = lib.load_compute(key, &cdesc)?; + note_hit(); + Some(pso.into_raw()) + } + + pub(super) unsafe fn try_load_graphics( + device: *mut c_void, + key: &str, + desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, + riid: *const GUID, + ppv: *mut *mut c_void, + ) -> bool { + let Some(lib) = library_for(device) else { return false }; + let Some(pso) = lib.load_graphics(key, desc) else { return false }; + if deliver_adopted(pso, riid, ppv) { + note_hit(); + true + } else { + false + } + } + + pub(super) unsafe fn try_load_stream( + device: *mut c_void, + key: &str, + stream_bytes: &[u8], + riid: *const GUID, + ppv: *mut *mut c_void, + ) -> bool { + let Some(lib) = library_for(device) else { return false }; + let sdesc = D3D12_PIPELINE_STATE_STREAM_DESC { + SizeInBytes: stream_bytes.len(), + pPipelineStateSubobjectStream: stream_bytes.as_ptr() as *mut c_void, + }; + let Some(pso) = lib.load_stream(key, &sdesc) else { return false }; + if deliver_adopted(pso, riid, ppv) { + note_hit(); + true + } else { + false + } + } + + pub(super) unsafe fn store_pipeline(device: *mut c_void, key: &str, pso_raw: *mut c_void) { + if pso_raw.is_null() { + return; + } + let Some(lib) = library_for(device) else { return }; + { + let mut g = LIB_STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if !s.stored_keys.insert(key.to_string()) { + return; + } + } + let Some(pso) = ID3D12PipelineState::from_raw_borrowed(&pso_raw) else { return }; + if lib.store(key, pso) { + LAST_STORE_MS.store(now_ms(), Ordering::Release); + if let Some(s) = LIB_STATE.lock().unwrap().as_mut() { + s.stores += 1; + } + } + } + + #[cfg(test)] + mod tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + #[test] + fn pipeline_library_keys_are_deterministic_and_sensitive_to_effective_state() { + let s1 = [([1u32, 2, 3, 4], false)]; + let s2 = [([1u32, 2, 3, 4], true)]; + let ck1 = compute_key(b"dxil-cs", &s1, 0); + assert_eq!(ck1, compute_key(b"dxil-cs", &s1, 0)); + assert_ne!(ck1, compute_key(b"dxil-cs", &s2, 0), "sampler change must change key"); + assert_ne!(ck1, compute_key(b"dxil-cs", &s1, 1), "flags change must change key"); + assert_ne!(ck1, compute_key(b"dxil-c2", &s1, 0), "shader change must change key"); + + // Graphics key reflects pc_topology_type's normalized topology and PC target format. + unsafe { + let mut g1: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::mem::zeroed(); + g1.NumRenderTargets = 1; + g1.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; + let mut g2 = g1.clone(); + g2.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + assert_ne!( + graphics_key(&g1, b"vs", Some(b"ps"), None, &[]), + graphics_key(&g2, b"vs", Some(b"ps"), None, &[]) + ); + pc_topology_type(&mut g1); + pc_topology_type(&mut g2); + assert_eq!( + graphics_key(&g1, b"vs", Some(b"ps"), None, &[]), + graphics_key(&g2, b"vs", Some(b"ps"), None, &[]), + "normalized graphics PSOs must share the same library key" + ); + } + + // Stream key hashes shader content, not pointer addresses. + unsafe { + let ms_a = b"mesh-shader-dxil-payload".to_vec(); + let ms_b = ms_a.clone(); + assert_ne!(ms_a.as_ptr(), ms_b.as_ptr()); + let ps = b"pixel-shader-dxil".to_vec(); + let build = |ms: &[u8], rs_ptr: usize| { + let mut out = StreamOut::default(); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &rs_ptr); + out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, ms); + out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &ps); + let rt = D3D12_RT_FORMAT_ARRAY { + RTFormats: [DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN], + NumRenderTargets: 1, + }; + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, &rt); + out + }; + let sa = build(&ms_a, 0x1000); + let sb = build(&ms_b, 0x2000); + assert_eq!( + stream_key(&sa.0, 0x1000, sa.shader_bytes()), + stream_key(&sb.0, 0x2000, sb.shader_bytes()), + "stream key must depend on shader content, not transient pointers" + ); + let ms_diff = b"mesh-shader-dxil-DIFF!!!".to_vec(); + let sc = build(&ms_diff, 0x1000); + assert_ne!( + stream_key(&sa.0, 0x1000, sa.shader_bytes()), + stream_key(&sc.0, 0x1000, sc.shader_bytes()), + ); + } + } + + #[test] + fn background_save_scheduler_batches_bursts_and_flushes_idle_tail() { + assert!(!should_background_save(0, 60_000, 10_000, 0)); + // Below batch threshold during active burst (< 5s idle) -> wait. + assert!(!should_background_save(10, 12_000, 10_000, 0)); + // At batch threshold (>= 32) but < 15s since last save -> wait. + assert!(!should_background_save(32, 20_000, 19_000, 10_000)); + // At batch threshold (>= 32) and >= 15s since last save -> save! + assert!(should_background_save(32, 25_000, 24_000, 10_000)); + // Small tail (1 dirty) after 5s idle since last store & save -> flush! + assert!(should_background_save(1, 30_000, 25_000, 20_000)); + } + } +} + #[cfg(test)] mod pso_release_tests { use super::*; diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 07aba13789..f5e673bf80 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -124,6 +124,7 @@ pub fn host_main(boot_path: &Path) -> i32 { std::thread::sleep(std::time::Duration::from_secs(secs)); let (shown, presented) = crate::hle::d3d12x::present::counters(); crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({shown} frames shown, {presented} PresentX calls)"); + crate::hle::d3d12x::real::flush_pipeline_library(); crate::report::write_final(None); crate::log::flush(); crate::hle::d3d12x::real::end_title(0); @@ -168,6 +169,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::report::write_final(None); let code = crate::loader::run_main(&main); crate::xlog_info!("game entry point returned code {code}"); + crate::hle::d3d12x::real::flush_pipeline_library(); crate::report::write_final(None); crate::log::flush(); code as i32 From 5aeb661b7db302d0d2af6d211d84c0e3c585f838 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:44:15 +0100 Subject: [PATCH 112/258] D3D12.X: never skip non-RT producer compute PSOs and throttle under low commit In the warm-.plib live run (a87b439e), heavy_compute marked every >= 24 KiB console compute shader as spared, causing resolve_wait_for to return the untranslated stand-in and skip 33+ memory-writing producer dispatches (including 0xc3008970 at t=157.996s and 32 more at t=166.458s) and indirect compute dispatches before the t=181.687s GPU VA fault. - Restrict spared/skippable async compute builds strictly to BVH RT traversal shaders (uses_bvh_intersect with XCL_RT_GATE) and pure image-only shaders (big_and_image_only: zero buffer/global/flat/scratch/GDS writes). - Keep heavy_compute deprioritized on xcl-pso-* workers (so BIG_COMPILES gating still caps concurrent driver compiles), and have resolve_wait_for enqueue + wait on the worker instead of compiling ungated on title threads or skipping the producer dispatch. - Add GlobalMemoryStatusEx commit-headroom throttling in pso_async (XCL_PSO_MEM_THROTTLE=0 to disable): pause speculative xcl-pso-pre-* preload below 4 GiB free commit and cap concurrent top-level worker builds to <= 2 below 4 GiB and 1 below 2 GiB (never 0). - Add unit tests for worker-gated heavy producer wait and commit-headroom throttling. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 169 +++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 9 +- 2 files changed, 164 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index c4f87572ed..5ab2374b15 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -388,12 +388,93 @@ fn enqueue(p: Arc) { ); } +/// Commit-headroom thresholds (`GlobalMemoryStatusEx::ullAvailPageFile`) for throttling background +/// PSO compilation under memory pressure (`XCL_PSO_MEM_THROTTLE=0`: off). +const PRELOAD_PAUSE_COMMIT: u64 = 4 << 30; +const WORKER_CAP_2_COMMIT: u64 = 4 << 30; +const WORKER_CAP_1_COMMIT: u64 = 2 << 30; + +fn mem_throttle_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| !cfg!(test) && !std::env::var("XCL_PSO_MEM_THROTTLE").is_ok_and(|v| v.trim() == "0")) +} + +fn avail_commit_bytes() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPageFile) +} + +/// Maximum concurrent top-level PSO worker builds allowed for the current available commit bytes: +/// `< 2 GiB` -> 1 worker (never 0, no deadlock), `< 4 GiB` -> at most 2, otherwise `max_workers`. +fn worker_cap_for_commit(avail_commit: Option, max_workers: usize) -> usize { + let max_workers = max_workers.max(1); + match avail_commit { + Some(avail) if avail < WORKER_CAP_1_COMMIT => 1, + Some(avail) if avail < WORKER_CAP_2_COMMIT => max_workers.min(2), + _ => max_workers, + } +} + +/// Pause speculative `xcl-pso-pre-*` preload builds while available commit is below 4 GiB. +fn should_pause_preload(avail_commit: Option) -> bool { + avail_commit.is_some_and(|avail| avail < PRELOAD_PAUSE_COMMIT) +} + +struct ActiveWorkerGate { + active: Mutex, + cv: Condvar, +} + +static ACTIVE_WORKERS: ActiveWorkerGate = ActiveWorkerGate { + active: Mutex::new(0), + cv: Condvar::new(), +}; + +struct ActiveWorkerGuard; + +impl Drop for ActiveWorkerGuard { + fn drop(&mut self) { + let mut n = ACTIVE_WORKERS.active.lock().unwrap(); + *n = n.saturating_sub(1); + ACTIVE_WORKERS.cv.notify_all(); + } +} + +fn acquire_worker_slot(max_workers: usize) -> ActiveWorkerGuard { + let mut n = ACTIVE_WORKERS.active.lock().unwrap(); + loop { + let avail = mem_throttle_enabled().then(avail_commit_bytes).flatten(); + let cap = worker_cap_for_commit(avail, max_workers); + if *n < cap { + if cap < max_workers { + static LOGGED: std::sync::Once = std::sync::Once::new(); + LOGGED.call_once(|| { + crate::xlog_info!( + "D3D12.X: throttling PSO workers to {cap} under low commit headroom ({} MiB free)", + avail.unwrap_or(0) >> 20 + ); + }); + } + *n += 1; + return ActiveWorkerGuard; + } + n = ACTIVE_WORKERS.cv.wait_timeout(n, std::time::Duration::from_millis(50)).unwrap().0; + } +} + fn build_queued(p: &Arc) { // (released by the title meanwhile) if p.orphan.load(Ordering::Acquire) { drop_unstarted_job(p); return; } + let _slot = acquire_worker_slot(crate::gpu::recomp::dxc::compile_threads()); + if p.orphan.load(Ordering::Acquire) { + drop_unstarted_job(p); + return; + } // (None: a bind took it and builds it itself) let job = p.job.lock().unwrap().take(); if let Some(job) = job { @@ -616,6 +697,24 @@ fn preload() -> Option<&'static Preload> { drop_unstarted_job(&p); continue; } + // Pause speculative preload under low commit headroom (< 4 GiB) unless a bind + // actively wants this pipeline; leave `p.job` untouched so binds can take it. + while mem_throttle_enabled() + && !p.orphan.load(Ordering::Acquire) + && !p.demand.lock().unwrap().wanted + && p.job.lock().unwrap().is_some() + && should_pause_preload(avail_commit_bytes()) + { + static PAUSED_LOG: std::sync::Once = std::sync::Once::new(); + PAUSED_LOG.call_once(|| { + crate::xlog_info!("D3D12.X: pausing speculative PSO preload under low commit headroom (< 4 GiB)"); + }); + std::thread::sleep(std::time::Duration::from_millis(50)); + } + if p.orphan.load(Ordering::Acquire) { + drop_unstarted_job(&p); + continue; + } // (None: a bind took it and builds it itself) let job = p.job.lock().unwrap().take(); if let Some(job) = job { @@ -1158,9 +1257,18 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { if let Some(budget) = budget { return resolve_within(&p, pso, budget); } - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - complete(&p, job()); + if p.deprioritized.load(Ordering::Acquire) && !building_here() { + // Heavy non-RT producer compute PSO: compile on an `xcl-pso-*` worker (where `BIG_COMPILES` + // gating bounds concurrent driver compiles) and wait until ready so the producer dispatch + // is NEVER skipped. + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); + } + } else { + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + complete(&p, job()); + } } p.want(); let mut done = p.done.lock().unwrap(); @@ -1242,13 +1350,14 @@ pub fn async_heavy_compute() -> bool { *ON.get_or_init(|| !std::env::var("XCL_ASYNC_HEAVY_COMPUTE").is_ok_and(|v| v.trim() == "0")) } -/// The compute pipeline behind stand-in `standin` is a heavyweight shader (`>= 512 KiB` DXIL): -/// never compile it synchronously on title threads — queue it at lower worker priority behind -/// normal/MS PSOs and return the stand-in until background `BIG_COMPILES` finishes it. +/// The compute pipeline behind stand-in `standin` is a heavyweight shader (`>= 24 KiB` console +/// code): never compile it synchronously on title threads — queue it deprioritized behind +/// normal/MS PSOs so `xcl-pso-*` workers compile it under `BIG_COMPILES` gating. Does NOT mark +/// `spared`, so non-RT producer compute shaders that write memory are NEVER skipped (call +/// `image_only` or `bvh_traversal` separately only for pure image-writing or BVH RT shaders). pub fn heavy_compute(standin: usize) { if let Some(p) = entry(standin) { p.deprioritized.store(true, Ordering::Release); - p.spared.store(true, Ordering::Release); } } @@ -1261,9 +1370,9 @@ pub fn bvh_traversal(standin: usize) { } } -/// `resolve_wait` for a pipeline binds do not wait for (`image_only`): the real one once built, -/// else the stand-in, with the build sent to the workers. Nobody waits, so the build is not -/// `wanted`: a big one takes its turn among the driver's compiles and waits for free commit. +/// `resolve_wait` for a pipeline binds do not wait for (`image_only` or `bvh_traversal`): the real +/// one once built, else the stand-in, with the build sent to the workers. Nobody waits, so the +/// build is not `wanted`: a big one takes its turn among the driver's compiles and waits for free commit. fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.real.load(Ordering::Acquire) { 0 => { @@ -1274,7 +1383,12 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); if n < 16 || n.is_power_of_two() { - crate::xlog_info!("D3D12.X: a compute program that writes only images is still being built: its dispatches are left out until it is ({} so far)", n + 1); + let kind = if p.bvh_traversal.load(Ordering::Acquire) { + "a BVH ray-tracing compute program" + } else { + "a compute program that writes only images" + }; + crate::xlog_info!("D3D12.X: {kind} is still being built: its dispatches are left out until it is ({} so far)", n + 1); } } p.stand(pso) @@ -1393,4 +1507,37 @@ mod pso_queue_tests { } assert_eq!(*order.lock().unwrap(), ["promoted", "wanted", "bg1", "heavy1", "heavy2"]); } + + #[test] + fn heavy_compute_producer_runs_on_worker_and_is_never_skipped() { + let standin = 0x7E57_B0C1usize; + let (tx, rx) = mpsc::channel(); + submit_lazy(standin, true, Box::new(move || { + let on_worker = std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso-")); + let _ = tx.send(on_worker); + 0x5C5C + }), 0); + heavy_compute(standin); + // Must wait for the worker and return the real PSO (never skip a memory-writing producer). + assert_eq!(resolve_wait_for(standin, None), 0x5C5C); + assert!(rx.recv_timeout(std::time::Duration::from_secs(10)).expect("ran on worker"), "heavy producer must compile on xcl-pso worker"); + let _ = released(standin); + } + + #[test] + fn commit_headroom_throttles_workers_and_pauses_preload() { + assert_eq!(worker_cap_for_commit(None, 8), 8); + assert_eq!(worker_cap_for_commit(Some(6 << 30), 8), 8); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT), 8), 8); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT - 1), 8), 2); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_1_COMMIT), 8), 2); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_1_COMMIT - 1), 8), 1); + assert_eq!(worker_cap_for_commit(Some(0), 8), 1, "must never drop to 0 workers"); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT - 1), 1), 1); + + assert!(!should_pause_preload(None)); + assert!(!should_pause_preload(Some(PRELOAD_PAUSE_COMMIT))); + assert!(should_pause_preload(Some(PRELOAD_PAUSE_COMMIT - 1))); + assert!(should_pause_preload(Some(0))); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ed34d52818..a6b67b2ff7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6176,10 +6176,10 @@ unsafe fn go_background( let dev = Dev(this as usize, f as usize); let key = owned.shaders_key(); // a big compute program that writes nothing but images: binds can go on without it - let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); + let big_image_only = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); + let image_only = big_image_only && super::pso_async::image_skip(); let bvh_trav = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::uses_bvh_intersect(b))); let heavy_compute = compute - && bvh_gate_enabled() && super::pso_async::async_heavy_compute() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::compute_code_len(b).is_some_and(|n| n >= crate::gpu::effects::HEAVY_CODE))); if compute { @@ -6208,7 +6208,10 @@ unsafe fn go_background( if driver != 0 { super::pso_async::shared(*ppv as usize, driver); } - if image_only { + // Only pure image-writing compute shaders (zero buffer/global/GDS writes) or BVH RT traversal + // shaders may ever be spared/skipped while building. Heavy producer compute shaders that write + // memory are deprioritized onto gated workers (`heavy_compute`) but NEVER skipped. + if image_only || (heavy_compute && big_image_only) { super::pso_async::image_only(*ppv as usize); } if bvh_trav && bvh_gate_enabled() { From 77453544660f8269a69f35cd6d57b1a9e24a8e37 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:49:29 +0100 Subject: [PATCH 113/258] D3D12.X: run indirect split compute via chain and cap scratch atomically Indirect dispatches of split compute pipelines previously fell back to the lazily-built whole form (whole_nonblocking), skipping them while background compilation finished (15 skipped indirect dispatches in world load). Separately, dispatch_chain::scratch_for checked LIVE against the 384 MiB scratch_total() cap before creating the GPU buffer and updated LIVE only afterward, letting concurrent recording threads overshoot the total scratch budget under load. Port the GPU slicer and chained indirect execution path (#2404) onto amd-dev with AMD RDNA4 safety improvements and atomic scratch admission: - Add pso::slab_count, chain_command_signature, chain_commands_buffer, record_slicer, and record_dispatch_chain_indirect (runtime helpers only; no translator or DXIL cache-key changes). - Align record_slicer root SRVs (t0/t1) down to 256-byte bases with byte offsets in b0 (rejecting <256 or unaligned addresses), compile via dxc::compile_cached, and label xcl dispatch_chain_slicer for DRED. - Transition guard_dispatch_args and prelude scratch buffers to INDIRECT_ARGUMENT | NON_PIXEL_SHADER_RESOURCE so record_slicer reads single-command indirect args from the committed, clamped, >65535-folded scratch buffer while preserving preset_io (IO_GROUP_LIMIT), resetting pc_abi_cs around slicer/chain binds, and keeping non-blocking whole_nonblocking fallback for bundles, non-dispatch-only signatures, or scratch OOM. - Atomically reserve bytes from LIVE via reserve_scratch_bytes / ScratchReservation before calling scratch_buffer, shrinking on TryMinimal OOM fallback and releasing on failure or Scratch::drop. - Add unit tests for slab_count/align_slicer_srv, indirect_rounds, and multi-threaded concurrent scratch admission. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/recomp/pso.rs | 285 +++++++++++++++ crates/xcl/src/hle/d3d12x/bind.rs | 246 +++++++++++-- crates/xcl/src/hle/d3d12x/device_x.rs | 3 + crates/xcl/src/hle/d3d12x/list_x.rs | 5 + .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 345 +++++++++++++++++- 5 files changed, 833 insertions(+), 51 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 5c2e2b76e2..6164cca0bf 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -1323,6 +1323,18 @@ pub(crate) fn dispatch_slabs(grid: [u32; 3], most: u64) -> Vec<([u32; 3], [u32; out } +/// How many slabs `dispatch_slabs` makes of `grid` (without making them) +pub(crate) fn slab_count(grid: [u32; 3], most: u64) -> u64 { + let [x, y, z] = grid.map(u64::from); + if x * y * z == 0 { + return 0; + } + let sx = x.min(most.max(1)); + let sy = if sx == x { y.min((most / x).max(1)) } else { 1 }; + let sz = if sx == x && sy == y { z.min((most / (x * y)).max(1)) } else { 1 }; + x.div_ceil(sx) * y.div_ceil(sy) * z.div_ceil(sz) +} + /// A chain's dispatch of `grid` groups, `most` of them at once (`dispatch_slabs`). `used`: the /// list (or one before it) has used `scratch`. pub(crate) unsafe fn record_dispatch_chain<'a>( @@ -1349,6 +1361,271 @@ pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[Stat abi_signature(dev, false, samplers, true) } +/// Bytes of one command of a chain's ExecuteIndirect (`chain_command_signature`): the eight +/// root constants of `record_dispatch_chain` and the slab's Dispatch. +pub(crate) const CHAIN_COMMAND_BYTES: u32 = 44; + +/// The command signature of a chain's ExecuteIndirect on the chain's root signature `rs`. +pub(crate) fn chain_command_signature(dev: &ID3D12Device, rs: &ID3D12RootSignature) -> Result { + let args = [ + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT, + Anonymous: D3D12_INDIRECT_ARGUMENT_DESC_0 { + Constant: D3D12_INDIRECT_ARGUMENT_DESC_0_1 { + RootParameterIndex: 7, + DestOffsetIn32BitValues: 0, + Num32BitValuesToSet: 8, + }, + }, + }, + D3D12_INDIRECT_ARGUMENT_DESC { + Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, + ..Default::default() + }, + ]; + let desc = D3D12_COMMAND_SIGNATURE_DESC { + ByteStride: CHAIN_COMMAND_BYTES, + NumArgumentDescs: 2, + pArgumentDescs: args.as_ptr(), + NodeMask: 0, + }; + let mut sig: Option = None; + unsafe { dev.CreateCommandSignature(&desc, rs, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?; + sig.ok_or_else(|| "CreateCommandSignature".into()) +} + +/// One thread that turns a title's Dispatch arguments into a chain's commands: each command's +/// groups in the slabs of `dispatch_slabs`, one slab a round, `rounds` rounds of `pieces` +/// commands (`CHAIN_COMMAND_BYTES` each; unused rounds dispatch nothing). After them +/// (`chain_predicate_offset`): a 64-bit predicate, 1 when the rounds did not hold every slab, +/// and the slabs there were (at most 2^32 - 256). +/// +/// `args_off` and `count_off` carry sub-256-byte offsets so `t0`/`t1` root SRVs are always +/// 256-byte aligned (D3D12 root raw SRVs require >= 16-byte alignment). +const SLICER: &str = r#" +#define RS "RootConstants(num32BitConstants=8, b0), SRV(t0), SRV(t1), UAV(u0)" +cbuffer C : register(b0) { uint rounds; uint most; uint commands; uint stride; uint counted; uint pieces; uint args_off; uint count_off; }; +ByteAddressBuffer args : register(t0); +ByteAddressBuffer count : register(t1); +RWByteAddressBuffer cmds : register(u0); +void put(uint r, uint3 n, uint3 o) { + for (uint i = 0; i < pieces; i++) { + uint at = (r * pieces + i) * 44; + cmds.Store4(at, uint4(n, i)); + cmds.Store4(at + 16, uint4(o, 0)); + cmds.Store3(at + 32, n); + } +} +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint n = counted != 0 ? min(count.Load(count_off), commands) : commands; + uint r = 0; + bool partial = false; + float slabs = 0; + for (uint k = 0; k < n; k++) { + uint3 g = min(args.Load3(args_off + k * stride), 65535); + if (any(g == 0)) continue; + uint3 s; + s.x = min(g.x, max(most, 1)); + s.y = s.x == g.x ? min(g.y, max(most / g.x, 1)) : 1; + s.z = s.x == g.x && s.y == g.y ? min(g.z, max(most / g.x / g.y, 1)) : 1; + uint3 c = (g + s - 1) / s; + float need = (float)c.x * c.y * c.z; + slabs += need; + uint first = r; + for (uint oz = 0; oz < g.z && r < rounds; oz += s.z) + for (uint oy = 0; oy < g.y && r < rounds; oy += s.y) + for (uint ox = 0; ox < g.x && r < rounds; ox += s.x) { + uint3 o = uint3(ox, oy, oz); + put(r++, min(s, g - o), o); + } + partial = partial || (float)(r - first) < need; + } + for (; r < rounds; r++) put(r, 0, 0); + cmds.Store4((rounds * pieces * 44 + 7) & ~7u, uint4(partial ? 1 : 0, 0, (uint)min(slabs, 4294967040.0), 0)); +} +"#; + +/// Where the slicer's predicate is in a chain's command buffer +pub(crate) fn chain_predicate_offset(rounds: u32, pieces: u32) -> u64 { + u64::from(rounds * pieces * CHAIN_COMMAND_BYTES).next_multiple_of(8) +} + +/// Bytes of a chain's command buffer (`SLICER`) +pub(crate) fn chain_commands_bytes(rounds: u32, pieces: u32) -> u64 { + chain_predicate_offset(rounds, pieces) + 16 +} + +/// The slicer's root signature and pipeline (made once per device). +fn slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static MADE: Mutex> = Mutex::new(None); + let mut g = MADE.lock().unwrap(); + if let Some((_, rs, pso)) = g.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) { + return Ok((rs.clone(), pso.clone())); + } + let dxil = super::dxc::compile_cached(SLICER, "main", "cs_6_0")?.0; + unsafe { + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("slicer root signature: {e}"))?; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: dxil.as_ptr().cast(), + BytecodeLength: dxil.len(), + }, + ..Default::default() + }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).map_err(|e| format!("slicer pipeline: {e}"))?; + let _ = pso.SetName(windows::core::w!("xcl dispatch_chain_slicer")); + *g = Some((windows::core::Interface::as_raw(dev) as usize, rs.clone(), pso.clone())); + Ok((rs, pso)) + } +} + +/// A chain's command buffer (`chain_commands_bytes`) in the UNORDERED_ACCESS state: the slicer +/// writes it, ExecuteIndirect and predication read it, and the CPU reads the slabs back. +pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32, pieces: u32) -> Option { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: chain_commands_bytes(rounds, pieces), + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + CreationNodeMask: 1, + VisibleNodeMask: 1, + }; + let mut resource = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut resource).ok()?; + resource +} + +/// Align a GPU virtual address down to a 256-byte root SRV base and its 4-byte-aligned offset. +fn align_slicer_srv(va: u64, what: &str) -> Result<(u64, u32), String> { + if va < 256 || va % 4 != 0 { + return Err(format!("invalid indirect {what} address {va:#x}")); + } + Ok((va & !255, (va & 255) as u32)) +} + +/// The slicer's dispatch: the title's `commands` commands of `stride` bytes at `args` (GPU +/// address; the count at `count` when there is one) into `out` (`chain_commands_bytes`, in the +/// UNORDERED_ACCESS state, left in INDIRECT_ARGUMENT). It sets the list's compute root signature: +/// the caller binds its own again. Returns the raw slicer PSO address for DRED labeling. +#[allow(clippy::too_many_arguments)] +pub(crate) unsafe fn record_slicer( + list: &ID3D12GraphicsCommandList, + args: u64, + stride: u32, + commands: u32, + count: Option, + rounds: u32, + most: u64, + pieces: u32, + out: &ID3D12Resource, +) -> Result { + let (args_base, args_off) = align_slicer_srv(args, "args")?; + let (cnt_base, cnt_off) = match count { + Some(c) => align_slicer_srv(c, "count")?, + None => (args_base, 0), + }; + let dev: ID3D12Device = { + let mut d: Option = None; + list.GetDevice(&mut d).map_err(|e| e.to_string())?; + d.ok_or("device")? + }; + let (rs, pso) = slicer(&dev)?; + let constants = [ + rounds, + most.min(u64::from(u32::MAX)) as u32, + commands, + stride, + count.is_some() as u32, + pieces, + args_off, + cnt_off, + ]; + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, constants.len() as u32, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, args_base); + list.SetComputeRootShaderResourceView(2, cnt_base); + list.SetComputeRootUnorderedAccessView(3, out.GetGPUVirtualAddress()); + // after the dispatches that wrote the arguments + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(out), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + }), + }, + }]); + Ok(windows::core::Interface::as_raw(&pso) as usize) +} + +/// `record_dispatch_chain` from the slicer's commands in `commands` (`rounds` rounds), after the +/// six common root views have been bound. With `predicated`, the pieces run only when the rounds +/// covered every slab (`record_slicer`'s predicate); the caller clears the predication. +pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( + list: &ID3D12GraphicsCommandList, + sig: &ID3D12CommandSignature, + commands: &ID3D12Resource, + rounds: u32, + predicated: bool, + scratch: &ID3D12Resource, + pieces: impl IntoIterator + Clone, +) { + let n = pieces.clone().into_iter().count() as u32; + if predicated { + list.SetPredication(commands, chain_predicate_offset(rounds, n), D3D12_PREDICATION_OP_NOT_EQUAL_ZERO); + } + list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); + for r in 0..rounds { + for (i, piece) in pieces.clone().into_iter().enumerate() { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::ManuallyDrop::new(None), + }), + }, + }]); + list.SetPipelineState(piece); + list.ExecuteIndirect( + sig, + 1, + commands, + u64::from((r * n + i as u32) * CHAIN_COMMAND_BYTES), + None::<&ID3D12Resource>, + 0, + ); + } + } +} + fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], split: bool) -> Result { let statics: Vec = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect(); unsafe { @@ -1425,7 +1702,15 @@ mod slab_tests { } } assert_eq!(dispatch_slabs([240, 135, 1], 1400).len(), 27, "five rows of 240 at once"); + for grid in [[1, 1, 1], [2, 3, 2], [240, 135, 1], [65_535, 2, 1], [5, 1, 7], [0, 4, 4]] { + for most in [0, 1, 3, 239, 240, 1000, u64::MAX] { + assert_eq!(super::slab_count(grid, most), dispatch_slabs(grid, most).len() as u64, "{grid:?} {most}"); + } + } assert!(dispatch_slabs([0, 4, 4], 8).is_empty()); + assert_eq!(super::align_slicer_srv(0x1000_000c, "args"), Ok((0x1000_0000, 12))); + assert!(super::align_slicer_srv(0, "args").is_err()); + assert!(super::align_slicer_srv(0x1000_0002, "args").is_err()); } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index c0f16f044b..806b10486c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -622,6 +622,23 @@ fn signature_dispatches(sig: usize) -> bool { DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } +/// command signatures of one Dispatch argument → their stride (a split program runs them as its +/// chain, `chained_indirect`) +static DISPATCH_ONLY: Mutex>> = Mutex::new(None); + +pub(super) fn note_dispatch_only_signature(sig: usize, stride: Option) { + let mut s = DISPATCH_ONLY.lock().unwrap(); + let s = s.get_or_insert_with(Default::default); + match stride { + Some(n) => { + s.insert(sig, n); + } + None => { + s.remove(&sig); + } + } +} + pub(super) fn note_dispatch_mesh_signature(sig: usize, companion_dispatch: usize, byte_stride: u32, mesh_offset: u32) { DISPATCH_MESH_SIGS .lock() @@ -1730,7 +1747,7 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { pResource: std::mem::ManuallyDrop::new(Some(b.clone())), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, + StateAfter: GUARDED_ARGS_STATE, }), }, }); @@ -1776,6 +1793,12 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { } } +/// State left on guarded indirect argument scratch buffers: valid for both `ExecuteIndirect` +/// and `pso::record_slicer` SRV reads (pure read-only state that decays cleanly to COMMON). +const GUARDED_ARGS_STATE: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATES( + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0, +); + /// The groups of an indirect dispatch above which they are not the title's (`GUARD_ARGS_HLSL`): /// a 4K target in groups of 2x2 pixels is 2.1 million. const MOST_GROUPS: u32 = 1 << 22; @@ -1882,9 +1905,9 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis list.SetComputeRootUnorderedAccessView(1, dst_va); list.SetComputeRootUnorderedAccessView(2, dispatch_io_va); list.Dispatch(1, 1, 1); - emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); with(this, |s| { - s.scratch[slot].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.scratch[slot].state = GUARDED_ARGS_STATE; s.pc_abi_cs = AbiBound::default(); s.arg_order_clean = true; }); @@ -1907,10 +1930,11 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis list.SetComputeRootUnorderedAccessView(2, dst_va); list.SetComputeRootUnorderedAccessView(3, dispatch_io_va); list.Dispatch(1, 1, 1); - // Transition scratch to INDIRECT_ARGUMENT and flush the `IO_GROUP_LIMIT` store in `dispatch_io_va`. - emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + // Transition scratch to INDIRECT_ARGUMENT | NON_PIXEL_SHADER_RESOURCE and flush the + // `IO_GROUP_LIMIT` store in `dispatch_io_va`. + emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); with(this, |s| { - s.scratch[slot].state = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; + s.scratch[slot].state = GUARDED_ARGS_STATE; s.pc_abi_cs = AbiBound::default(); s.arg_order_clean = true; }); @@ -2359,6 +2383,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us let off = usize::try_from(count_off).ok()?; (off.checked_add(4)? <= n).then(|| p.checked_add(off)).flatten() }); + let (args_off_title, count_off_title) = (args_off, count_off); let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if let Some(tp) = super::real::two_pass_of(pso) { if skip_mesh() { @@ -2481,33 +2506,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - // For split compute pipelines, resolve the whole form without stalling the title thread - // (kicking off background compilation on first indirect use instead of blocking 15-60s). - let whole_pso = if compute { - match super::real::dispatch_chain::whole_nonblocking(pso) { - super::real::dispatch_chain::WholeStatus::NotSplit => None, - super::real::dispatch_chain::WholeStatus::Ready(whole) => Some(whole), - super::real::dispatch_chain::WholeStatus::Pending => { - count(DISPATCHES_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 8 { - crate::xlog_info!("D3D12.X: ExecuteIndirect of split compute PSO ({pso:#x}) skipped while whole form builds in background"); - } - return; - } - super::real::dispatch_chain::WholeStatus::Failed => { - count(DISPATCHES_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO ({pso:#x}) failed – skipped"); - } - return; - } - } - } else { - None - }; - // (before the dispatch's own root signature and pipeline are bound) + // Guard single-command indirect dispatches before binding or chaining so both `record_slicer` + // and the PC `ExecuteIndirect` read clamped, >65535 X-folded arguments from a committed buffer. let mut guarded = None; let mut preset_io = None; if compute && max == 1 && indirect_guard() && signature_dispatches(sig) { @@ -2536,7 +2536,94 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } } - let (args, args_off) = guarded.as_ref().map_or((args, args_off), |(b, o)| (b.as_raw() as usize, *o)); + let (exec_args, exec_args_off) = guarded.as_ref().map_or((args, args_off), |(b, o)| (b.as_raw() as usize, *o)); + if compute && super::real::dispatch_chain::is_split(pso) { + // Run split compute ExecuteIndirects through their already-built chain pieces on the GPU + // instead of stalling or skipping while the whole form compiles in the background. + let ei = || { + if guarded.is_some() { + pc(this, sig, max, exec_args, exec_args_off, count_buf, count_off); + } else { + fresh_indirect_arguments(this, || pc(this, sig, max, exec_args, exec_args_off, count_buf, count_off)); + } + }; + let mark = super::culprit::before_dispatch(list, raw_pso, pso, [0, 0, max]); + match chained_indirect( + this, + list, + pso, + sig, + max, + guarded.as_ref(), + (args, args_off_title, args_off), + (count_buf, count_off_title, count_off), + preset_io, + ei, + ) { + Ok(true) => { + super::culprit::after_dispatch(list, mark); + with(this, |s| { + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = false; + s.prelude_blocked = true; + }); + return count(DISPATCHES); + } + Ok(false) => { + super::culprit::after_dispatch(list, mark); + } + Err(e) => { + super::culprit::after_dispatch(list, mark); + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + with(this, |s| s.pc_abi_cs = AbiBound::default()); + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect of a split program skipped: {e}"); + } + return; + } + } + } + // Non-chainable fallback (bundles, non-dispatch-only signatures, or no scratch): resolve the + // whole form without stalling the title thread. + let whole_pso = if compute { + match super::real::dispatch_chain::whole_nonblocking(pso) { + super::real::dispatch_chain::WholeStatus::NotSplit => None, + super::real::dispatch_chain::WholeStatus::Ready(whole) => Some(whole), + super::real::dispatch_chain::WholeStatus::Pending => { + if guarded.is_some() { + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + } + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!("D3D12.X: ExecuteIndirect of split compute PSO ({pso:#x}) skipped while whole form builds in background"); + } + return; + } + super::real::dispatch_chain::WholeStatus::Failed => { + if guarded.is_some() { + if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + list.SetPipelineState(real); + } + } + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO ({pso:#x}) failed – skipped"); + } + return; + } + } + } else { + None + }; + let (args, args_off) = (exec_args, exec_args_off); match bind_abi(this, list, pso, gfx, 0, preset_io) { Ok(()) => { if let Some(whole) = whole_pso { @@ -2573,6 +2660,97 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } +/// An ExecuteIndirect of split program `pso` with a command signature of one Dispatch, run as its +/// chain (`dispatch_chain::execute_indirect`); the buffers as (resource, title's offset, PC's). +/// Ok(false): nothing recorded – fall back to the whole form. +#[allow(clippy::too_many_arguments)] +unsafe fn chained_indirect( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + pso: usize, + sig: usize, + max: u32, + guarded: Option<&(ID3D12Resource, u64)>, + (args, args_title, args_pc): (usize, u64, u64), + (count_buf, count_title, count_pc): (usize, u64, u64), + preset_io: Option, + ei: impl FnOnce(), +) -> Result { + let Some(stride) = DISPATCH_ONLY.lock().unwrap().as_ref().and_then(|m| m.get(&sig).copied()) else { + return Ok(false); + }; + let args_va = match guarded { + Some((b, off)) => { + let va = b.GetGPUVirtualAddress(); + if va == 0 { + return Ok(false); + } + va + *off + } + None => match indirect_address(args, args_title, args_pc) { + Some(v) => v, + None => return Ok(false), + }, + }; + let count_va = match count_buf { + 0 => None, + c => match indirect_address(c, count_title, count_pc) { + Some(v) => Some(v), + None => return Ok(false), + }, + }; + // the arguments there now (the GPU's last ones) size the rounds + let read = |res: usize, off: u64, n: usize| -> Option> { + let (p, size) = super::real::console_buffer(res)?; + let off = usize::try_from(off).ok()?; + let end = off.checked_add(4 * n)?; + let at = p.checked_add(off)?; + (end <= size && crate::gpu::shader::readable(at, 4 * n)) + .then(|| (0..n).map(|i| std::ptr::read_volatile((at as *const u32).add(i))).collect()) + }; + let n = if count_buf == 0 { + max + } else { + read(count_buf, count_title, 1).map_or(max, |c| c[0].min(max)) + }; + let seen: Vec<[u32; 3]> = (0..n.min(64)) + .filter_map(|k| read(args, args_title.checked_add(u64::from(k).checked_mul(u64::from(stride))?)?, 3)) + .map(|v| [v[0], v[1], v[2]]) + .collect(); + let predicated = super::list_x::predication_active(this); + super::real::dispatch_chain::execute_indirect( + list, + pso, + with(this, |s| s.allocator), + args_va, + stride, + max, + count_va, + &seen, + predicated, + || { + with(this, |s| s.pc_abi_cs = AbiBound::default()); + bind_abi(this, list, pso, false, 0, preset_io) + }, + ei, + ) +} + +/// The GPU address of a title's buffer `res` at its offset `title` (a buffer in unified memory) or +/// `pc` (another). +unsafe fn indirect_address(res: usize, title: u64, pc: u64) -> Option { + match super::real::console_buffer(res) { + Some((p, n)) => { + let off = usize::try_from(title).ok()?; + let addr = p.checked_add(off)?; + (off < n).then(|| super::real::uma_va_of(addr)).flatten() + } + None => Some(ID3D12Resource::from_raw_borrowed(&(res as *mut c_void))?.GetGPUVirtualAddress()) + .filter(|&va| va != 0) + .map(|va| va + pc), + } +} + /// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses static ARGUMENT_ORDER: Mutex> = Mutex::new(None); diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index f33124a540..3e6777f9d8 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1307,6 +1307,9 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); + let stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let dispatch_only = list.len() == 1 && list[0][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32 && stride >= 12 && stride % 4 == 0; + super::bind::note_dispatch_only_signature(*ppv as usize, dispatch_only.then_some(stride)); } hr } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 1a5014e20a..a98420f984 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3373,6 +3373,11 @@ pub(super) fn on_pc_reset(list: *mut c_void) { } } +/// Whether the title's predication is set on `list` (XCL cannot set its own there) +pub(super) fn predication_active(list: *mut c_void) -> bool { + LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.predication.is_some()) +} + /// Copy 8 predicate bytes from `(uma_buf, off)` into `pb` with exact barrier transitions and /// bind `SetPredication(pb, 0, op)` on `this`. unsafe fn apply_predication_copy(this: *mut c_void, uma_buf: usize, off: u64, pb: usize, op: D3D12_PREDICATION_OP) { diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 0cbd9ce9c1..30d4cd3bb7 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -13,12 +13,24 @@ static SLABS: AtomicU64 = AtomicU64::new(0); static LIVE: AtomicU64 = AtomicU64::new(0); static PEAK: AtomicU64 = AtomicU64::new(0); static WANTED: AtomicU64 = AtomicU64::new(0); +/// ExecuteIndirects run as chains, those of them that ran the whole form instead (more slabs than +/// rounds), and the slabs lost when there was no whole form yet +static INDIRECT: AtomicU64 = AtomicU64::new(0); +static INDIRECT_WHOLE: AtomicU64 = AtomicU64::new(0); +static INDIRECT_LOST: AtomicU64 = AtomicU64::new(0); +/// ExecuteIndirects that ran the whole form (not chainable) +static WHOLE_INDIRECT: AtomicU64 = AtomicU64::new(0); +/// fast check so non-split indirect dispatches avoid locking `CHAINS` +static HAS_CHAINS: AtomicBool = AtomicBool::new(false); +/// raw PSO address of the slicer already labeled for DRED +static SLICER_LABELED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); pub(crate) fn log_counts() { let mib = |a: &AtomicU64| a.load(Ordering::Relaxed) >> 20; - crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab)", - PROGRAMS.load(Ordering::Relaxed), PIECES.load(Ordering::Relaxed), DISPATCHES.load(Ordering::Relaxed), SLABS.load(Ordering::Relaxed), - mib(&LIVE), mib(&PEAK), mib(&WANTED)); + let n = |a: &AtomicU64| a.load(Ordering::Relaxed); + crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab); ExecuteIndirect: {} chained ({} of them whole, {} slabs lost), {} whole", + n(&PROGRAMS), n(&PIECES), n(&DISPATCHES), n(&SLABS), mib(&LIVE), mib(&PEAK), mib(&WANTED), + n(&INDIRECT), n(&INDIRECT_WHOLE), n(&INDIRECT_LOST), n(&WHOLE_INDIRECT)); } /// The scratch a dispatch uses at once, `XCL_SPLIT_SCRATCH_MB` (256): more groups than fit run in @@ -57,6 +69,12 @@ struct Chain { whole_started: AtomicBool, whole_failed: AtomicBool, build_whole: Mutex<()>, + /// its command signature for ExecuteIndirect (`pso::chain_command_signature`) + signature: OnceLock, + /// the most slabs one of its ExecuteIndirects had + slabs: std::sync::atomic::AtomicU32, + /// a lost slab was reported once for this program + warned: AtomicBool, } pub(in crate::hle::d3d12x) enum WholeStatus { @@ -132,13 +150,24 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT } let mut pieces = all.into_iter(); let first = pieces.next()?; - let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), whole: OnceLock::new(), whole_started: AtomicBool::new(false), - whole_failed: AtomicBool::new(false), build_whole: Mutex::new(()) }); + let chain = Arc::new(Chain { + builder, + tail: pieces.collect(), + words: plan.dwords_per_group, + whole_code: whole.to_vec(), + whole: OnceLock::new(), + whole_started: AtomicBool::new(false), + whole_failed: AtomicBool::new(false), + build_whole: Mutex::new(()), + signature: OnceLock::new(), + slabs: Default::default(), + warned: AtomicBool::new(false), + }); PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); CHAINS.lock().unwrap().insert(*result as usize, chain); + HAS_CHAINS.store(true, Ordering::Release); Some(rs) } @@ -147,14 +176,23 @@ pub(super) fn forget(pso: usize) { drop(gone); // releasing a tail PSO also goes through forget_pso } +/// Fast check for whether `pso` is a split compute pipeline. +pub(in crate::hle::d3d12x) fn is_split(pso: usize) -> bool { + HAS_CHAINS.load(Ordering::Acquire) && CHAINS.lock().unwrap().contains_key(&pso) +} + /// Resolve the whole compute pipeline for an `ExecuteIndirect` without stalling the recording /// thread: when async PSO builds are enabled and the whole form is not compiled yet, kick off /// its build once on a background thread and return `Pending`. pub(in crate::hle::d3d12x) unsafe fn whole_nonblocking(pso: usize) -> WholeStatus { + if !HAS_CHAINS.load(Ordering::Acquire) { + return WholeStatus::NotSplit; + } let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return WholeStatus::NotSplit; }; if let Some(p) = chain.whole.get() { + WHOLE_INDIRECT.fetch_add(1, Ordering::Relaxed); return WholeStatus::Ready(p.clone()); } if chain.whole_failed.load(Ordering::Acquire) { @@ -162,7 +200,10 @@ pub(in crate::hle::d3d12x) unsafe fn whole_nonblocking(pso: usize) -> WholeStatu } if !super::super::pso_async::enabled() { return match chain.whole() { - Ok(p) => WholeStatus::Ready(p), + Ok(p) => { + WHOLE_INDIRECT.fetch_add(1, Ordering::Relaxed); + WholeStatus::Ready(p) + } Err(_) => { chain.whole_failed.store(true, Ordering::Release); WholeStatus::Failed @@ -180,7 +221,7 @@ struct Scratch { impl Drop for Scratch { fn drop(&mut self) { - LIVE.fetch_sub(self.bytes, Ordering::Relaxed); + LIVE.fetch_sub(self.bytes, Ordering::AcqRel); } } @@ -188,6 +229,56 @@ struct Recording { scratch: Arc, first: ID3D12PipelineState, chain: Arc, + indirect: Option, +} + +/// The commands of a chained ExecuteIndirect (`pso::record_slicer`), read when the GPU is done +/// with them (the allocator is reset): with more slabs than rounds, the next ExecuteIndirect of +/// the program records more, and the whole form is built in the background for it. +struct Indirect { + commands: ID3D12Resource, + at: u64, + rounds: u32, + /// the whole form ran instead under predication; `checked`: the predicate is XCL's own + whole: bool, + checked: bool, +} + +impl Recording { + fn read_back(&self) { + let Some(i) = self.indirect.as_ref().filter(|i| i.checked) else { return }; + let mut p = std::ptr::null_mut(); + let range = D3D12_RANGE { Begin: i.at as usize, End: i.at as usize + 16 }; + if unsafe { i.commands.Map(0, Some(&range), Some(&mut p)) }.is_err() { + return; + } + let [partial, _, slabs, _] = unsafe { std::ptr::read_volatile((p as *const u8).add(i.at as usize) as *const [u32; 4]) }; + unsafe { i.commands.Unmap(0, Some(&D3D12_RANGE::default())) }; + if partial == 0 { + return; + } + self.chain.slabs.fetch_max(slabs, Ordering::Relaxed); + if i.whole { + INDIRECT_WHOLE.fetch_add(1, Ordering::Relaxed); + return; + } + let lost = slabs.saturating_sub(i.rounds); + INDIRECT_LOST.fetch_add(u64::from(lost), Ordering::Relaxed); + if !self.chain.warned.swap(true, Ordering::Relaxed) { + crate::xlog_warn!( + "D3D12.X: ExecuteIndirect of a split program ({:#x}) had {slabs} slabs for {} rounds: {lost} lost; its whole form is built for the next ones", + self.first.as_raw() as usize, + i.rounds + ); + } + self.chain.start_whole_async(); + } +} + +impl Drop for Recording { + fn drop(&mut self) { + self.read_back(); + } } static RECORDINGS: LazyLock>>>> = LazyLock::new(Default::default); @@ -262,26 +353,88 @@ fn scratch_oom_fallback(had_bytes: Option, attempted: u64, group: u64) -> S } } +/// Guard for bytes atomically reserved from `LIVE` before `scratch_buffer` allocates GPU memory: +/// releases on drop if allocation fails, shrinks on OOM fallback, or transfers ownership to `Scratch`. +struct ScratchReservation<'a> { + live: &'a AtomicU64, + bytes: u64, +} + +impl<'a> ScratchReservation<'a> { + fn shrink(&mut self, new_bytes: u64) { + if new_bytes < self.bytes { + let release = self.bytes - new_bytes; + self.live.fetch_sub(release, Ordering::AcqRel); + self.bytes = new_bytes; + } + } + + fn commit(mut self) -> u64 { + let bytes = self.bytes; + self.bytes = 0; + bytes + } +} + +impl Drop for ScratchReservation<'_> { + fn drop(&mut self) { + if self.bytes != 0 { + self.live.fetch_sub(self.bytes, Ordering::AcqRel); + self.bytes = 0; + } + } +} + +/// Atomically decide whether to reuse `had` or reserve new scratch bytes from `live` BEFORE +/// creating the GPU buffer so concurrent recording threads cannot overshoot `total`. +fn reserve_scratch_bytes<'a>( + live: &'a AtomicU64, + peak: &AtomicU64, + needed: u64, + group: u64, + budget: u64, + had: Option, + total: u64, +) -> Option> { + let mut cur = live.load(Ordering::Acquire); + loop { + let (bytes, make) = scratch_bytes(needed, group, budget, had, cur, total); + if !make { + return None; + } + let next = cur.saturating_add(bytes); + match live.compare_exchange_weak(cur, next, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + peak.fetch_max(next, Ordering::Relaxed); + return Some(ScratchReservation { live, bytes }); + } + Err(observed) => cur = observed, + } + } +} + /// A scratch for a chain of `needed` bytes recorded on `list` with `allocator`, and whether a /// chain before it on the list used it. unsafe fn scratch_for(dev: &ID3D12Device, list: usize, allocator: usize, needed: u64, group: u64) -> Option<(Arc, bool)> { let had = SHARED.lock().unwrap().get(&list).filter(|s| s.0 == allocator).and_then(|s| s.1.upgrade()); let had_bytes = had.as_ref().map(|s| s.bytes); - let (bytes, make) = scratch_bytes(needed, group, scratch_budget(), had_bytes, LIVE.load(Ordering::Relaxed), scratch_total()); - if !make { + let Some(mut reservation) = reserve_scratch_bytes(&LIVE, &PEAK, needed, group, scratch_budget(), had_bytes, scratch_total()) else { return had.map(|s| (s, true)); - } - let (buffer, actual) = match scratch_buffer(dev, bytes) { - Some(b) => (b, bytes), + }; + let bytes = reservation.bytes; + let buffer = match scratch_buffer(dev, bytes) { + Some(b) => b, None => match scratch_oom_fallback(had_bytes, bytes, group) { ScratchOomFallback::ReuseExisting => return had.map(|s| (s, true)), - ScratchOomFallback::TryMinimal(min_bytes) => (scratch_buffer(dev, min_bytes)?, min_bytes), + ScratchOomFallback::TryMinimal(min_bytes) => { + reservation.shrink(min_bytes); + scratch_buffer(dev, min_bytes)? + } ScratchOomFallback::None => return None, }, }; + let actual = reservation.commit(); let s = Arc::new(Scratch { buffer, bytes: actual }); - let live = LIVE.fetch_add(actual, Ordering::Relaxed) + actual; - PEAK.fetch_max(live, Ordering::Relaxed); SHARED.lock().unwrap().insert(list, (allocator, Arc::downgrade(&s))); Some((s, false)) } @@ -329,7 +482,7 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, return Ok(()); }; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); - let held = Arc::new(Recording { scratch, first, chain }); + let held = Arc::new(Recording { scratch, first, chain, indirect: None }); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); DISPATCHES.fetch_add(1, Ordering::Relaxed); SLABS.fetch_add(slabs.len() as u64, Ordering::Relaxed); @@ -337,6 +490,111 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, Ok(()) } +/// The rounds a chained ExecuteIndirect records at most, `XCL_SPLIT_INDIRECT_ROUNDS` (16): each +/// is one ExecuteIndirect and one barrier per piece, also when the title's arguments leave it empty. +fn most_rounds() -> u32 { + static B: OnceLock = OnceLock::new(); + *B.get_or_init(|| { + std::env::var("XCL_SPLIT_INDIRECT_ROUNDS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .filter(|&n| n > 0) + .unwrap_or(16u32) + .min(1024) + }) +} + +/// The rounds for slabs of `most` groups: as many as the arguments there now (`seen`, the GPU's +/// last ones) or an earlier ExecuteIndirect of the program (`before`) had, a quarter more, at +/// least two and at most `cap`. +fn indirect_rounds(seen: &[[u32; 3]], most: u64, before: u32, cap: u32) -> u32 { + let now: u64 = seen.iter().map(|&g| pso::slab_count(g, most)).sum(); + let want = now.max(u64::from(before)); + (want + want.div_ceil(4)).clamp(2, u64::from(cap.max(2))) as u32 +} + +/// An ExecuteIndirect of split program `pso` whose command signature is one Dispatch of `stride` +/// bytes: `commands` of them at GPU address `args` (their count at `count`, when given), run as +/// the chain. `seen`: the arguments the CPU sees there now; `predicated`: the title's predication +/// is set. `bind` binds the ABI after the slicer, and `whole` is the title's ExecuteIndirect, run +/// with the whole form (built already) when the arguments have more slabs than the rounds. +/// Ok(false): nothing recorded (no chain, a bundle, no scratch) – the caller runs the whole form. +#[allow(clippy::too_many_arguments)] +pub(in crate::hle::d3d12x) unsafe fn execute_indirect( + list: &ID3D12GraphicsCommandList, + pso: usize, + allocator: usize, + args: u64, + stride: u32, + commands: u32, + count: Option, + seen: &[[u32; 3]], + predicated: bool, + bind: impl FnOnce() -> Result<(), String>, + whole: impl FnOnce(), +) -> Result { + if !HAS_CHAINS.load(Ordering::Acquire) { + return Ok(false); + } + let chain = CHAINS.lock().unwrap().get(&pso).cloned(); + let Some(chain) = chain else { return Ok(false) }; + let allocator = if super::super::alloc_pool::enabled() { + super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) + } else { + allocator + }; + if allocator == 0 || list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE { + return Ok(false); + } + let dev = &chain.builder.device; + let group = u64::from(chain.words) * 4; + let Some((scratch, _)) = scratch_for(dev, list.as_raw() as usize, allocator, scratch_budget(), group) else { + return Ok(false); + }; + let most = (scratch.bytes / group).max(1); + let sig = match chain.signature.get() { + Some(s) => s.clone(), + None => { + let s = pso::chain_command_signature(dev, &chain.builder.signature)?; + chain.signature.get_or_init(|| s).clone() + } + }; + let rounds = indirect_rounds(seen, most, chain.slabs.load(Ordering::Relaxed), most_rounds()); + let pieces = chain.tail.len() as u32 + 1; + let buffer = pso::chain_commands_buffer(dev, rounds, pieces).ok_or("no buffer for the commands of a chained ExecuteIndirect")?; + let slicer_pso = pso::record_slicer(list, args, stride, commands, count, rounds, most, pieces, &buffer)?; + if slicer_pso != 0 && SLICER_LABELED.swap(slicer_pso, Ordering::Relaxed) != slicer_pso { + super::super::dred::label_text(slicer_pso, || "xcl dispatch_chain_slicer".into()); + } + bind()?; + // under the title's own predication XCL's cannot be set: the slabs past the rounds are lost + let full = if predicated { None } else { chain.whole.get().cloned() }; + let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); + pso::record_dispatch_chain_indirect(list, &sig, &buffer, rounds, full.is_some(), &scratch.buffer, std::iter::once(&first).chain(&chain.tail)); + let at = pso::chain_predicate_offset(rounds, pieces); + if let Some(full) = &full { + list.SetPredication(&buffer, at, D3D12_PREDICATION_OP_EQUAL_ZERO); + list.SetPipelineState(full); + whole(); + list.SetPredication(None::<&ID3D12Resource>, 0, D3D12_PREDICATION_OP_EQUAL_ZERO); + } + let indirect = Indirect { + commands: buffer, + at, + rounds, + whole: full.is_some(), + checked: !predicated, + }; + RECORDINGS + .lock() + .unwrap() + .entry(allocator) + .or_default() + .push(Arc::new(Recording { scratch, first, chain, indirect: Some(indirect) })); + INDIRECT.fetch_add(1, Ordering::Relaxed); + Ok(true) +} + #[cfg(test)] mod tests { use super::{scratch_bytes, LEAST}; @@ -408,4 +666,57 @@ mod tests { // Already attempted minimal 1-group allocation with no usable existing scratch: give up. assert_eq!(scratch_oom_fallback(None, group, group), ScratchOomFallback::None); } + + #[test] + fn concurrent_scratch_admission_serializes_budget_reservations() { + use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, Barrier, + }; + let group = 256 << 10; + let budget = 64 * MB; + let total = 384 * MB; + + // Case 1: 12 concurrent threads whose lists already have a 4 MiB scratch buffer race to + // grow to 64 MiB. Atomic reservation caps `peak <= total` (at most 6 grow; 6 reuse). + let live = Arc::new(AtomicU64::new(0)); + let peak = Arc::new(AtomicU64::new(0)); + let start = Arc::new(Barrier::new(12)); + let hold = Arc::new(Barrier::new(12)); + let mut threads = Vec::new(); + for _ in 0..12 { + let (live, peak, start, hold) = (Arc::clone(&live), Arc::clone(&peak), Arc::clone(&start), Arc::clone(&hold)); + threads.push(std::thread::spawn(move || { + start.wait(); + let res = super::reserve_scratch_bytes(&live, &peak, budget, group, budget, Some(4 * MB), total); + let granted = res.as_ref().map_or(0, |r| r.bytes); + hold.wait(); + drop(res); + granted + })); + } + let grants: Vec = threads.into_iter().map(|t| t.join().unwrap()).collect(); + assert_eq!(grants.iter().filter(|&&b| b == budget).count(), 6); + assert_eq!(grants.iter().filter(|&&b| b == 0).count(), 6); + assert_eq!(peak.load(Ordering::Relaxed), total); + assert_eq!(live.load(Ordering::Relaxed), 0); + + // Case 2: shrink + rollback on OOM fallback releases reserved bytes accurately. + let mut r = super::reserve_scratch_bytes(&live, &peak, budget, group, budget, None, total).unwrap(); + assert_eq!(r.bytes, budget); + assert_eq!(live.load(Ordering::Relaxed), budget); + r.shrink(group); + assert_eq!(r.bytes, group); + assert_eq!(live.load(Ordering::Relaxed), group); + drop(r); + assert_eq!(live.load(Ordering::Relaxed), 0); + } + + #[test] + fn indirect_rounds_clamps_and_adds_headroom() { + assert_eq!(super::indirect_rounds(&[], 100, 0, 16), 2); + assert_eq!(super::indirect_rounds(&[[100, 4, 1]], 100, 0, 16), 5); + assert_eq!(super::indirect_rounds(&[[100, 1, 1]], 100, 8, 16), 10); + assert_eq!(super::indirect_rounds(&[[100, 40, 1]], 100, 0, 16), 16); + } } From e6e13bce648f09288a91e7303ff9fcc8162f0bce Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:53:09 +0100 Subject: [PATCH 114/258] D3D12.X: defer sparse UpdateTileMappings(NULL) behind title queues flush_parked previously issued UpdateTileMappings(NULL) on xcl sparse queue immediately while active title queues were still executing against those sparse windows. On AMD RDNA4, mutating reserved-buffer page tables concurrently with executing shaders can trigger DXGI_ERROR_DEVICE_HUNG (0x887A0006) page faults. Gate sparse window NULL unmaps behind live title-queue fence completion (pending_unmaps) without adding cross-queue GPU Waits on the sparse queue (deadlock-free). Re-committing a VA before its deferred unmap completes reclaims the still-mapped tile in O(1) via pending_unmap_va with a monotonic sequence id to prevent ABA stale-unmap wipes. Tested: cargo check -p xcl --lib (0 errors, 0 new warnings); added gpu_flush_parked_defers_null_unmap_and_recommit_cancels_stale_unmap. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/sparse.rs | 249 +++++++++++++++---- crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 3 + 2 files changed, 210 insertions(+), 42 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b71ef897bf..c2f86c4dab 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -205,6 +205,13 @@ struct RetiredTiles { marks: Option>, } +struct PendingUnmap { + seq: u64, + entries: Vec<(usize, (u32, u32))>, + /// Fence marks on every known title queue (`None` = signal failed, keep mapped/held). + marks: Option>, +} + struct State { dev: ID3D12Device, queue: ID3D12CommandQueue, @@ -234,6 +241,13 @@ struct State { /// decommits and commits again thousands of tiles a second, and each `UpdateTileMappings` /// took ~0.15 ms.) parked: FxHashMap, + /// parked tiles awaiting in-flight title queues before `UpdateTileMappings(NULL)` executes + pending_unmaps: VecDeque, + /// tile VA → `(pool_tile, unmap_seq)` for tiles still mapped in hardware inside `pending_unmaps`; + /// re-committing a VA cancels its pending unmap with no GPU tile-mapping change + pending_unmap_va: FxHashMap, + /// monotonic sequence id preventing ABA cancellation across repeated decommit/recommit cycles + unmap_seq: u64, /// unmapped parked pool tiles awaiting `self.queue` and in-flight title queues before entering `free` quarantined: VecDeque, /// unpinned unused pool tiles queued from `forget_in` (cannot signal queues under D3D12 release locks) @@ -561,6 +575,9 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, quarantined: VecDeque::new(), pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), @@ -789,7 +806,7 @@ impl State { while t < end { if !self.mapped.contains_key(&t) && self.window_index(t).is_some() { // still mapped there: no new mapping, what it held is cleared - if let Some(tile) = self.parked.remove(&t) { + if let Some(tile) = self.parked.remove(&t).or_else(|| self.pending_unmap_va.remove(&t).map(|(tile, _)| tile)) { self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); self.runs = None; self.to_zero.push((t, TILE)); @@ -1433,6 +1450,7 @@ impl State { if !self.pinned.contains_key(&tile) && !self.mapped.values().any(|e| e.pool == tile) && !self.parked.values().any(|&p| p == tile) + && !self.pending_unmap_va.values().any(|&(p, _)| p == tile) && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) && !self.pending_quarantine.contains(&tile) && !self.free.contains(&tile) @@ -1454,6 +1472,7 @@ impl State { !self.pinned.contains_key(tile) && !self.mapped.values().any(|e| e.pool == *tile) && !self.parked.values().any(|&p| p == *tile) + && !self.pending_unmap_va.values().any(|&(p, _)| p == *tile) && !self.quarantined.iter().any(|b| b.tiles.contains(tile)) }) .collect(); @@ -1496,29 +1515,96 @@ impl State { ok } + unsafe fn signal_title_queues(&mut self) -> Option> { + if !self.sync_known_queues() { + return None; + } + let mut marks = Vec::with_capacity(self.queue_fences.len()); + for (q, fence, val) in self.queue_fences.values_mut() { + let next = *val + 1; + if q.Signal(&*fence, next).is_ok() { + *val = next; + marks.push((fence.clone(), next)); + } else { + return None; + } + } + Some(marks) + } + unsafe fn quarantine_tiles(&mut self, tiles: Vec<(u32, u32)>) { if tiles.is_empty() { return; } - let mut ok = self.sync_known_queues(); - let mut marks = Vec::with_capacity(1 + self.queue_fences.len()); - marks.push((self.fence.clone(), self.value)); - if ok { - for (q, fence, val) in self.queue_fences.values_mut() { - let next = *val + 1; - if q.Signal(&*fence, next).is_ok() { - *val = next; - marks.push((fence.clone(), next)); - } else { - ok = false; - break; + let marks = self.signal_title_queues().map(|mut title_marks| { + title_marks.push((self.fence.clone(), self.value)); + title_marks + }); + self.quarantined.push_back(RetiredTiles { tiles, marks }); + } + + /// Unmap `entries` on `self.queue` and quarantine their unpinned pool tiles behind `self.fence`. + /// Caller guarantees every active title queue has already passed the work that could touch them. + unsafe fn unmap_entries_and_quarantine(&mut self, entries: Vec<(usize, (u32, u32))>) { + if entries.is_empty() { + return; + } + let mut by_window: FxHashMap> = FxHashMap::default(); + let mut tiles: Vec<(u32, u32)> = Vec::new(); + for (va, tile) in entries { + if let Some(wi) = self.window_index(va) { + by_window.entry(wi).or_default().push(va); + } + if !self.pinned.contains_key(&tile) + && !self.mapped.values().any(|e| e.pool == tile) + && !self.parked.values().any(|&p| p == tile) + && !self.pending_unmap_va.values().any(|&(p, _)| p == tile) + && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) + && !tiles.contains(&tile) + { + tiles.push(tile); + } + } + for (wi, ts) in by_window { + let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); + self.unmap_tiles(&r, b, &ts); + } + self.signal(); + if !tiles.is_empty() { + self.quarantined.push_back(RetiredTiles { + tiles, + marks: Some(vec![(self.fence.clone(), self.value)]), + }); + } + } + + /// Execute deferred `UpdateTileMappings(NULL)` batches once all title queues have passed their + /// completion marks, skipping any VA that was re-committed in the meantime. + unsafe fn drain_pending_unmaps(&mut self) -> bool { + let mut unmapped = false; + while let Some(front) = self.pending_unmaps.front() { + let ready = front.marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)); + if !ready { + break; + } + let batch = self.pending_unmaps.pop_front().unwrap(); + let mut ready_entries = Vec::with_capacity(batch.entries.len()); + for (va, tile) in batch.entries { + if self.pending_unmap_va.get(&va).is_some_and(|&(_, s)| s == batch.seq) { + self.pending_unmap_va.remove(&va); + ready_entries.push((va, tile)); } } + if !ready_entries.is_empty() { + self.unmap_entries_and_quarantine(ready_entries); + unmapped = true; + } } - self.quarantined.push_back(RetiredTiles { tiles, marks: ok.then_some(marks) }); + unmapped } unsafe fn drain_quarantined(&mut self) -> bool { + self.drain_pending_unmaps(); let mut freed = false; while let Some(front) = self.quarantined.front() { let ready = front.marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)); @@ -1536,39 +1622,27 @@ impl State { freed } - /// The parked tiles unmapped from their windows (one call per window) and their unpinned - /// pool tiles quarantined behind `self.queue` and every known title queue's completion fence. - /// Pools left all free are not retired here: callers do that (`retire_free_pools`) unless - /// they take a tile right away. + /// Queue parked tiles for unmapping once all active title queues finish in-flight work (never + /// issuing `UpdateTileMappings(NULL)` concurrently with executing title queues, and never + /// inserting a cross-queue GPU `Wait` on `self.queue`). When no title queues are busy, unmaps + /// immediately on `self.queue` and quarantines unpinned pool tiles behind `self.fence`. unsafe fn flush_parked(&mut self) -> bool { + self.drain_pending_unmaps(); if self.parked.is_empty() { return false; } - let mut by_window: FxHashMap> = FxHashMap::default(); - let mut tiles: Vec<(u32, u32)> = Vec::new(); - for (t, tile) in std::mem::take(&mut self.parked) { - if let Some(wi) = self.window_index(t) { - by_window.entry(wi).or_default().push(t); - } - if !self.pinned.contains_key(&tile) { - tiles.push(tile); - } - } - for (wi, ts) in by_window { - let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); - self.unmap_tiles(&r, b, &ts); - } - self.signal(); - for tile in self.pending_quarantine.drain(..) { - if !self.pinned.contains_key(&tile) - && !self.mapped.values().any(|e| e.pool == tile) - && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) - && !tiles.contains(&tile) - { - tiles.push(tile); + let entries: Vec<(usize, (u32, u32))> = std::mem::take(&mut self.parked).into_iter().collect(); + let title_marks = self.signal_title_queues(); + if title_marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { + self.unmap_entries_and_quarantine(entries); + } else { + self.unmap_seq = self.unmap_seq.wrapping_add(1); + let seq = self.unmap_seq; + for &(va, tile) in &entries { + self.pending_unmap_va.insert(va, (tile, seq)); } + self.pending_unmaps.push_back(PendingUnmap { seq, entries, marks: title_marks }); } - self.quarantine_tiles(tiles); true } } @@ -1911,6 +1985,9 @@ mod tests { free: Vec::new(), retired: Vec::new(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, mapped: FxHashMap::default(), pinned: FxHashMap::default(), quarantined: VecDeque::new(), @@ -2122,6 +2199,9 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, quarantined: VecDeque::new(), pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), @@ -2220,6 +2300,9 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, quarantined: VecDeque::new(), pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), @@ -2346,6 +2429,9 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, quarantined: VecDeque::new(), pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), @@ -2649,9 +2735,16 @@ mod tests { s.pinned.insert(tile, 1); s.buffers.insert(BUF, vec![tile]); - // Decommit and flush while still pinned by BUF: tile is unmapped from window, NOT freed. + // Decommit and flush while still pinned by BUF: tile is unmapped from window once + // idle title_queue passes its fence, NOT freed. s.decommit_range(base, TILE); assert!(s.flush_parked()); + let start = std::time::Instant::now(); + while !s.pending_unmaps.is_empty() && start.elapsed() < std::time::Duration::from_secs(5) { + s.drain_pending_unmaps(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(s.pending_unmaps.is_empty()); assert!(!s.free.contains(&tile)); assert!(s.quarantined.is_empty()); @@ -2682,4 +2775,76 @@ mod tests { assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } } + + /// `flush_parked` must defer `UpdateTileMappings(NULL)` until active title queues finish + /// their prior work (preventing concurrent PTE unmapping while shaders run), and re-committing + /// the VA before that fence completes must cancel the deferred unmap cleanly (including ABA). + #[test] + fn gpu_flush_parked_defers_null_unmap_and_recommit_cancels_stale_unmap() { + use windows_sys::Win32::System::Memory::{VirtualFree, MEM_RELEASE}; + unsafe { + let (base, mut s) = test_state_with_reserved(2); + let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + assert!(s.note_queue(&title_q)); + + s.commit_range(base, TILE); + let tile = s.mapped[&base].pool; + s.wait_for(s.value); + let v_before = s.value; + + let gate1: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate1"); + let _unblock1 = SignalOnDrop(gate1.clone(), 1); + title_q.Wait(&gate1, 1).expect("gate title_q 1"); + + // Decommit + flush while title_q is busy: NULL unmap must be deferred, NOT queued on s.queue yet. + s.decommit_range(base, TILE); + assert!(s.flush_parked()); + assert_eq!(s.value, v_before, "UpdateTileMappings(NULL) must not be issued while title queue is in flight"); + assert_eq!(s.pending_unmaps.len(), 1); + assert!(s.pending_unmap_va.contains_key(&base)); + + // Re-commit same VA before gate1 signals: cancels pending unmap, keeps tile, zeros it, no GPU remap. + s.to_zero.clear(); + s.commit_range(base, TILE); + assert_eq!(s.mapped[&base].pool, tile); + assert!(!s.pending_unmap_va.contains_key(&base)); + assert_eq!(s.to_zero, vec![(base, TILE)]); + assert_eq!(s.value, v_before); + + // ABA check: decommit & flush again behind a second gate; when gate1 finishes first, + // batch #1 must NOT unmap batch #2's tile. + let gate2: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate2"); + let _unblock2 = SignalOnDrop(gate2.clone(), 1); + title_q.Wait(&gate2, 1).expect("gate title_q 2"); + s.decommit_range(base, TILE); + assert!(s.flush_parked()); + assert_eq!(s.pending_unmaps.len(), 2); + + gate1.Signal(1).expect("signal gate1"); + let start = std::time::Instant::now(); + while s.pending_unmaps.len() == 2 && start.elapsed() < std::time::Duration::from_secs(5) { + s.drain_pending_unmaps(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(s.pending_unmaps.len(), 1, "batch #1 drained cleanly"); + assert_eq!(s.value, v_before, "stale batch #1 must not unmap VA owned by batch #2"); + assert!(s.pending_unmap_va.contains_key(&base)); + + // Releasing gate2 executes batch #2's deferred NULL unmap and returns tile to free. + gate2.Signal(1).expect("signal gate2"); + let start = std::time::Instant::now(); + while !s.drain_quarantined() && start.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(s.value > v_before, "batch #2 must emit UpdateTileMappings(NULL) once title_q completes"); + assert!(s.pending_unmaps.is_empty() && s.pending_unmap_va.is_empty()); + assert!(s.free.contains(&tile)); + + drop(_unblock2); + drop(_unblock1); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs index 557255080c..3aa28019ab 100644 --- a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -582,6 +582,9 @@ mod tests { mapped: FxHashMap::default(), pinned: FxHashMap::default(), parked: FxHashMap::default(), + pending_unmaps: VecDeque::new(), + pending_unmap_va: FxHashMap::default(), + unmap_seq: 0, quarantined: VecDeque::new(), pending_quarantine: Vec::new(), queue_fences: FxHashMap::default(), From ca38495ce48efed63ded3b84c9814d7bd76741d8 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:53:09 +0100 Subject: [PATCH 115/258] D3D12.X: fence-gate VRAM tile unmaps, cooling, and late_release unmap_superseded and apply_backing previously called UpdateTileMappings(NULL) on xcl vram tile-mapping queue immediately while title queues were still executing against live reserved textures (matching the live type-34 resource GPU VA page fault signature on AMD RDNA4). In addition, unmap_superseded bypassed IDLE with a 2 s wall-clock COOL timer that could expire during 4-8 s PSO compile stalls, and late_release did not fence the vram tile-mapping queue. Defer both whole-resource (unmap_superseded) and per-tile (apply_backing) NULL unmaps behind per-queue completion fences across all live device queues (never adding cross-queue GPU Waits), cancel stale unmaps on remap via Target::mapping_gen and Follow::mapped, quarantine unshared tiles behind pages.fence completion (fenced_tiles), bound TilePool::drain_cooling by a completed multi-queue GPU fence barrier (safe_cool_before), and include lock-free vram::queues() in late_release::drain_known. Tested: cargo check -p xcl --lib (0 errors, 0 new warnings); added pending_unmap_batches_wait_for_all_live_queues_and_hold_on_signal_error and tile_pool_cooling_respects_gpu_fence_barrier_across_long_stalls. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/late_release.rs | 1 + crates/xcl/src/hle/d3d12x/vram.rs | 487 +++++++++++++++++++--- 2 files changed, 440 insertions(+), 48 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 7e8606da25..6662e7e8ae 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -168,6 +168,7 @@ pub unsafe fn drain_known(seal_now: bool) { } } queues.extend(super::sparse::queue()); + queues.extend(super::vram::queues()); queues.extend(super::title_textures::upload_queues()); match HELD.lock().unwrap().as_mut() { Some(h) => h.drain(&queues, seal_now), diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 4601117a00..d2f6fd3402 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -394,6 +394,8 @@ struct Target { console_bytes: Option, total: u32, mapped: bool, + /// incremented on every `unmap_superseded` / `remap_if_unmapped` to cancel stale deferred unmaps + mapping_gen: u64, used: Vec, used_extra: Vec<(usize, usize)>, /// its owned pages in graphics reservations (`Pages::follow`) @@ -655,10 +657,13 @@ impl TilePool { self.cooling.push_back((tile, now)); } - /// Move every cooled tile (`>= COOL`) into its pool heap's free list so best-fit allocation + /// Move every cooled tile (`>= COOL` and, when `safe_before` is set, queued no later than the + /// latest GPU-verified fence barrier) into its pool heap's free list so best-fit allocation /// sees all ready tiles at once. - fn drain_cooling(&mut self, now: std::time::Instant) { - while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + fn drain_cooling_before(&mut self, now: std::time::Instant, safe_before: Option) { + while self.cooling.front().is_some_and(|&(_, at)| { + now.duration_since(at) >= COOL && safe_before.is_none_or(|safe| at <= safe) + }) { let Some(((h, t), _)) = self.cooling.pop_front() else { break }; let idx = h as usize; if idx < self.free_by_heap.len() { @@ -669,6 +674,12 @@ impl TilePool { } } + /// Move every cooled tile (`>= COOL`) into its pool heap's free list. + #[cfg(test)] + fn drain_cooling(&mut self, now: std::time::Instant) { + self.drain_cooling_before(now, None); + } + fn return_tiles(&mut self, tiles: &[Tile]) { for &(h, t) in tiles { let idx = h as usize; @@ -715,18 +726,31 @@ impl TilePool { /// Allocate `count` tiles, preferring a single heap and ascending contiguous offsets. /// `make_heap` allocates a new backing pool heap of `pool_pages` tiles when `free_total == 0`. /// On failure, any tiles already taken are returned untouched. + #[cfg(test)] fn take_batch( &mut self, count: usize, preferred: Option, now: std::time::Instant, pool_pages: u32, + make_heap: impl FnMut() -> Option, + ) -> Option> { + self.take_batch_fenced(count, preferred, now, None, pool_pages, make_heap) + } + + fn take_batch_fenced( + &mut self, + count: usize, + preferred: Option, + now: std::time::Instant, + safe_before: Option, + pool_pages: u32, mut make_heap: impl FnMut() -> Option, ) -> Option> { if count == 0 { return Some(Vec::new()); } - self.drain_cooling(now); + self.drain_cooling_before(now, safe_before); let mut out = Vec::with_capacity(count); while out.len() < count { let rem = count - out.len(); @@ -829,6 +853,44 @@ fn keep_spare_pools() -> usize { }) } +/// Deferred `UpdateTileMappings(NULL)` operation awaiting completion of all in-flight device queues. +enum PendingUnmapOp { + /// Whole-resource unmap from `unmap_superseded` (skipped if `Target::mapping_gen` advanced). + Whole { res: ID3D12Resource, key: usize, gen: u64, total: u32, tiles: Vec }, + /// Per-tile unmap from `apply_backing` (each `(tile_idx, page_addr)` skipped if `follow[page_addr].mapped` became true again). + Tiles { res: ID3D12Resource, key: usize, total: u32, pairs: Vec<(u32, usize)> }, +} + +/// Sealed batch of deferred unmaps waiting on live device queues (`F` = fence; pure-CPU types in tests). +struct PendingUnmapBatch { + ops: Vec, + /// `None` if signaling any live queue failed (held to avoid premature unmapping). + marks: Option>, +} + +/// Pop every front batch in `queue` whose fence marks have all completed. +fn drain_ready_unmap_batches( + queue: &mut std::collections::VecDeque>, + mut completed: impl FnMut(&F) -> u64, +) -> Vec { + let mut ready = Vec::new(); + while queue.front().is_some_and(|b| b.marks.as_ref().is_some_and(|m| m.iter().all(|(f, v)| completed(f) >= *v))) { + if let Some(batch) = queue.pop_front() { + ready.extend(batch.ops); + } + } + ready +} + +/// Tile-mapping queues across devices, kept outside `PAGES` so `late_release` (called from inside +/// COM `Release`) can fence them without acquiring `PAGES.lock()`. +static VRAM_QUEUES: Mutex> = Mutex::new(Vec::new()); + +/// Live `vram` tile-mapping queues (lock-free with respect to `PAGES`). +pub fn queues() -> Vec { + VRAM_QUEUES.lock().unwrap().clone() +} + /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { queue: ID3D12CommandQueue, @@ -839,6 +901,20 @@ struct Pages { dirty_signal: bool, /// per-device timestamp of the last periodic reclaim check last_reclaim: std::time::Instant, + /// creation time (lower bound for `safe_cool_before` once live queues are observed) + created_at: std::time::Instant, + /// true once `before_execute` has run on a live queue for this device + has_live_queues: bool, + /// unmaps queued inside `PAGES.lock()` awaiting live-queue fence marks (`seal_and_drain_unmaps`) + unsealed_unmaps: Vec, + /// sealed unmaps awaiting all live device queues before `UpdateTileMappings(NULL)` executes + pending_unmaps: std::collections::VecDeque>, + /// unshared tiles already unmapped on `self.queue`, awaiting `self.fence >= val` before returning to `pool` + fenced_tiles: std::collections::VecDeque<(u64, Vec)>, + /// periodic multi-queue fence probe bounding `TilePool::cooling` against >2s GPU/PSO stalls + cool_probe: Option<(std::time::Instant, Vec<(ID3D12Fence, u64)>)>, + /// latest timestamp proven free of in-flight work across all live device queues + safe_cool_before: Option, pools: PoolHeaps, pool: TilePool, /// title page address → its video memory @@ -884,13 +960,22 @@ impl Pages { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).ok()?; let _ = queue.SetName(windows::core::w!("xcl vram tile-mapping queue")); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + VRAM_QUEUES.lock().unwrap().push(queue.clone()); crate::xlog_info!("D3D12.X: textures in title memory: tiled resources on 64 KiB pages of video memory, one per page of the title's"); + let now = std::time::Instant::now(); Some(Pages { queue, fence, value: 0, dirty_signal: false, - last_reclaim: std::time::Instant::now(), + last_reclaim: now, + created_at: now, + has_live_queues: false, + unsealed_unmaps: Vec::new(), + pending_unmaps: std::collections::VecDeque::new(), + fenced_tiles: std::collections::VecDeque::new(), + cool_probe: None, + safe_cool_before: None, pools: PoolHeaps::new(), pool: TilePool::new(), pages: std::collections::HashMap::new(), @@ -909,6 +994,26 @@ impl Pages { }) } + /// Latest timestamp proven free of in-flight GPU work when live queues are tracked. + #[inline] + fn cool_bound(&self) -> Option { + self.has_live_queues.then(|| self.safe_cool_before.unwrap_or(self.created_at)) + } + + /// Return any unshared tiles whose deferred `UpdateTileMappings(NULL)` fence on `self.queue` + /// has completed back into `self.pool` immediately. + unsafe fn drain_fenced_tiles(&mut self) { + if self.fenced_tiles.is_empty() { + return; + } + let done = self.fence.GetCompletedValue(); + while self.fenced_tiles.front().is_some_and(|&(fv, _)| done >= fv) { + if let Some((_, tiles)) = self.fenced_tiles.pop_front() { + self.pool.return_tiles(&tiles); + } + } + } + /// Pages no resource used for `IDLE` go back to the pools. fn sweep(&mut self, now: std::time::Instant) { sweep_idle(&mut self.idle, &mut self.pages, &mut self.extra_pages, &mut self.pool.cooling, now); @@ -919,7 +1024,7 @@ impl Pages { /// outside `PAGES.lock()`. fn sweep_and_reclaim(&mut self, now: std::time::Instant) -> Vec { self.sweep(now); - self.pool.drain_cooling(now); + self.pool.drain_cooling_before(now, self.cool_bound()); let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare_pools(), POOL_PAGES); let mut dropped = Vec::with_capacity(reclaimed_ids.len()); for idx in reclaimed_ids { @@ -1023,6 +1128,62 @@ impl Pages { } } + /// Unmap selected tiles (`sel(i) == true`) of `res` (`D3D12_TILE_RANGE_FLAG_NULL`). + unsafe fn unmap_selected(&mut self, res: &ID3D12Resource, total: u32, sel: impl Fn(u32) -> bool) { + if total == 0 { + return; + } + let ranges = update_ranges(total, D3D12_TILE_RANGE_FLAG_NULL, |i| sel(i).then_some(0)); + if ranges.iter().all(|r| r.0 == D3D12_TILE_RANGE_FLAG_SKIP) { + return; + } + let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); + let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; + let flags: Vec = ranges.iter().map(|r| r.0).collect(); + let offsets: Vec = ranges.iter().map(|r| r.1).collect(); + let counts: Vec = ranges.iter().map(|r| r.2).collect(); + self.queue.UpdateTileMappings( + res, + 1, + Some(&coord), + Some(®ion), + None, + ranges.len() as u32, + Some(flags.as_ptr()), + Some(offsets.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + self.dirty_signal = true; + } + + /// Decrement page refcounts for a superseded texture and collect any now-unshared pool tiles + /// so they stay quarantined until the deferred `UpdateTileMappings(NULL)` finishes on the GPU. + fn release_tiles_unshared(&mut self, used: Vec, used_extra: Vec<(usize, usize)>) -> Vec { + let mut unshared = Vec::new(); + for a in used { + if let Some(p) = self.pages.get_mut(&a) { + p.users = p.users.saturating_sub(1); + if p.users == 0 { + if let Some(p) = self.pages.remove(&a) { + unshared.push(p.tile); + } + } + } + } + for k in used_extra { + if let Some(p) = self.extra_pages.get_mut(&k) { + p.users = p.users.saturating_sub(1); + if p.users == 0 { + if let Some(p) = self.extra_pages.remove(&k) { + unshared.push(p.tile); + } + } + } + } + unshared + } + fn release_tiles(&mut self, used: Vec, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) { for a in used { if let Some(p) = self.pages.get_mut(&a) { @@ -1143,9 +1304,10 @@ impl Pages { } } + let safe_before = self.cool_bound(); let pools = &mut self.pools; let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, now, POOL_PAGES, || { + let fresh = pool.take_batch_fenced(missing, preferred, now, safe_before, POOL_PAGES, || { let _timer = step(Step::Heap); let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) @@ -1248,9 +1410,12 @@ impl Pages { addrs.sort_unstable(); addrs.dedup(); let now = std::time::Instant::now(); + let safe_before = self.cool_bound(); let mut backed_run = BackedRun::default(); - // texture → (tile, its new page or None: unmapped) - let mut changes: std::collections::HashMap)>> = std::collections::HashMap::new(); + // texture → (tile, its new page) for immediate maps + let mut map_changes: std::collections::HashMap> = std::collections::HashMap::new(); + // texture → (tile, page_addr) for deferred NULL unmaps (gated behind live device queues) + let mut unmap_changes: std::collections::HashMap> = std::collections::HashMap::new(); for a in addrs { let Some(mapped) = self.follow.get(&a).map(|f| f.mapped) else { continue }; let backed = title_backed_in(a, &mut backed_run); @@ -1270,7 +1435,7 @@ impl Pages { None => { let pools = &mut self.pools; let pool = &mut self.pool; - let Some(mut fresh) = pool.take_batch(1, None, now, POOL_PAGES, || { + let Some(mut fresh) = pool.take_batch_fenced(1, None, now, safe_before, POOL_PAGES, || { let _timer = step(Step::Heap); let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) @@ -1286,7 +1451,7 @@ impl Pages { if let Some(t) = self.targets.get_mut(&k).filter(|t| t.mapped) { t.used.push(a); self.pages.get_mut(&a).unwrap().users += 1; - changes.entry(k).or_default().push((i, Some(tile))); + map_changes.entry(k).or_default().push((i, tile)); } } } else { @@ -1296,7 +1461,7 @@ impl Pages { t.used.swap_remove(at); self.release_tiles(vec![a], Vec::new(), now, false); } - changes.entry(k).or_default().push((i, None)); + unmap_changes.entry(k).or_default().push((i, a)); } } } @@ -1304,25 +1469,30 @@ impl Pages { f.mapped = backed; } } - if changes.is_empty() { + for (k, pairs) in unmap_changes { + let Some(total) = self.targets.get(&k).map(|t| t.total) else { continue }; + let raw = k as *mut c_void; + let Some(res) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; + self.unsealed_unmaps.push(PendingUnmapOp::Tiles { + res: res.clone(), + key: k, + total, + pairs, + }); + } + if map_changes.is_empty() { return; } - for (k, tiles) in changes { + for (k, tiles) in map_changes { let Some(total) = self.targets.get(&k).map(|t| t.total) else { continue }; let raw = k as *mut c_void; let Some(res) = ID3D12Resource::from_raw_borrowed(&raw) else { continue }; - let at: std::collections::HashMap> = tiles.into_iter().collect(); - let mut heaps: Vec = at.values().flatten().map(|t| t.0).collect(); + let at: std::collections::HashMap = tiles.into_iter().collect(); + let mut heaps: Vec = at.values().map(|t| t.0).collect(); heaps.sort_unstable(); heaps.dedup(); - let mut calls: Vec<(Option, Vec<(D3D12_TILE_RANGE_FLAGS, u32, u32)>)> = heaps - .into_iter() - .map(|h| (Some(h), update_ranges(total, D3D12_TILE_RANGE_FLAG_NONE, |i| at.get(&i).copied().flatten().filter(|t| t.0 == h).map(|t| t.1)))) - .collect(); - if at.values().any(|t| t.is_none()) { - calls.push((None, update_ranges(total, D3D12_TILE_RANGE_FLAG_NULL, |i| at.get(&i).filter(|t| t.is_none()).map(|_| 0)))); - } - for (h, ranges) in calls { + for h in heaps { + let ranges = update_ranges(total, D3D12_TILE_RANGE_FLAG_NONE, |i| at.get(&i).copied().filter(|t| t.0 == h).map(|t| t.1)); let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; let flags: Vec = ranges.iter().map(|r| r.0).collect(); @@ -1333,7 +1503,7 @@ impl Pages { 1, Some(&coord), Some(®ion), - h.map(|h| &self.pools[h as usize]), + &self.pools[h as usize], ranges.len() as u32, Some(flags.as_ptr()), Some(offsets.as_ptr()), @@ -1563,10 +1733,10 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), follows: Vec::new(), levels, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used: Vec::new(), used_extra: Vec::new(), follows: Vec::new(), levels, recycle: recycle_key }); true } else if let Some((used, used_extra, follows)) = pages.bind(dev, res, raw as usize, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, follows, levels: None, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used, used_extra, follows, levels: None, recycle: recycle_key }); true } else { false @@ -1584,30 +1754,53 @@ unsafe fn place_on_pages( Some(hr) } -/// Unmap a placed texture superseded by a placement with a different address range, returning its -/// unshared tiles (`extra_pages` and unshared tail pages) to the cooling pool immediately. +/// Defer unmapping a placed texture superseded by a placement with a different address range +/// until all live device queues finish in-flight work, and quarantine its unshared tiles behind +/// both the live queues and `pages.fence` (never calling `UpdateTileMappings(NULL)` concurrently +/// with executing title queues). pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { let key = res.as_raw() as usize; - let mut g = PAGES.lock().unwrap(); - let now = std::time::Instant::now(); - for pages in g.values_mut().flatten() { - let Some(t) = pages.targets.get_mut(&key) else { continue }; - if !t.mapped { - return; + let found_dev = { + let mut g = PAGES.lock().unwrap(); + let mut hit = None; + for (&dev_key, slot) in g.iter_mut() { + let Some(pages) = slot.as_mut() else { continue }; + let Some(t) = pages.targets.get_mut(&key) else { continue }; + if !t.mapped { + return; + } + let total = t.total; + let used = std::mem::take(&mut t.used); + let used_extra = std::mem::take(&mut t.used_extra); + let follows = std::mem::take(&mut t.follows); + t.mapped = false; + t.mapping_gen = t.mapping_gen.wrapping_add(1); + let gen = t.mapping_gen; + if let Some(l) = t.levels.as_mut() { + LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); + l.groups.iter_mut().for_each(|g| g.3 = false); + } + let unshared = pages.release_tiles_unshared(used, used_extra); + pages.unfollow(key, &follows); + pages.unsealed_unmaps.push(PendingUnmapOp::Whole { + res: res.clone(), + key, + gen, + total, + tiles: unshared, + }); + hit = Some(dev_key); + break; + } + hit + }; + if let Some(dev_key) = found_dev { + let mut dev: Option = None; + if res.GetDevice(&mut dev).is_ok() { + if let Some(dev) = dev { + seal_and_drain_unmaps(&dev, dev_key, None); + } } - let total = t.total; - let used = std::mem::take(&mut t.used); - let used_extra = std::mem::take(&mut t.used_extra); - let follows = std::mem::take(&mut t.follows); - t.mapped = false; - if let Some(l) = t.levels.as_mut() { - LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); - l.groups.iter_mut().for_each(|g| g.3 = false); - } - pages.unmap(res, total); - pages.release_tiles(used, used_extra, now, true); - pages.unfollow(key, &follows); - return; } } @@ -1630,6 +1823,7 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { // (lazy levels: they get their pages again with their next texels) if let Some(t) = pages.targets.get_mut(&key).filter(|t| t.levels.is_some()) { t.mapped = true; + t.mapping_gen = t.mapping_gen.wrapping_add(1); return true; } let Some((used, used_extra, follows)) = pages.bind(&dev, res, key, va, console_bytes, total) else { @@ -1640,6 +1834,7 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.used_extra = used_extra; t.follows = follows; t.mapped = true; + t.mapping_gen = t.mapping_gen.wrapping_add(1); } true } @@ -1686,6 +1881,32 @@ struct RetireQueue { fences: std::collections::HashMap, b impl RetireQueue { fn new() -> Self { Self { fences: std::collections::HashMap::new(), batches: Vec::new() } } + /// Signal one fence value on each queue in `queues`; returns `None` if any fence creation or + /// signal fails so callers never mistake a failed signal for an idle GPU. + fn signal_queues_with( + &mut self, + queues: &[(usize, Q)], + mut make_fence: impl FnMut() -> Option, + mut signal: impl FnMut(&Q, &F, u64) -> bool, + ) -> Option> { + let mut marks = Vec::with_capacity(queues.len()); + for (k, q) in queues { + let (f, v) = match self.fences.entry(*k) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => { + let Some(f) = make_fence() else { return None }; + e.insert((f, 0)) + } + }; + if !signal(q, f, *v + 1) { + return None; + } + *v += 1; + marks.push((f.clone(), *v)); + } + Some(marks) + } + /// Seal `heaps` behind `unmap_mark` and one fence signal per queue (signaled BEFORE queueing). /// Returns `heaps` immediately when zero marks were signaled and `unmap_mark` is `None`. fn retire_with(&mut self, heaps: Vec, unmap_mark: Option<(F, u64)>, queues: &[(usize, Q)], mut make_fence: impl FnMut() -> Option, mut signal: impl FnMut(&Q, &F, u64) -> bool) -> Vec { @@ -1759,6 +1980,112 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla }; } +/// Signal every live queue on `dev_key` using `RETIRE`'s per-queue fences (never locking `PAGES`). +unsafe fn signal_device_queues( + dev: &ID3D12Device, + dev_key: usize, + extra_queue: Option<&ID3D12CommandQueue>, +) -> Option> { + let queues = collect_device_queues(dev_key, extra_queue); + let mut guard = RETIRE.lock().unwrap(); + let map = guard.get_or_insert_with(std::collections::HashMap::new); + let rq = map.entry(dev_key).or_insert_with(RetireQueue::new); + rq.signal_queues_with( + &queues, + || dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok(), + |q, f, v| q.Signal(f, v).is_ok(), + ) +} + +/// Seal any unsealed deferred unmaps and/or a cooling-tile fence probe behind all live queues on +/// `dev_key`, drain every completed unmap batch onto `pages.queue` (skipping cancelled/remapped +/// targets and tiles), and drop popped COM resource references outside `PAGES.lock()`. +unsafe fn seal_and_drain_unmaps(dev: &ID3D12Device, dev_key: usize, extra_queue: Option<&ID3D12CommandQueue>) { + let (need_seal_unmaps, need_cool_probe, has_pending_or_probe) = { + let g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get(&dev_key) else { return }; + let need_unmaps = !pages.unsealed_unmaps.is_empty(); + let need_probe = pages.has_live_queues && pages.cool_probe.is_none() && (!pages.pool.cooling.is_empty() || !pages.idle.is_empty()); + let has_waiters = !pages.pending_unmaps.is_empty() || pages.cool_probe.is_some(); + (need_unmaps, need_probe, has_waiters) + }; + if !need_seal_unmaps && !need_cool_probe && !has_pending_or_probe { + return; + } + let marks = if need_seal_unmaps || need_cool_probe { + signal_device_queues(dev, dev_key, extra_queue) + } else { + None + }; + let probe_at = std::time::Instant::now(); + let mut drop_outside: Vec = Vec::new(); + { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { return }; + if !pages.unsealed_unmaps.is_empty() { + let ops = std::mem::take(&mut pages.unsealed_unmaps); + pages.pending_unmaps.push_back(PendingUnmapBatch { ops, marks: marks.clone() }); + } + if pages.has_live_queues && pages.cool_probe.is_none() && (!pages.pool.cooling.is_empty() || !pages.idle.is_empty()) { + if let Some(probe_marks) = marks { + pages.cool_probe = Some((probe_at, probe_marks)); + } + } + if let Some((at, ref probe_marks)) = pages.cool_probe { + if probe_marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v) { + pages.safe_cool_before = Some(pages.safe_cool_before.map_or(at, |prev| prev.max(at))); + pages.cool_probe = None; + } + } + let ready = drain_ready_unmap_batches(&mut pages.pending_unmaps, |f| f.GetCompletedValue()); + let mut newly_fenced_tiles: Vec = Vec::new(); + for op in ready { + match op { + PendingUnmapOp::Whole { res, key, gen, total, tiles } => { + match pages.targets.get(&key) { + Some(t) if t.mapping_gen != gen && t.mapped => { + if let Some(lv) = t.levels.as_ref() { + // Lazy texture was remapped without binding all levels: unmap only + // still-unmapped level groups so recycled tiles have no stale PTEs. + let lv_clone = lv.clone(); + pages.unmap_selected(&res, total, |tile_idx| { + lv_clone.groups.iter().any(|&(_, first, count, mapped)| { + !mapped && tile_idx >= first && tile_idx < first + count + }) + }); + } + } + _ => { + pages.unmap(&res, total); + } + } + newly_fenced_tiles.extend(tiles); + drop_outside.push(res); + } + PendingUnmapOp::Tiles { res, key, total, pairs } => { + if pages.targets.get(&key).is_some_and(|t| t.mapped) { + let still_unbacked: HashSet = pairs + .into_iter() + .filter(|&(_, addr)| pages.follow.get(&addr).is_none_or(|f| !f.mapped)) + .map(|(tile_idx, _)| tile_idx) + .collect(); + if !still_unbacked.is_empty() { + pages.unmap_selected(&res, total, |i| still_unbacked.contains(&i)); + } + } + drop_outside.push(res); + } + } + } + if !newly_fenced_tiles.is_empty() { + pages.flush_signal(); + pages.fenced_tiles.push_back((pages.value, newly_fenced_tiles)); + } + pages.drain_fenced_tiles(); + } + drop(drop_outside); +} + /// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device, /// release any previously retired heaps whose GPU fences have completed, and periodically (once /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind @@ -1773,10 +2100,13 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let now = std::time::Instant::now(); let mut newly_reclaimed = Vec::new(); let mut do_reclaim = false; + let mut need_unmap_work = false; let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { + pages.has_live_queues = true; + pages.drain_fenced_tiles(); let changed = std::mem::take(&mut *BACKING.lock().unwrap()); if !changed.is_empty() && !pages.follow.is_empty() { pages.apply_backing(&dev, &changed); @@ -1797,8 +2127,16 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { unmap_mark = Some((pages.fence.clone(), pages.value)); } } + need_unmap_work = !pages.unsealed_unmaps.is_empty() + || !pages.pending_unmaps.is_empty() + || pages.cool_probe.is_some() + || !pages.pool.cooling.is_empty() + || !pages.idle.is_empty(); } } + if need_unmap_work { + seal_and_drain_unmaps(&dev, dev_key, Some(queue)); + } if do_reclaim { newly_reclaimed.extend(ARENAS.lock().unwrap().sweep_dropped_for(dev_key, now)); } @@ -2927,4 +3265,57 @@ mod tests { drop(ID3D12Resource::from_raw(reused_raw as *mut c_void)); } } + + #[test] + fn pending_unmap_batches_wait_for_all_live_queues_and_hold_on_signal_error() { + use std::collections::VecDeque; + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let f1 = Arc::new(AtomicU64::new(0)); + let f2 = Arc::new(AtomicU64::new(0)); + let mut q: VecDeque>> = VecDeque::new(); + q.push_back(PendingUnmapBatch { + ops: vec!["unmap_a"], + marks: Some(vec![(f1.clone(), 1), (f2.clone(), 1)]), + }); + q.push_back(PendingUnmapBatch { + ops: vec!["unmap_failed_signal"], + marks: None, + }); + // While f2 is still behind, nothing drains. + f1.store(1, Ordering::SeqCst); + assert!(drain_ready_unmap_batches(&mut q, |f| f.load(Ordering::SeqCst)).is_empty()); + assert_eq!(q.len(), 2); + // Once both queues complete, batch 1 drains; batch 2 with failed signal stays held. + f2.store(1, Ordering::SeqCst); + assert_eq!(drain_ready_unmap_batches(&mut q, |f| f.load(Ordering::SeqCst)), vec!["unmap_a"]); + assert_eq!(q.len(), 1); + assert!(drain_ready_unmap_batches(&mut q, |f| f.load(Ordering::SeqCst)).is_empty()); + } + + #[test] + fn tile_pool_cooling_respects_gpu_fence_barrier_across_long_stalls() { + let t0 = Instant::now(); + let mut pool = TilePool::new(); + pool.add_heap_at(0, 4); + let taken = pool.take_batch(4, None, t0, 4, || None).unwrap(); + assert_eq!(pool.free_total, 0); + + // Tile 0 cooled at t0 + 1s; Tile 1 cooled at t0 + 2s. + pool.push_cooling(taken[0], t0 + Duration::from_secs(1)); + pool.push_cooling(taken[1], t0 + Duration::from_secs(2)); + + // Simulate an 8-second PSO compile stall where GPU fences only cleared up to t0 + 500ms: + // wall-clock COOL (2s) has long expired, yet neither tile may return to free! + let t_stall = t0 + Duration::from_secs(10); + pool.drain_cooling_before(t_stall, Some(t0 + Duration::from_millis(500))); + assert_eq!(pool.free_total, 0, "cooling tiles must stay held while GPU fence barrier has not passed them"); + + // Once GPU queues pass t0 + 1500ms, only Tile 0 returns; Tile 1 stays held. + pool.drain_cooling_before(t_stall, Some(t0 + Duration::from_millis(1500))); + assert_eq!(pool.free_total, 1); + + // Once GPU queues pass t0 + 2500ms, Tile 1 returns too. + pool.drain_cooling_before(t_stall, Some(t0 + Duration::from_millis(2500))); + assert_eq!(pool.free_total, 2); + } } From 202f649bc206afd5db91aa88f0c6fd227447f21a Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:32:25 +0000 Subject: [PATCH 116/258] D3D12.X: the GPU wait watchdog does not miss the wake of an armed wait The watchdog thread takes its pair's lock, reads ARMED_GPU_WAITS and sleeps on the condvar when it is 0. The arm in try_gpu_wait called notify_one() without taking that lock, so a notify falling between the watchdog's read of 0 and its cv.wait was lost: the watchdog slept with the wait armed, its timeout never ran, and a wait with no producer was never released on the CPU (no "did not complete" line). Only a later arm woke it. The notify now takes the pair's lock (notify_sync_watchdog). The lock is a leaf: the watchdog takes no other lock while it holds it, so the notifier's SYNC_GRAPH or queue locks cannot invert with it. The check and sleep move to sync_watchdog_sleep_if_idle, with an after_check hook the new test uses to arm and notify between the read and the wait; it fails on main (the watchdog does not wake within 2 s) and passes with the fix. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/list_x.rs | 72 ++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index a98420f984..ac5d92f7bc 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1618,13 +1618,11 @@ fn wait_expired(aw: &mut ArmedGpuWait, held: bool) -> bool { fn wake_sync_watchdog() { let pair = sync_watchdog_pair(&SYNC_WATCHDOG_WAKE, || { let _ = std::thread::Builder::new().name("xcl-sync-watchdog".into()).spawn(|| loop { - let (lock, cv) = SYNC_WATCHDOG_WAKE.get().unwrap(); - let guard = lock.lock().unwrap(); - if ARMED_GPU_WAITS.load(Ordering::Acquire) == 0 { - let _g = cv.wait(guard).unwrap(); + let pair = SYNC_WATCHDOG_WAKE.get().unwrap(); + let Some(guard) = sync_watchdog_sleep_if_idle(pair, &ARMED_GPU_WAITS, || {}) else { continue; - } - let _ = cv.wait_timeout(guard, Duration::from_millis(50)).unwrap(); + }; + let _ = pair.1.wait_timeout(guard, Duration::from_millis(50)).unwrap(); let (expired, rewinds) = { let mut g = SYNC_GRAPH.lock().unwrap(); let mut out: Vec<(u64, u64, ID3D12Fence, usize, i32, Option, Option, u64, u64, u64)> = Vec::new(); @@ -1714,6 +1712,31 @@ fn wake_sync_watchdog() { } }); }); + notify_sync_watchdog(pair); +} + +/// The watchdog's check for armed waits: none (`armed` is 0) – it sleeps until a +/// `notify_sync_watchdog` and returns `None`; some – the pair's lock, still held. The lock is held +/// from the check until `cv.wait` releases it; `after_check` runs in between (a test's pause). +fn sync_watchdog_sleep_if_idle<'a>( + pair: &'a (Mutex<()>, Condvar), + armed: &AtomicUsize, + after_check: impl FnOnce(), +) -> Option> { + let guard = pair.0.lock().unwrap(); + if armed.load(Ordering::Acquire) != 0 { + return Some(guard); + } + after_check(); + let _g = pair.1.wait(guard).unwrap(); + None +} + +/// Wake the watchdog after a wait was armed. The notify takes the pair's lock: without it, it can +/// fall between the watchdog's check (still 0) and its `cv.wait`, and the watchdog sleeps with the +/// wait armed and never releases it (the lock is a leaf: the watchdog takes no other lock with it). +fn notify_sync_watchdog(pair: &(Mutex<()>, Condvar)) { + let _g = pair.0.lock().unwrap(); pair.1.notify_one(); } @@ -6630,6 +6653,43 @@ mod tests { assert_eq!(seen, [true]); } + /// A wait armed between the watchdog's check (no wait armed) and its `cv.wait` wakes it: the + /// watchdog pauses there (`after_check`) until the arm's notify is done, or 200 ms when the + /// notify waits for the lock. A notify that does not take the lock is lost there, and the + /// watchdog sleeps with the wait armed (no "did not complete" release). + #[test] + fn a_wait_armed_during_the_watchdogs_check_wakes_it() { + use std::sync::{mpsc, Arc}; + let pair = Arc::new((Mutex::new(()), Condvar::new())); + let armed = Arc::new(AtomicUsize::new(0)); + let (checked_tx, checked_rx) = mpsc::channel(); + let (notified_tx, notified_rx) = mpsc::channel::<()>(); + let (woke_tx, woke_rx) = mpsc::channel(); + let (p, a) = (pair.clone(), armed.clone()); + let watchdog = std::thread::spawn(move || { + let slept = sync_watchdog_sleep_if_idle(&p, &a, || { + checked_tx.send(()).unwrap(); + let _ = notified_rx.recv_timeout(Duration::from_millis(200)); + }) + .is_none(); + woke_tx.send(slept).unwrap(); + }); + checked_rx.recv().unwrap(); + armed.fetch_add(1, Ordering::AcqRel); + notify_sync_watchdog(&pair); + // (the pause may be over already: then nobody receives this) + let _ = notified_tx.send(()); + let woke = woke_rx.recv_timeout(Duration::from_secs(2)); + if woke.is_err() { + // let the thread end before the test fails + pair.1.notify_one(); + } + watchdog.join().unwrap(); + assert_eq!(woke, Ok(true), "the watchdog slept through the arm's notify"); + // a wait already armed: no sleep, the lock comes back + assert!(sync_watchdog_sleep_if_idle(&pair, &armed, || unreachable!()).is_some()); + } + /// Submitting a DIRECT list with `Wait64BitValueX(va, >=, 0x677)` BEFORE submitting the /// COMPUTE list that recorded `Write64BitValueBottomOfPipeX(va, 0x677)` must bridge via /// GPU `queue.Wait`/`queue.Signal` without blocking the submitter thread for `WAIT_TIMEOUT`. From fb81714de7489e4495160a719932f1e7d2a5ed8a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:10:48 +0100 Subject: [PATCH 117/258] D3D12.X: register split segment allocators and gate/cache whole-form builds After a mid-list split (deferred compute dispatch or wait-after-Write64), list_x::split and list_x::deferred_segment created fresh raw PC command lists without calling lloc_pool::created_on. Subsequent ExecuteIndirect (and Dispatch) calls of split compute PSOs on those segments saw lloc_pool::recording_backing(list) == None, fell back out of the GPU slicer to whole_nonblocking, and spawned concurrent whole-form compile threads named xcl-whole-*. Because driver_compile_identified only gates threads prefixed xcl-pso, four 602-730 KiB whole-form builds ran ungated simultaneously (+11.3 GiB commit spike and 49s stall), and neither split pieces nor whole forms were loaded from or stored in the memory-mapped pipeline library (.plib). Fix all three pieces cleanly: - Call lloc_pool::created_on(p as usize, pc_alloc, ty.0) when creating fresh PC command lists in list_x::split and list_x::deferred_segment so ecording_backing stays populated across splits and indirect split compute dispatches stay on the GPU slicer path. - Route Chain::start_whole_async through a single background worker queue named xcl-pso-whole, ensuring at most one whole-form build runs at a time and driver_compile_identified gates it through compile_slots (BIG_COMPILES) and ig_compile_commit_free. - Load and store split compute pieces and whole forms in pso_lib (.plib) under a distinct sc-... key (preventing root-signature collisions with standard 6-parameter c-... compute PSOs). - Add unit tests for WHOLE_WORKER_THREAD_NAME gating prefix and split_plib_key distinctiveness. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/list_x.rs | 27 +++-- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 98 +++++++++++++++++-- 2 files changed, 107 insertions(+), 18 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ac5d92f7bc..55154d62b6 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -2974,14 +2974,20 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } let next_pc = match next_pc { Some(p) => p, - None => match real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(alloc), init_pso) { - Some(p) => p, - None => { - static CREATE_ERR: AtomicU64 = AtomicU64::new(0); - warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed")); - return None; + None => { + let pc_alloc = super::alloc_pool::current(alloc); + match real::create_raw_pc_command_list(dev.as_raw(), ty, pc_alloc, init_pso) { + Some(p) => { + super::alloc_pool::created_on(p as usize, pc_alloc, ty.0); + p + } + None => { + static CREATE_ERR: AtomicU64 = AtomicU64::new(0); + warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed")); + return None; + } } - }, + } }; // the next segment is a recording of its own (reset or made here, not through `cl_reset`) @@ -3125,7 +3131,12 @@ unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_CO }; let p = match super::title_list::pop_spare(wrapper).filter(emptied) { Some(p) => p, - None => real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(own), 0)?, + None => { + let pc_alloc = super::alloc_pool::current(own); + let made = real::create_raw_pc_command_list(dev.as_raw(), ty, pc_alloc, 0)?; + super::alloc_pool::created_on(made as usize, pc_alloc, ty.0); + made + } }; let ext = *(p as *const usize); pc:: i32>(p, PC_CLOSE)(p); diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 30d4cd3bb7..c701228407 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -41,10 +41,23 @@ fn scratch_budget() -> u64 { *B.get_or_init(|| std::env::var("XCL_SPLIT_SCRATCH_MB").ok().and_then(|v| v.trim().parse().ok()).filter(|&m| m > 0).unwrap_or(256u64).min(4096) << 20) } +/// Thread name for the dedicated background whole-form compiler. The `xcl-pso` prefix ensures +/// `driver_compile_identified` routes its driver compiles through `compile_slots` (`BIG_COMPILES` +/// / `MEDIUM_COMPILES` / `GIANT_COMPILES`) and `big_compile_commit_free` commit-headroom gating. +const WHOLE_WORKER_THREAD_NAME: &str = "xcl-pso-whole"; + +/// Deterministic cross-run `.plib` key for a split compute pipeline (piece or whole form). +/// Prefixed with `s` (`sc-...`) so 8-parameter split-root-signature PSOs never collide with +/// 6-parameter standard compute PSOs (`c-...`) in the shared pipeline library. +fn split_plib_key(dxil: &[u8], samplers: &[pso::StaticSampler], flags: i32) -> String { + format!("s{}", pso_lib::compute_key(dxil, samplers, flags)) +} + struct PipelineBuilder { device: ID3D12Device, create: PsoFn, signature: ID3D12RootSignature, + samplers: Vec, flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, @@ -52,11 +65,27 @@ struct PipelineBuilder { impl PipelineBuilder { unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Option { + let lib_key = split_plib_key(dxil, &self.samplers, self.flags.0); let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; + let lib_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(self.signature.as_raw()), + CS: bytecode(dxil), + NodeMask: self.node, + Flags: self.flags, + ..Default::default() + }; let mut raw = std::ptr::null_mut(); + if pso_lib::try_load_compute(self.device.as_raw(), &lib_key, &lib_desc, iid, &mut raw) && !raw.is_null() { + return Some(ID3D12PipelineState::from_raw(raw)); + } let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), dxil, self.record, iid, &mut raw, true); - (hr >= 0 && !raw.is_null()).then(|| ID3D12PipelineState::from_raw(raw)) + if hr >= 0 && !raw.is_null() { + pso_lib::store_pipeline(self.device.as_raw(), &lib_key, raw); + Some(ID3D12PipelineState::from_raw(raw)) + } else { + None + } } } @@ -107,21 +136,49 @@ impl Chain { if self.whole_started.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { return; } - let chain = Arc::clone(self); - let record = chain.builder.record; + if !enqueue_whole_async(Arc::clone(self)) { + self.whole_started.store(false, Ordering::Release); + } + } +} + +/// Queue a background whole-form build onto the single `xcl-pso-whole` worker so multiple split +/// programs never compile huge whole forms concurrently and every build goes through +/// `driver_compile_identified`'s `BIG_COMPILES` + commit-headroom gate. +fn enqueue_whole_async(chain: Arc) -> bool { + static QUEUE: LazyLock<(Mutex>>, std::sync::Condvar)> = + LazyLock::new(|| (Mutex::new(std::collections::VecDeque::new()), std::sync::Condvar::new())); + static WORKER_STARTED: AtomicBool = AtomicBool::new(false); + if WORKER_STARTED.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_ok() { if std::thread::Builder::new() - .name(format!("xcl-whole-{record:016x}")) - .spawn(move || { - if let Err(e) = unsafe { chain.whole() } { - chain.whole_failed.store(true, Ordering::Release); - crate::xlog_warn!("D3D12.X: background whole compute PSO for cs {record:016x} failed: {e}"); + .name(WHOLE_WORKER_THREAD_NAME.into()) + .spawn(|| { + let (lock, cv) = &*QUEUE; + loop { + let chain = { + let mut q = lock.lock().unwrap(); + while q.is_empty() { + q = cv.wait(q).unwrap(); + } + q.pop_front().unwrap() + }; + let record = chain.builder.record; + if let Err(e) = unsafe { chain.whole() } { + chain.whole_failed.store(true, Ordering::Release); + crate::xlog_warn!("D3D12.X: background whole compute PSO for cs {record:016x} failed: {e}"); + } } }) .is_err() { - self.whole_started.store(false, Ordering::Release); + WORKER_STARTED.store(false, Ordering::Release); + return false; } } + let (lock, cv) = &*QUEUE; + lock.lock().unwrap().push_back(chain); + cv.notify_one(); + true } static CHAINS: LazyLock>>> = LazyLock::new(Default::default); @@ -134,7 +191,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; let rs = signature.as_raw() as usize; let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, - flags: desc.Flags, node: desc.NodeMask, record }); + samplers: samplers.to_vec(), flags: desc.Flags, node: desc.NodeMask, record }); let jobs = (0..plan.pieces.len()).map(|i| { let plan = plan.clone(); let builder = builder.clone(); @@ -719,4 +776,25 @@ mod tests { assert_eq!(super::indirect_rounds(&[[100, 1, 1]], 100, 8, 16), 10); assert_eq!(super::indirect_rounds(&[[100, 40, 1]], 100, 0, 16), 16); } + + #[test] + fn whole_worker_thread_name_matches_driver_compile_gate() { + assert!( + super::WHOLE_WORKER_THREAD_NAME.starts_with("xcl-pso"), + "whole-form background worker must carry the xcl-pso prefix so driver_compile_identified gates it" + ); + } + + #[test] + fn split_plib_key_is_distinct_from_standard_compute_key() { + let dxil = b"DXBC-fake-split-whole-dxil"; + let samplers = [([1, 2, 3, 4], false)]; + let std_key = super::super::pso_lib::compute_key(dxil, &samplers, 0); + let split_key = super::split_plib_key(dxil, &samplers, 0); + assert!(split_key.starts_with("sc-")); + assert_ne!(split_key, std_key); + assert_eq!(split_key, super::split_plib_key(dxil, &samplers, 0)); + assert_ne!(split_key, super::split_plib_key(dxil, &[], 0)); + assert_ne!(split_key, super::split_plib_key(dxil, &samplers, 1)); + } } From 378cc2af5a6e574e3cc01d7907c00ea07ef02b93 Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:41:54 +0000 Subject: [PATCH 118/258] D3D12.X: the same root signature set again keeps the root arguments SetComputeRootSignature / SetGraphicsRootSignature zeroed the root arguments on every call. In D3D12 a redundant set of the same root signature leaves the existing bindings valid; only a different one makes them stale. A title that sets the same signature again and then binds only some parameters left the others at address 0 in the translated shader's argument table. The arguments are now cleared only when the layout is not the one already set (compared as the same layout object, so a signature made at a freed one's address still clears). The console list replay does the same. Reset and ClearState still clear everything. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/bind.rs | 54 ++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/console_list.rs | 17 ++++++- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 806b10486c..018f4b2445 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -521,7 +521,11 @@ fn put(list: *mut c_void, i: u32, offset: u32, bytes: &[u8]) { pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_void, rs: *mut c_void) { let layout = console_list::layout_of(rs as usize); with(this, |s| { - s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + // the same root signature again keeps the bound arguments (D3D12: only a different + // one invalidates them) + if !console_list::same_layout(&s.layout_gfx, &layout) { + s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + } s.layout_gfx = layout; s.rs_gfx = rs as usize; s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); @@ -3236,7 +3240,9 @@ unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { let layout = console_list::layout_of(rs as usize); with(this, |s| { - s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + if !console_list::same_layout(&s.layout, &layout) { + s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + } s.layout = layout; s.rs_cs = rs as usize; s.args_gen_cs = s.args_gen_cs.wrapping_add(1); @@ -3918,6 +3924,50 @@ void main(uint t : SV_GroupIndex) { forget(list); } + #[test] + fn the_same_root_signature_again_keeps_the_root_arguments() { + let list = 0x7100_0301usize as *mut c_void; + let (rs_a, rs_b) = (0x7100_0310usize, 0x7100_0320usize); + console_list::note_root_signature(rs_a, &test_rts0_blob()); + console_list::note_root_signature(rs_b, &test_rts0_blob()); + let set = |gfx: bool, rs: usize| unsafe { + if gfx { set_graphics_root_signature(list, rs as *mut c_void) } else { set_compute_root_signature(list, rs as *mut c_void) } + }; + let args = |gfx: bool| with(list, |s| if gfx { s.args_gfx.clone() } else { s.args.clone() }); + reset(list, 0x7100_0330, 0); + set(false, rs_a); + set(true, rs_a); + unsafe { set_compute_root_constant(list, 0, 0xABCD, 0) }; + assert!(args(false).iter().any(|b| *b != 0)); + assert!(args(true).iter().all(|b| *b == 0), "compute and graphics arguments are separate"); + // the same signature again: the arguments stay + set(false, rs_a); + assert_eq!(&args(false)[..4], &0xABCDu32.to_le_bytes()); + // graphics is independent: a different one there leaves compute alone + unsafe { set_graphics_root_constant(list, 0, 0x1234, 0) }; + set(true, rs_b); + assert!(args(true).iter().all(|b| *b == 0)); + assert_eq!(&args(false)[..4], &0xABCDu32.to_le_bytes()); + // a different signature clears + set(false, rs_b); + assert!(args(false).iter().all(|b| *b == 0)); + // a signature re-made at the same address is a different one + unsafe { set_compute_root_constant(list, 0, 0xABCD, 0) }; + console_list::note_root_signature(rs_b, &test_rts0_blob()); + set(false, rs_b); + assert!(args(false).iter().all(|b| *b == 0)); + // Reset and ClearState clear, so the signature set again afterwards starts empty + unsafe { set_compute_root_constant(list, 0, 0xABCD, 0) }; + clear_state(list, 0); + set(false, rs_b); + assert!(args(false).iter().all(|b| *b == 0)); + unsafe { set_compute_root_constant(list, 0, 0xABCD, 0) }; + reset(list, 0x7100_0330, 0); + set(false, rs_b); + assert!(args(false).iter().all(|b| *b == 0)); + forget(list); + } + #[repr(C)] struct FakeAdoptedList { vt: *const usize, diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index b73e882ff6..b8f7efaa91 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -237,6 +237,16 @@ pub(super) fn layout_of(rs: usize) -> Option> { LAYOUTS.lock().unwrap().as_ref()?.get(&rs).cloned() } +/// Both are the layout of the same root signature object (not merely of one at the same +/// address: a signature made at a freed one's address has a layout of its own). +pub(super) fn same_layout(a: &Option>, b: &Option>) -> bool { + match (a, b) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (None, None) => true, + _ => false, + } +} + // --------------------------------------------------------------------------------------- // pipeline states // --------------------------------------------------------------------------------------- @@ -857,8 +867,11 @@ pub unsafe fn close(obj: *mut c_void) -> Result { at += 7; } else if w0 == RS_MARKER { let r = get(2) as usize | (get(3) as usize) << 32; - layout = layout_of(r); - table = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + let new = layout_of(r); + if !same_layout(&layout, &new) { + table = vec![0u8; new.as_ref().map_or(0, |l| l.size as usize)]; + } + layout = new; at += 4; } else if w0 == HEAPS_MARKER { let n = get(1) as usize; From a080eb6a2f5317a5f3d0bb46bff3ab510e06d711 Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:43:26 +0000 Subject: [PATCH 119/258] D3D12.X: a same-list write drops a later wait only when its value meets it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `wait_memory` dropped a `Wait32/64BitValueX` whenever the same open list had already written an overlapping address (`has_prior_write`, since 3dfbcfbd). The reason for that drop is that the wait would otherwise be polled before the list is submitted, while the write that satisfies it is still in the unsubmitted list. That only holds when the value the list wrote meets the comparison. A list that resets a counter (`Write64BitValue…X(X, 0)`) and then waits `X >= 1` for another queue to raise it lost its wait: the list ran without waiting for the producer. The list now keeps the value of its last immediate write (`write`) per address. The wait is dropped when that value, masked, meets the comparison (`compare_u64`), or when the last write over the address has no known value (fill, copy, a partial write, or a split segment), as before. Otherwise it is recorded like any other wait. Test `a_wait_after_an_own_write_is_dropped_only_when_the_written_value_meets_it`: all eight comparison functions, 32 and 64 bit, the Wait32 mask, the last of several writes, and a fill over the value. With the drop condition of `main` it fails on the first case (write 0, wait >= 1: 0 waits kept, 1 expected); with this change it passes (5 of 5 runs). `cargo test --workspace --no-fail-fast -- --test-threads=4`, twice: 1420 passed, 4 failed, 46 ignored; the 4 failures are `gpu::dxil::fuzz_tests::fuzz_validate_and_gpu_0..3` (E_OUTOFMEMORY from CreateComputePipelineState). Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/list_x.rs | 91 ++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 55154d62b6..688c5b1431 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -719,6 +719,9 @@ struct ListState { occlusion: Occlusion, /// UMA address ranges written by this list since last Reset/KickoffX written_ranges: Vec<(u64, u64)>, + /// `(va, bytes, value)` of this list's last immediate write (`write`) to each address; a later + /// write over it of unknown value (fill, copy) removes it + written_values: Vec<(u64, u64, u64)>, /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, /// `CopyMemoryToMemoryX`, timestamps) to copy back to the CPU view after execution. sparse_writes: Vec<(usize, usize)>, @@ -756,6 +759,7 @@ impl ListState { return; } let end = va.saturating_add(size); + self.written_values.retain(|&(s, n, _)| !(va < s + n && s < end)); if self.written_ranges.len() < MAX_WRITTEN_RANGES { self.written_ranges.push((va, end)); } else if let Some(last) = self.written_ranges.last_mut() { @@ -968,6 +972,7 @@ pub(super) fn clear_segment_state(list: usize) { if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { s.occlusion = Occlusion::default(); s.written_ranges.clear(); + s.written_values.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); @@ -1127,6 +1132,16 @@ fn note_write(list: usize, va: u64, size: u64) { LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); } +/// `note_write` for an immediate write of `words`, keeping its value for `wait_memory`. +fn note_write_value(list: usize, va: u64, words: &[u32]) { + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(list).or_default(); + s.note_write(va, 4 * words.len() as u64); + if words.len() <= 2 && s.written_values.len() < MAX_WRITTEN_RANGES { + s.written_values.push((va, 4 * words.len() as u64, words.iter().rev().fold(0, |v, &w| v << 32 | w as u64))); + } +} + // --------------------------------------------------------------------------------------- // per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX // --------------------------------------------------------------------------------------- @@ -2612,7 +2627,7 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF } return warn(&N, what, format_args!("{va:#x} is not in unified memory")); }; - note_write(list as usize, va, n); + note_write_value(list as usize, va, words); let params: Vec = words.iter().enumerate().map(|(i, &w)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + 4 * i as u64, Value: w }).collect(); let modes = vec![mode; words.len()]; type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); @@ -3174,7 +3189,9 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va let need_split = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); - if s.has_prior_write(va, n) { + // (only when the value it wrote meets the wait: else another queue is to produce it) + let own = s.written_values.iter().find(|&&(w, len, _)| w == va && len == n); + if s.has_prior_write(va, n) && own.is_none_or(|&(_, _, v)| compare_u64(comparison, v & mask, value) == Some(true)) { return; } if s.write64_signals.is_empty() { @@ -3538,6 +3555,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let sparse_writes = s.clear_sparse_writes(); let write64_signals = s.clear_write64_signals(); s.written_ranges.clear(); + s.written_values.clear(); let cpu_writes = std::mem::take(&mut s.cpu_writes); let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); let pred_buf = s.pred_buf.as_ref().map(|r| r.as_raw() as usize); @@ -3634,6 +3652,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.pred_in_state = false; s.occlusion = Occlusion { active: None, ended_early }; s.written_ranges.clear(); + s.written_values.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); @@ -4535,6 +4554,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.depth_bounds = None; s.occlusion = Occlusion::default(); s.written_ranges.clear(); + s.written_values.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); @@ -5465,6 +5485,73 @@ mod tests { assert!(!s.has_prior_write(0x0FF8, 8)); } + /// A wait on an address the same list wrote is dropped only when the value that write left + /// meets it: a list that resets a counter to 0 and then waits for another queue to raise it + /// keeps its wait. + #[test] + fn a_wait_after_an_own_write_is_dropped_only_when_the_written_value_meets_it() { + let cell64 = AtomicU64::new(0); + let cell32 = AtomicU32::new(0); + let (va64, va32) = (&cell64 as *const AtomicU64 as u64, &cell32 as *const AtomicU32 as u64); + let mut token = 0usize; + let list = (&mut token as *mut usize).cast::(); + // records the writes (as `write` does) and the wait, and returns the waits left on the list + let kept = |writes: &[(u64, &[u32])], wait: &dyn Fn()| -> usize { + for &(va, words) in writes { + note_write_value(list as usize, va, words); + } + wait(); + let n = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).map_or(0, |s| s.pending_waits.len()); + on_release(list as usize); + n + }; + let w64 = |v: u64| [v as u32, (v >> 32) as u32]; + use D3D12_COMPARISON_FUNC as F; + // (value written, comparison, value waited for, wait kept) + for (written, op, wanted, keep) in [ + (0u64, D3D12_COMPARISON_FUNC_GREATER_EQUAL, 1u64, true), + (5, D3D12_COMPARISON_FUNC_GREATER_EQUAL, 1, false), + (0xFFFF_FFFF, D3D12_COMPARISON_FUNC_GREATER_EQUAL, 1 << 32, true), + (0, D3D12_COMPARISON_FUNC_EQUAL, 1, true), + (1, D3D12_COMPARISON_FUNC_EQUAL, 1, false), + (1, D3D12_COMPARISON_FUNC_NOT_EQUAL, 1, true), + (0, D3D12_COMPARISON_FUNC_NOT_EQUAL, 1, false), + (1, D3D12_COMPARISON_FUNC_LESS, 1, true), + (0, D3D12_COMPARISON_FUNC_LESS, 1, false), + (2, D3D12_COMPARISON_FUNC_LESS_EQUAL, 1, true), + (1, D3D12_COMPARISON_FUNC_LESS_EQUAL, 1, false), + (1, D3D12_COMPARISON_FUNC_GREATER, 1, true), + (2, D3D12_COMPARISON_FUNC_GREATER, 1, false), + (0, D3D12_COMPARISON_FUNC_ALWAYS, 1, false), + (0, D3D12_COMPARISON_FUNC_NEVER, 1, false), + ] { + let F(op) = op; + let got = kept(&[(va64, &w64(written))], &|| unsafe { wait64_x(list, va64, op as u32, wanted, 0, 0) }); + assert_eq!(got, keep as usize, "64-bit: wrote {written:#x}, wait op {op} {wanted:#x}"); + if wanted <= u32::MAX as u64 && written <= u32::MAX as u64 { + let got = kept(&[(va32, &[written as u32])], &|| unsafe { wait32_x(list, va32, op as u32, wanted as u32, u32::MAX, 0) }); + assert_eq!(got, keep as usize, "32-bit: wrote {written:#x}, wait op {op} {wanted:#x}"); + } + } + let ge = D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32; + let eq = D3D12_COMPARISON_FUNC_EQUAL.0 as u32; + // the mask applies to the written value too + assert_eq!(kept(&[(va32, &[0x1234_00FF])], &|| unsafe { wait32_x(list, va32, eq, 0xFF, 0xFF, 0) }), 0); + assert_eq!(kept(&[(va32, &[0x0000_12FE])], &|| unsafe { wait32_x(list, va32, eq, 0xFF, 0xFF, 0) }), 1); + // the last write before the wait counts + assert_eq!(kept(&[(va64, &w64(5)), (va64, &w64(0))], &|| unsafe { wait64_x(list, va64, ge, 1, 0, 0) }), 1); + assert_eq!(kept(&[(va64, &w64(0)), (va64, &w64(5))], &|| unsafe { wait64_x(list, va64, ge, 1, 0, 0) }), 0); + // a write to another address leaves the wait alone + assert_eq!(kept(&[(va32, &[5])], &|| unsafe { wait64_x(list, va64, ge, 1, 0, 0) }), 1); + // a write of unknown value over it (a fill or a copy) still drops the wait, as before + let fill = || { + note_write_value(list as usize, va64, &w64(0)); + note_write(list as usize, va64, 8); + unsafe { wait64_x(list, va64, ge, 1, 0, 0) } + }; + assert_eq!(kept(&[], &fill), 0); + } + #[test] fn execute_with_waits_splits_batches_before_unsatisfied_list() { // Use synthetic non-zero list pointers distinct from real COM objects. From e54df0f05a1e4a1d8d46be61b6ffce1948d7df2e Mon Sep 17 00:00:00 2001 From: Tiago Leal <183942127+tiagonleal@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:41:55 +0000 Subject: [PATCH 120/258] D3D12.X: forget a command signature's root-changing kind when its address is reused ROOT_SIGNATURES only ever inserted. If a command signature with root arguments was freed and a simple one (Dispatch, DrawIndexed) was made at the same address, every ExecuteIndirect with it and a translated pipeline was skipped, with no counter and no log. It is now noted at every creation, as DISPATCH_SIGNATURES is. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/bind.rs | 26 ++++++++++++++++++---- crates/xcl/src/hle/d3d12x/device_x.rs | 31 +++++++++++++-------------- 2 files changed, 37 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 018f4b2445..ad4de4301b 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -604,8 +604,15 @@ struct DispatchMeshSig { static DISPATCH_MESH_SIGS: Mutex>> = Mutex::new(None); -pub(super) fn note_root_changing_signature(sig: usize) { - ROOT_SIGNATURES.lock().unwrap().get_or_insert_with(Default::default).insert(sig); +/// noted at every creation, so a signature made at a freed one's address does not keep its kind +pub(super) fn note_root_changing_signature(sig: usize, changes: bool) { + let mut s = ROOT_SIGNATURES.lock().unwrap(); + let s = s.get_or_insert_with(Default::default); + if changes { + s.insert(sig); + } else { + s.remove(&sig); + } } /// command signatures with a Dispatch argument (noted at every creation, so a signature made @@ -4049,7 +4056,7 @@ void main(uint t : SV_GroupIndex) { let standin_ok = 0x7200_0001usize; let real_ok = 0x7200_0002usize; let sig_root_changing = 0x7200_00F0usize; - note_root_changing_signature(sig_root_changing); + note_root_changing_signature(sig_root_changing, true); pso_async::submit( standin_ok, @@ -4147,6 +4154,17 @@ void main(uint t : SV_GroupIndex) { assert!(!real::is_console_compute(standin_fail), "a released pipeline's address does not stay a console one"); } + #[test] + fn a_command_signature_made_at_a_freed_ones_address_does_not_keep_its_kind() { + let sig = 0x7230_00F0usize; + let changing = |s: usize| ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|set| set.contains(&s)); + note_root_changing_signature(sig, true); + assert!(changing(sig)); + // the signature is freed; a simple one is made at its address + note_root_changing_signature(sig, false); + assert!(!changing(sig)); + } + #[test] fn execute_indirect_skips_failed_shared_console_compute_standin() { let mut orig_vt = [0usize; 64]; @@ -4183,7 +4201,7 @@ void main(uint t : SV_GroupIndex) { let sig_dispatch = 0x7210_00F8usize; let sig_root_changing = 0x7210_00F0usize; note_signature_dispatches(sig_dispatch, true); - note_root_changing_signature(sig_root_changing); + note_root_changing_signature(sig_root_changing, true); pso_async::submit_lazy(shell_fail, true, Box::new(|| 0), 0); pso_async::shared(shell_fail, shared_driver); diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 3e6777f9d8..b10da3e1da 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1288,24 +1288,23 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let needs_root = list.iter().any(|a| (5..=8).contains(&a[0])); pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes()); let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv); - if hr >= 0 && !ppv.is_null() { - if needs_root { - super::bind::note_root_changing_signature(*ppv as usize); - } else if let Some(idx) = list.iter().position(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32) { - let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); - let byte_stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); - let mut dispatch_list = list.clone(); - dispatch_list[idx][0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; - let mut dpc = pc; - dpc[8..16].copy_from_slice(&(dispatch_list.as_ptr() as u64).to_le_bytes()); - let mut companion: *mut c_void = std::ptr::null_mut(); - let hr2 = real::dev_create_command_signature(this, dpc.as_ptr() as usize, 0, riid, &mut companion); - if hr2 >= 0 && !companion.is_null() { - super::bind::note_dispatch_mesh_signature(*ppv as usize, companion as usize, byte_stride, offset); + if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::bind::note_root_changing_signature(*ppv as usize, needs_root); + if !needs_root { + if let Some(idx) = list.iter().position(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH.0 as u32) { + let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); + let byte_stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); + let mut dispatch_list = list.clone(); + dispatch_list[idx][0] = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32; + let mut dpc = pc; + dpc[8..16].copy_from_slice(&(dispatch_list.as_ptr() as u64).to_le_bytes()); + let mut companion: *mut c_void = std::ptr::null_mut(); + let hr2 = real::dev_create_command_signature(this, dpc.as_ptr() as usize, 0, riid, &mut companion); + if hr2 >= 0 && !companion.is_null() { + super::bind::note_dispatch_mesh_signature(*ppv as usize, companion as usize, byte_stride, offset); + } } } - } - if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); let stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); let dispatch_only = list.len() == 1 && list[0][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32 && stride >= 12 && stride % 4 == 0; From 1f6588b423f1b93ad22d79e848b6c890a05725f5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:11:21 +0100 Subject: [PATCH 121/258] D3D12.X: isolate >=900 KiB giant compiles, skip heavy preload, fix indirect-branch BVH check In the Wave 10 run (202f649b), xcl-pso-pre-* preload worker 25276 speculatively launched 95cc13288a27a96e (71,816 B console CS -> 1,061,720 B DXIL) at t=156.5s at THREAD_PRIORITY_LOWEST, holding BIG_COMPILES slot #1 (because GIANT_DRIVER_COMPILE was 4 MiB) and ~3-4 GB of compiler commit for >144s through t=300s. - Lower GIANT_DRIVER_COMPILE from 4 MiB to 900 KiB in real.rs so >= 900 KiB monster DXIL shaders compile in their own dedicated 1-slot GIANT_COMPILES lane without starving MEDIUM_COMPILES (256-512 KiB) or BIG_COMPILES (512-900 KiB). - Add SubmitFlags + submit_lazy_with_flags / submit_with_flags in pso_async.rs and set spared/bvh_traversal/deprioritized atomically before inserting into PENDING or queues; exclude deprioritized/heavy/BVH/spared pipelines from speculative xcl-pso-pre-* preloading so THREAD_PRIORITY_LOWEST preload workers never launch >1 MiB compiles ahead of first use. - Mark heavy deprioritized producers wanted before enqueueing in resolve_wait_for so needed producer dispatches jump straight to the front of PsoQueue. - Scan RDNA2 compute machine code directly for IMAGE_BVH*_INTERSECT_RAY in gpu/effects.rs (100% cache-safe; not in build.rs) so large RT shaders with s_setpc_b64/s_swappc_b64 indirect branches are still recognized as BVH traversal shaders instead of returning false when conservative effects::of() returns None. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/effects.rs | 34 ++++++++++- crates/xcl/src/hle/d3d12x/pso_async.rs | 79 ++++++++++++++++++++++---- crates/xcl/src/hle/d3d12x/real.rs | 32 ++++++----- 3 files changed, 118 insertions(+), 27 deletions(-) diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index 05ef4eacb1..750b391f1d 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -119,10 +119,35 @@ pub fn compute_code_len(blob: &[u8]) -> Option { compute_code(blob).map(|c| c.len()) } +/// Whether raw RDNA2 compute machine code `code` contains `IMAGE_BVH_INTERSECT_RAY` or +/// `IMAGE_BVH64_INTERSECT_RAY`. Unlike [`of`], this does not bail out on indirect branches +/// (`s_setpc_b64` / `s_swappc_b64` switch tables or subroutines), which large RT shaders use. +pub fn code_uses_bvh_intersect(code: &[u8]) -> bool { + let mut off = 0; + let mut ended = false; + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { + if ended { + break; + } + return false; + }; + if ended && d.inst.name == "S_CODE_END" { + break; + } + if d.enc.name == "ENC_MIMG" && (d.inst.name == "IMAGE_BVH_INTERSECT_RAY" || d.inst.name == "IMAGE_BVH64_INTERSECT_RAY") { + return true; + } + off += d.len; + ended |= d.inst.flags & rdna2::F_TERMINATOR != 0; + } + false +} + /// Whether the compute shader `blob` issues `IMAGE_BVH_INTERSECT_RAY` or `IMAGE_BVH64_INTERSECT_RAY`. pub fn uses_bvh_intersect(blob: &[u8]) -> bool { let Some(code) = compute_code(blob) else { return false }; - of(&code).is_some_and(|e| e.bvh_intersect) + code_uses_bvh_intersect(&code) } #[cfg(test)] @@ -146,6 +171,13 @@ mod tests { assert_eq!(of(&asm(&[MOV, IMAGE_STORE, END])), Some(Effects { memory: false, images: true, bvh_intersect: false, instructions: 3 })); let bvh: (&str, &str, &[(&str, u64)]) = ("IMAGE_BVH64_INTERSECT_RAY", "ENC_MIMG", &[("DMASK", 15), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]); assert_eq!(of(&asm(&[bvh, END])).map(|e| (e.memory, e.images, e.bvh_intersect)), Some((false, false, true))); + assert!(code_uses_bvh_intersect(&asm(&[bvh, END]))); + // Indirect jump (`s_setpc_b64`) makes conservative `of()` return None, yet BVH detection + // must still recognize `IMAGE_BVH64_INTERSECT_RAY` so large RT shaders are classified as BVH. + let indirect: (&str, &str, &[(&str, u64)]) = ("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 2)]); + let rt_with_indirect = asm(&[indirect, bvh, END]); + assert_eq!(of(&rt_with_indirect), None); + assert!(code_uses_bvh_intersect(&rt_with_indirect)); let image_atomic: (&str, &str, &[(&str, u64)]) = ("IMAGE_ATOMIC_ADD", "ENC_MIMG", &[("DMASK", 1), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]); assert_eq!(of(&asm(&[image_atomic, END])).map(|e| (e.memory, e.images)), Some((false, true))); // every way into memory another pass or an indirect call reads diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 5ab2374b15..3b77e92091 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -519,9 +519,24 @@ pub fn release(p: usize) { } } +/// Initial scheduling classification set atomically before a `Pending` entry is visible to +/// preload or normal workers (avoids any race where `xcl-pso-pre-*` pops a heavy/BVH pipeline +/// before its flags are applied). +#[derive(Clone, Copy, Default)] +pub struct SubmitFlags { + pub spared: bool, + pub bvh_traversal: bool, + pub deprioritized: bool, +} + /// `standin` went to the title; `job` builds the real pipeline on a worker. pub fn submit(standin: usize, compute: bool, job: Job) { - submit_as(standin, compute, job, true, 0); + submit_as(standin, compute, job, true, 0, SubmitFlags::default()); +} + +/// Like [`submit`], with initial scheduling flags applied before the entry is queued. +pub fn submit_with_flags(standin: usize, compute: bool, job: Job, flags: SubmitFlags) { + submit_as(standin, compute, job, true, 0, flags); } /// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get @@ -537,10 +552,17 @@ pub fn lazy() -> bool { /// `submit`, sent to the workers only on its first `resolve` (`lazy`) – or now, at a low /// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`). pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { - submit_as(standin, compute, job, false, key); + submit_as(standin, compute, job, false, key, SubmitFlags::default()); +} + +/// Like [`submit_lazy`], applying `flags` atomically before insertion and excluding heavyweight / +/// BVH / spared pipelines from speculative `xcl-pso-pre-*` preloading so `THREAD_PRIORITY_LOWEST` +/// workers never stall `BIG_COMPILES`/`GIANT_COMPILES` on unreferenced >1 MiB shaders. +pub fn submit_lazy_with_flags(standin: usize, compute: bool, job: Job, key: u64, flags: SubmitFlags) { + submit_as(standin, compute, job, false, key, flags); } -fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { +fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, flags: SubmitFlags) { let p = Arc::new(Pending { job: Mutex::new(Some(job)), sent: std::sync::atomic::AtomicBool::new(send), @@ -553,9 +575,9 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { used: Default::default(), orphan: Default::default(), late: Default::default(), - spared: Default::default(), - bvh_traversal: Default::default(), - deprioritized: Default::default(), + spared: std::sync::atomic::AtomicBool::new(flags.spared), + bvh_traversal: std::sync::atomic::AtomicBool::new(flags.bvh_traversal), + deprioritized: std::sync::atomic::AtomicBool::new(flags.deprioritized), demand: Default::default(), }); PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); @@ -565,7 +587,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { }); if send { enqueue(p); - } else if used::known(key) { + } else if used::known(key) && !flags.deprioritized && !flags.bvh_traversal && !flags.spared { if let Some(q) = preload() { q.list.lock().unwrap().push_back(p); q.cv.notify_one(); @@ -697,6 +719,14 @@ fn preload() -> Option<&'static Preload> { drop_unstarted_job(&p); continue; } + // Never speculatively compile deprioritized/heavy/BVH/spared pipelines at + // THREAD_PRIORITY_LOWEST; leave `p.job` untouched until actually bound. + if p.deprioritized.load(Ordering::Acquire) + || p.bvh_traversal.load(Ordering::Acquire) + || p.spared.load(Ordering::Acquire) + { + continue; + } // Pause speculative preload under low commit headroom (< 4 GiB) unless a bind // actively wants this pipeline; leave `p.job` untouched so binds can take it. while mem_throttle_enabled() @@ -1258,9 +1288,10 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { return resolve_within(&p, pso, budget); } if p.deprioritized.load(Ordering::Acquire) && !building_here() { - // Heavy non-RT producer compute PSO: compile on an `xcl-pso-*` worker (where `BIG_COMPILES` - // gating bounds concurrent driver compiles) and wait until ready so the producer dispatch - // is NEVER skipped. + // Heavy non-RT producer compute PSO: mark wanted BEFORE enqueueing so it jumps straight + // to the front of `PsoQueue` on `xcl-pso-*` workers (under `BIG_COMPILES`/`GIANT_COMPILES` + // gating) and wait until ready so the producer dispatch is NEVER skipped. + p.want(); if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p.clone()); } @@ -1269,8 +1300,8 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { if let Some(job) = job { complete(&p, job()); } + p.want(); } - p.want(); let mut done = p.done.lock().unwrap(); while !*done { done = p.cv.wait(done).unwrap(); @@ -1540,4 +1571,30 @@ mod pso_queue_tests { assert!(should_pause_preload(Some(PRELOAD_PAUSE_COMMIT - 1))); assert!(should_pause_preload(Some(0))); } + + #[test] + fn heavy_and_bvh_pipelines_are_not_speculatively_preloaded() { + let heavy_standin = 0x7E57_B0D1usize; + let heavy_key = 0x5EED_B0D1u64; + used::earlier_run_used(heavy_key); + let ran = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let ran_job = ran.clone(); + submit_lazy_with_flags( + heavy_standin, + true, + Box::new(move || { + ran_job.store(true, Ordering::Release); + 0x5D5D + }), + heavy_key, + SubmitFlags { spared: false, bvh_traversal: false, deprioritized: true }, + ); + std::thread::sleep(std::time::Duration::from_millis(80)); + assert!(!ran.load(Ordering::Acquire), "heavy deprioritized PSO must not be speculatively preloaded"); + assert!(is_pending(heavy_standin)); + // Once actually bound, resolve_wait compiles it on a worker and returns the real PSO. + assert_eq!(resolve_wait_for(heavy_standin, None), 0x5D5D); + assert!(ran.load(Ordering::Acquire)); + let _ = released(heavy_standin); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a6b67b2ff7..cbe13c36dd 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4363,7 +4363,10 @@ impl Drop for SlotGuard { const LARGE_DRIVER_COMPILE: usize = 512 << 10; static MEDIUM_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Medium }; static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Big }; -const GIANT_DRIVER_COMPILE: usize = 4 << 20; +/// True giant DXIL shaders (`>= 900 KiB`, e.g. >1 MiB RT/compute shaders that can take >60-140s +/// in the driver compiler) get their own dedicated 1-slot lane so they never starve `MEDIUM_COMPILES` +/// (`256-512 KiB`) or `BIG_COMPILES` (`512-900 KiB`). +const GIANT_DRIVER_COMPILE: usize = 900 << 10; static GIANT_COMPILES: Slots = Slots::fixed(1, 1); fn compile_slots(bytes: usize) -> &'static Slots { @@ -4602,8 +4605,10 @@ mod big_compile_tests { fn giant_driver_compiles_have_their_own_lane() { assert!(std::ptr::eq(compile_slots(LARGE_DRIVER_COMPILE - 1), &MEDIUM_COMPILES)); assert!(std::ptr::eq(compile_slots(LARGE_DRIVER_COMPILE), &BIG_COMPILES)); + assert!(std::ptr::eq(compile_slots(729_672), &BIG_COMPILES)); assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE - 1), &BIG_COMPILES)); assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE), &GIANT_COMPILES)); + assert!(std::ptr::eq(compile_slots(1_061_720), &GIANT_COMPILES)); } #[test] @@ -6200,26 +6205,23 @@ unsafe fn go_background( 0 } }); + // Only pure image-writing compute shaders (zero buffer/global/GDS writes) or BVH RT traversal + // shaders may ever be spared/skipped while building. Heavy producer compute shaders that write + // memory are deprioritized onto gated workers (`deprioritized`) and excluded from speculative + // low-priority preloading, but NEVER skipped when bound. + let flags = super::pso_async::SubmitFlags { + spared: image_only || (heavy_compute && big_image_only), + bvh_traversal: bvh_trav && bvh_gate_enabled(), + deprioritized: heavy_compute || (bvh_trav && bvh_gate_enabled()), + }; if super::pso_async::lazy() { - super::pso_async::submit_lazy(*ppv as usize, compute, job, key); + super::pso_async::submit_lazy_with_flags(*ppv as usize, compute, job, key, flags); } else { - super::pso_async::submit(*ppv as usize, compute, job); + super::pso_async::submit_with_flags(*ppv as usize, compute, job, flags); } if driver != 0 { super::pso_async::shared(*ppv as usize, driver); } - // Only pure image-writing compute shaders (zero buffer/global/GDS writes) or BVH RT traversal - // shaders may ever be spared/skipped while building. Heavy producer compute shaders that write - // memory are deprioritized onto gated workers (`heavy_compute`) but NEVER skipped. - if image_only || (heavy_compute && big_image_only) { - super::pso_async::image_only(*ppv as usize); - } - if bvh_trav && bvh_gate_enabled() { - super::pso_async::bvh_traversal(*ppv as usize); - } - if heavy_compute { - super::pso_async::heavy_compute(*ppv as usize); - } Some(hr) } From b36de34bde1425af067b42bf8d317b919d46520f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:14:12 +0100 Subject: [PATCH 122/258] D3D12.X: gate RT companion compute shader 95cc13288a27a96e under XCL_RT_GATE Screen-probe ray-activation compute shader 95cc13288a27a96e (1,061,720 B DXIL, >144 s cold compile on AMD RDNA4) feeds RT traversal without directly issuing image_bvh*_intersect_ray, so uses_bvh_intersect() did not classify it as RT-gated. Running it ahead of RT traversal both stalls world entry and clears downstream lighting/shadow/reflection buffers. Classify RT_COMPANION_CS_HASHES (0x95cc13288a27a96e) alongside uses_bvh_intersect() in is_rt_gated_cs() so XCL_RT_GATE both spares its async build in GIANT_COMPILES (never blocking resolve_wait_for) and holds back dispatch until BVH builders succeed (XCL_RT_GATE=0 disables). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index cbe13c36dd..a9e04e2239 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1961,8 +1961,24 @@ fn note_compute_threads(pso: usize, cs: &[u8]) { } } +/// Compute shaders that feed RT ray-tracing passes without directly issuing +/// `image_bvh*_intersect_ray` (e.g. giant screen-probe ray-activation passes). Gating them +/// alongside BVH traversal under `XCL_RT_GATE` avoids >100 s compile freezes on world entry +/// and prevents them from clearing lighting/shadow/reflection buffers before RT traversal is ready. +const RT_COMPANION_CS_HASHES: &[u64] = &[ + 0x95cc_1328_8a27_a96e, +]; + +fn is_rt_gated_cs_hash(hash: u64) -> bool { + RT_COMPANION_CS_HASHES.contains(&hash) +} + +fn is_rt_gated_cs(cs: &[u8]) -> bool { + is_rt_gated_cs_hash(crate::gpu::shader::fnv64(cs)) || crate::gpu::effects::uses_bvh_intersect(cs) +} + fn note_bvh_traversal(pso: usize, cs: &[u8]) { - if pso != 0 && crate::gpu::effects::uses_bvh_intersect(cs) { + if pso != 0 && is_rt_gated_cs(cs) { BVH_TRAVERSAL_PSOS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } @@ -4609,6 +4625,8 @@ mod big_compile_tests { assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE - 1), &BIG_COMPILES)); assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE), &GIANT_COMPILES)); assert!(std::ptr::eq(compile_slots(1_061_720), &GIANT_COMPILES)); + assert!(is_rt_gated_cs_hash(0x95cc_1328_8a27_a96e)); + assert!(!is_rt_gated_cs_hash(0xef5e_ce92_2dc3_3bfe)); } #[test] @@ -6183,7 +6201,7 @@ unsafe fn go_background( // a big compute program that writes nothing but images: binds can go on without it let big_image_only = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); let image_only = big_image_only && super::pso_async::image_skip(); - let bvh_trav = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::uses_bvh_intersect(b))); + let bvh_trav = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| is_rt_gated_cs(b))); let heavy_compute = compute && super::pso_async::async_heavy_compute() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::compute_code_len(b).is_some_and(|n| n >= crate::gpu::effects::HEAVY_CODE))); From 7582db3a0a8be204f462fc9d3f631cae64ccc198 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:21:33 +0100 Subject: [PATCH 123/258] D3D12.X: serialize ID3D12PipelineLibrary1 calls and guard null descs MmapPipelineLibrary::store() previously held lib_rw.read(), allowing concurrent StorePipeline and LoadComputePipeline calls inside D3D12Core.dll which raced on internal lookup tables (0xc0000005 null deref at D3D12Core+0x7dfa when split/whole pipeline library traffic surged). Replace lib_rw with lib_lock (Mutex) serializing all Load*, StorePipeline, GetSerializedSize, and Serialize calls on ID3D12PipelineLibrary1, and guard null root signature / shader bytecode / stream / output pointers before entering D3D12. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/pso_library.rs | 43 +++++++++++++++--------- crates/xcl/src/hle/d3d12x/real.rs | 12 +++++++ 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_library.rs b/crates/xcl/src/hle/d3d12x/pso_library.rs index 84ecae4a8e..f7f5ae2a5a 100644 --- a/crates/xcl/src/hle/d3d12x/pso_library.rs +++ b/crates/xcl/src/hle/d3d12x/pso_library.rs @@ -11,7 +11,7 @@ use std::ffi::c_void; use std::os::windows::ffi::OsStrExt; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock, RwLock}; +use std::sync::{Mutex, OnceLock}; use windows::core::{Interface, HSTRING}; use windows::Win32::Graphics::Direct3D12::*; @@ -360,13 +360,14 @@ pub struct MmapPipelineLibrary { dirty: AtomicU64, saving: AtomicBool, save_lock: Mutex<()>, - /// Synchronizes concurrent `StorePipeline` (shared read lock) against `GetSerializedSize` + - /// `Serialize` (exclusive write lock) so serialization never races a concurrent size growth. - lib_rw: RwLock<()>, + /// Serializes all `ID3D12PipelineLibrary1` operations (`Load*`, `StorePipeline`, + /// `GetSerializedSize`, `Serialize`). `D3D12Core.dll` is not thread-safe for concurrent + /// `StorePipeline` + `Load*` (races on internal lookup tables -> 0xc0000005). + lib_lock: Mutex<()>, } -// `ID3D12PipelineLibrary1` methods are free-threaded per the D3D12 specification; `_backing` is -// read-only and `save_lock` serializes disk snapshots. +// `_backing` is read-only; `lib_lock` serializes all `ID3D12PipelineLibrary1` calls and +// `save_lock` serializes disk snapshots. unsafe impl Send for MmapPipelineLibrary {} unsafe impl Sync for MmapPipelineLibrary {} @@ -393,7 +394,7 @@ impl MmapPipelineLibrary { dirty: AtomicU64::new(0), saving: AtomicBool::new(false), save_lock: Mutex::new(()), - lib_rw: RwLock::new(()), + lib_lock: Mutex::new(()), }); } Err(e) => { @@ -439,31 +440,43 @@ impl MmapPipelineLibrary { dirty: AtomicU64::new(0), saving: AtomicBool::new(false), save_lock: Mutex::new(()), - lib_rw: RwLock::new(()), + lib_lock: Mutex::new(()), }) } pub unsafe fn load_compute(&self, key: &str, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> Option { + if key.is_empty() || desc.pRootSignature.is_none() || desc.CS.pShaderBytecode.is_null() || desc.CS.BytecodeLength == 0 { + return None; + } let name = HSTRING::from(key); - let _r = self.lib_rw.read().unwrap(); + let _g = self.lib_lock.lock().unwrap(); self.lib.LoadComputePipeline(&name, desc).ok() } pub unsafe fn load_graphics(&self, key: &str, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option { + if key.is_empty() || desc.pRootSignature.is_none() { + return None; + } let name = HSTRING::from(key); - let _r = self.lib_rw.read().unwrap(); + let _g = self.lib_lock.lock().unwrap(); self.lib.LoadGraphicsPipeline(&name, desc).ok() } pub unsafe fn load_stream(&self, key: &str, desc: &D3D12_PIPELINE_STATE_STREAM_DESC) -> Option { + if key.is_empty() || desc.pPipelineStateSubobjectStream.is_null() || desc.SizeInBytes == 0 { + return None; + } let name = HSTRING::from(key); - let _r = self.lib_rw.read().unwrap(); + let _g = self.lib_lock.lock().unwrap(); self.lib.LoadPipeline(&name, desc).ok() } pub unsafe fn store(&self, key: &str, pso: &ID3D12PipelineState) -> bool { + if key.is_empty() { + return false; + } let name = HSTRING::from(key); - let _r = self.lib_rw.read().unwrap(); + let _g = self.lib_lock.lock().unwrap(); if self.lib.StorePipeline(&name, pso).is_ok() { self.dirty.fetch_add(1, Ordering::Relaxed); true @@ -476,15 +489,15 @@ impl MmapPipelineLibrary { self.dirty.load(Ordering::Relaxed) } - /// Serialize under `save_lock` (already held by caller), taking `lib_rw.write()` so no - /// `StorePipeline` can grow the library between `GetSerializedSize` and `Serialize`. + /// Serialize under `save_lock` (already held by caller), taking `lib_lock` so no concurrent + /// `StorePipeline` or `Load*` can race `GetSerializedSize` + `Serialize`. unsafe fn save_locked(&self, min_dirty: u64) -> Option { let dirty_before = self.dirty.load(Ordering::Acquire); if dirty_before < min_dirty { return None; } let (size, saved) = { - let _w = self.lib_rw.write().unwrap(); + let _g = self.lib_lock.lock().unwrap(); let size = self.lib.GetSerializedSize(); let saved = if size > 0 { self.store.write_generation(size, |buf| self.lib.Serialize(buf).is_ok()) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index a9e04e2239..fcecb29a89 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -10228,6 +10228,9 @@ mod pso_lib { riid: *const GUID, ppv: *mut *mut c_void, ) -> bool { + if ppv.is_null() { + return false; + } let Some(lib) = library_for(device) else { return false }; let Some(pso) = lib.load_compute(key, desc) else { return false }; if deliver_adopted(pso, riid, ppv) { @@ -10244,6 +10247,9 @@ mod pso_lib { rs: *mut c_void, cs: &[u8], ) -> Option<*mut c_void> { + if rs.is_null() || cs.is_empty() { + return None; + } let lib = library_for(device)?; let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); @@ -10260,6 +10266,9 @@ mod pso_lib { riid: *const GUID, ppv: *mut *mut c_void, ) -> bool { + if ppv.is_null() { + return false; + } let Some(lib) = library_for(device) else { return false }; let Some(pso) = lib.load_graphics(key, desc) else { return false }; if deliver_adopted(pso, riid, ppv) { @@ -10277,6 +10286,9 @@ mod pso_lib { riid: *const GUID, ppv: *mut *mut c_void, ) -> bool { + if ppv.is_null() || stream_bytes.is_empty() { + return false; + } let Some(lib) = library_for(device) else { return false }; let sdesc = D3D12_PIPELINE_STATE_STREAM_DESC { SizeInBytes: stream_bytes.len(), From b71981dcd11f5e2d1fb65cf8a2790e09b62058d5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:32:54 +0100 Subject: [PATCH 124/258] D3D12.X: defer >=256 KiB graphics/MS PSOs, lower HEAVY_CODE to 16 KiB, add RT name gate and 24 ms frame wait cap Eliminate remaining cold PSO title-thread stalls on world entry while preserving non-RT producer correctness (100% cache-safe): - Lower HEAVY_CODE from 24 KiB to 16 KiB in gpu/effects.rs so 16-24 KiB compute shaders (~200-300 KiB DXIL) compile on gated xcl-pso-* workers instead of ungated on title threads, while still waiting for memory-writing producers. - Defer >= huge_pso_bytes() (256 KiB) graphics and two-pass mesh pipelines in translated_graphics_pso_once and translated_mesh_stream_once when dxc::defer() is active (matching translated_compute_pso_once). - Extend is_rt_gated_cs() to match RT companion compute shader names (RaytracingResolve, ScreenProbes_ActivateRays, IrradianceCache_Shade) in container metadata and optional XCL_RT_SKIP_HASHES hex list. - Add FrameWaitBudget (XCL_PSO_FRAME_WAIT_MS, default 24 ms, 0 to disable) for non-BVH spared compute PSOs so fast warm .plib loads finish on first bind while cold compiles never stall PresentX past 24 ms/frame. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/effects.rs | 17 +++-- crates/xcl/src/hle/d3d12x/pso_async.rs | 87 +++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 45 ++++++++++++- 3 files changed, 141 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index 750b391f1d..baf9cf7d62 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -109,10 +109,17 @@ pub fn big_and_image_only(blob: &[u8]) -> bool { code.len() >= BIG_CODE && of(&code).is_some_and(|e| !e.memory) } -/// Console RDNA2 code bytes (24 KiB, ~6 000 instructions, ~512+ KiB DXIL) from which a compute -/// shader is treated as heavyweight for async-only compilation so title threads never freeze -/// compiling multi-10s RT compute shaders synchronously. -pub const HEAVY_CODE: usize = 24 << 10; +/// Console RDNA2 code bytes (16 KiB, ~4 000 instructions, ~200+ KiB DXIL) from which a compute +/// shader is treated as heavyweight for worker-gated compilation so title threads never compile +/// large compute shaders ungated (and `xcl-pso-pre-*` never speculatively preloads them). +pub const HEAVY_CODE: usize = 16 << 10; + +/// Fast ASCII substring scan over a raw console shader container (`PRIV`/`ILDN`/metadata) to +/// recognize known RT companion shader families without touching any `build.rs`-hashed translator +/// sources. +pub fn container_contains_ascii_any(blob: &[u8], needles: &[&[u8]]) -> bool { + needles.iter().any(|needle| !needle.is_empty() && blob.windows(needle.len()).any(|w| w == *needle)) +} /// Length in bytes of the compute program's RDNA2 code (`None` if not a valid console CS). pub fn compute_code_len(blob: &[u8]) -> Option { @@ -178,6 +185,8 @@ mod tests { let rt_with_indirect = asm(&[indirect, bvh, END]); assert_eq!(of(&rt_with_indirect), None); assert!(code_uses_bvh_intersect(&rt_with_indirect)); + assert!(container_contains_ascii_any(b"\0\x01CS_ScreenProbes_ActivateRays\0", &[b"RaytracingResolve", b"ScreenProbes_ActivateRays"])); + assert!(!container_contains_ascii_any(b"\0\x01CS_DepthPyramid\0", &[b"RaytracingResolve", b"ScreenProbes_ActivateRays"])); let image_atomic: (&str, &str, &[(&str, u64)]) = ("IMAGE_ATOMIC_ADD", "ENC_MIMG", &[("DMASK", 1), ("VADDR", 0), ("VDATA", 4), ("SRSRC", 2)]); assert_eq!(of(&asm(&[image_atomic, END])).map(|e| (e.memory, e.images)), Some((false, true))); // every way into memory another pass or an indirect call reads diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 3b77e92091..4d6b738bb4 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1401,15 +1401,81 @@ pub fn bvh_traversal(standin: usize) { } } +/// Per-frame wait cap for non-critical spared compute PSOs (`XCL_PSO_FRAME_WAIT_MS`, default 24 ms, +/// `0` = never wait). Lets fast warm `.plib` hits finish on their first bind without stalling +/// `PresentX` past 24 ms/frame on cold compiles; never applies to memory-writing producer shaders. +fn frame_wait_budget() -> Option { + static B: OnceLock> = OnceLock::new(); + *B.get_or_init(|| { + let ms = std::env::var("XCL_PSO_FRAME_WAIT_MS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(24); + (ms > 0).then(|| std::time::Duration::from_millis(ms)) + }) +} + +struct FrameWaitBudget { + frame: u64, + spent: std::time::Duration, +} + +impl FrameWaitBudget { + const fn new() -> Self { + Self { frame: 0, spent: std::time::Duration::ZERO } + } + + fn remaining(&mut self, frame: u64, cap: std::time::Duration) -> std::time::Duration { + if frame > self.frame { + self.frame = frame; + self.spent = std::time::Duration::ZERO; + } + cap.saturating_sub(self.spent) + } + + fn record(&mut self, frame: u64, elapsed: std::time::Duration) { + if frame > self.frame { + self.frame = frame; + self.spent = elapsed; + } else if frame == self.frame { + self.spent = self.spent.saturating_add(elapsed); + } + } +} + +static FRAME_WAIT: Mutex = Mutex::new(FrameWaitBudget::new()); + /// `resolve_wait` for a pipeline binds do not wait for (`image_only` or `bvh_traversal`): the real -/// one once built, else the stand-in, with the build sent to the workers. Nobody waits, so the -/// build is not `wanted`: a big one takes its turn among the driver's compiles and waits for free commit. +/// one once built, else the stand-in, with the build sent to the workers. For non-BVH `spared` +/// pipelines (e.g. pure image-only shaders), waits up to the remaining per-frame `frame_wait_budget` +/// (`XCL_PSO_FRAME_WAIT_MS`, default 24 ms) so fast warm `.plib` loads complete on first bind +/// without ever freezing `PresentX`. Nobody marks the build `wanted`, so cold big compiles stay +/// strictly behind critical work and commit headroom. fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.real.load(Ordering::Acquire) { 0 => { if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p.clone()); } + if !p.bvh_traversal.load(Ordering::Acquire) && !p.late.load(Ordering::Acquire) { + if let Some(cap) = frame_wait_budget() { + let frame = super::present::presents(); + let rem = FRAME_WAIT.lock().unwrap().remaining(frame, cap); + if !rem.is_zero() { + let t0 = std::time::Instant::now(); + let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), rem, |d| !*d).unwrap(); + let finished = *done; + drop(done); + FRAME_WAIT.lock().unwrap().record(frame, t0.elapsed()); + if finished { + return match p.real.load(Ordering::Acquire) { + 0 => p.stand(pso), + r => r, + }; + } + } + } + } if !*p.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); @@ -1597,4 +1663,21 @@ mod pso_queue_tests { assert!(ran.load(Ordering::Acquire)); let _ = released(heavy_standin); } + + #[test] + fn frame_wait_budget_caps_per_frame_and_resets_on_new_frame() { + let cap = std::time::Duration::from_millis(24); + let mut b = FrameWaitBudget::new(); + assert_eq!(b.remaining(1, cap), cap); + b.record(1, std::time::Duration::from_millis(10)); + assert_eq!(b.remaining(1, cap), std::time::Duration::from_millis(14)); + b.record(1, std::time::Duration::from_millis(20)); + assert_eq!(b.remaining(1, cap), std::time::Duration::ZERO); + // Advancing to frame 2 resets the budget cleanly. + assert_eq!(b.remaining(2, cap), cap); + // Stale lower frame number must not clear frame 2's spent budget. + b.record(2, std::time::Duration::from_millis(12)); + b.record(1, std::time::Duration::from_millis(5)); + assert_eq!(b.remaining(2, cap), std::time::Duration::from_millis(12)); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index fcecb29a89..43f3767207 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1969,12 +1969,36 @@ const RT_COMPANION_CS_HASHES: &[u64] = &[ 0x95cc_1328_8a27_a96e, ]; +/// Generic RT companion compute shader name fragments matched in container metadata (`PRIV`/`ILDN`). +const RT_COMPANION_CS_NAMES: &[&[u8]] = &[ + b"RaytracingResolve", + b"ScreenProbes_ActivateRays", + b"IrradianceCache_Shade", +]; + +fn parse_rt_skip_hashes(raw: &str) -> HashSet { + raw.split(|c: char| c == ',' || c == ';' || c.is_ascii_whitespace()) + .filter_map(|tok| { + let t = tok.trim().trim_start_matches("0x").trim_start_matches("0X"); + (!t.is_empty()).then(|| u64::from_str_radix(t, 16).ok()).flatten() + }) + .collect() +} + +/// Optional extra 64-bit shader hashes to gate under `XCL_RT_GATE` (`XCL_RT_SKIP_HASHES=hex1,hex2`). +fn extra_rt_skip_hashes() -> &'static HashSet { + static SET: OnceLock> = OnceLock::new(); + SET.get_or_init(|| std::env::var("XCL_RT_SKIP_HASHES").map_or_else(|_| HashSet::new(), |v| parse_rt_skip_hashes(&v))) +} + fn is_rt_gated_cs_hash(hash: u64) -> bool { - RT_COMPANION_CS_HASHES.contains(&hash) + RT_COMPANION_CS_HASHES.contains(&hash) || extra_rt_skip_hashes().contains(&hash) } fn is_rt_gated_cs(cs: &[u8]) -> bool { - is_rt_gated_cs_hash(crate::gpu::shader::fnv64(cs)) || crate::gpu::effects::uses_bvh_intersect(cs) + is_rt_gated_cs_hash(crate::gpu::shader::fnv64(cs)) + || crate::gpu::effects::container_contains_ascii_any(cs, RT_COMPANION_CS_NAMES) + || crate::gpu::effects::uses_bvh_intersect(cs) } fn note_bvh_traversal(pso: usize, cs: &[u8]) { @@ -4627,6 +4651,12 @@ mod big_compile_tests { assert!(std::ptr::eq(compile_slots(1_061_720), &GIANT_COMPILES)); assert!(is_rt_gated_cs_hash(0x95cc_1328_8a27_a96e)); assert!(!is_rt_gated_cs_hash(0xef5e_ce92_2dc3_3bfe)); + let parsed = parse_rt_skip_hashes("0x39f0e9aeb156a61c, 73fb752d7f62c3a5; bad"); + assert!(parsed.contains(&0x39f0_e9ae_b156_a61c)); + assert!(parsed.contains(&0x73fb_752d_7f62_c3a5)); + assert_eq!(parsed.len(), 2); + assert!(is_rt_gated_cs(b"HDR\0CS_RaytracingResolve_01\0")); + assert!(is_rt_gated_cs(b"HDR\0CS_IrradianceCache_Shade_Low\0")); } #[test] @@ -5763,6 +5793,13 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const Some(p) => Some(p.to_vec()), None => None, }; + // Large translated graphics pipelines (>= huge_pso_bytes) defer off the title thread when + // `dxc::defer()` is active, matching `translated_compute_pso_once` so cold >= 256 KiB graphics + // PSOs never stall title threads even when `XCL_LAZY_PSO=0`. + let big = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) >= huge_pso_bytes(); + if big && crate::gpu::recomp::dxc::defer() { + return None; + } let rs = abi_rs_for(this, &samplers)?; let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); @@ -6904,6 +6941,10 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri return Some(E_INVALIDARG); } }; + let big = tp.ms.len() + tp.cs.len() + ps.as_ref().map_or(0, Vec::len) >= huge_pso_bytes(); + if big && crate::gpu::recomp::dxc::defer() { + return None; + } let Some(rs) = abi_rs_for(this, &ps_samplers) else { return Some(E_INVALIDARG) }; // the title's state (blend, rasteriser, depth, formats …) with XCL's RS and shaders let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref()); From 8d3c69c52fd0bf8d6017e272ff7319cdc0962a5a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:32:59 +0100 Subject: [PATCH 125/258] D3D12.X: fence-quarantine released shared descriptor ranges release_global and release_global_sampler previously returned freed ranges straight to GLOBAL.free / GLOBAL_SAMPLER.free, where first-fit take_range immediately handed those shader-visible indices to a new heap and CopyDescriptorsSimple overwrote slots still read by in-flight GPU command lists (causing long-run MMU faults on AMD RDNA4). Quarantine released shared descriptor ranges behind per-queue completion fences across all live device queues (signaled outside GLOBAL/GLOBAL_SAMPLER/HEAPS locks) and drain completed batches into free before reserving or releasing. Keeps zero-queue unit tests immediate and holds ranges safely on fence-signal errors. Tested: cargo check -p xcl --lib (0 errors, 0 new warnings); added retired_descriptor_ranges_stay_quarantined_until_all_queues_complete. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/console_heap.rs | 140 ++++++++++++++++++++-- 1 file changed, 132 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 879b90fb71..902ff97fc6 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -25,6 +25,7 @@ //! Without the shared heap (it could not be made) a heap keeps its own PC heap: SRV at 2k, //! UAV at 2k + 1. +use std::collections::{HashMap, VecDeque}; use std::sync::Mutex; use windows::core::Interface; @@ -74,6 +75,76 @@ impl Heap { static HEAPS: Mutex> = Mutex::new(Vec::new()); +/// Released descriptor range in `GLOBAL` or `GLOBAL_SAMPLER` awaiting active GPU queues before +/// being returned to `free` (prevents overwriting shader-visible descriptors still read in flight). +struct RetiredRange { + first: u32, + count: u32, + /// Fence marks across all live queues on the device (`None` = signal failed, keep held). + marks: Option>, +} + +fn drain_retired_ranges( + retired: &mut VecDeque>, + free: &mut Vec<(u32, u32)>, + mut completed: impl FnMut(&F) -> u64, +) { + while retired + .front() + .is_some_and(|r| r.marks.as_ref().is_some_and(|m| m.iter().all(|(f, v)| completed(f) >= *v))) + { + if let Some(r) = retired.pop_front() { + merge_release(free, r.first, r.count); + } + } +} + +struct QueueFences(HashMap); + +// D3D12 fences are free-threaded; accessed only under HEAP_FENCES lock. +unsafe impl Send for QueueFences {} + +static HEAP_FENCES: Mutex> = Mutex::new(None); + +/// Signal every known live title queue belonging to `dev` (called outside `GLOBAL`/`GLOBAL_SAMPLER` +/// and `HEAPS`). Returns `Some(vec![])` when no live queues exist for `dev`, or `None` if fence +/// creation or signaling fails so released descriptor ranges stay safely quarantined. +unsafe fn signal_live_queues_for(dev: &ID3D12Device) -> Option> { + let dev_raw = dev.as_raw(); + let mut queues: Vec<(usize, ID3D12CommandQueue)> = Vec::new(); + for raw in super::present::known_queues() { + let ptr = raw as *mut std::ffi::c_void; + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&ptr) { + let mut qdev: Option = None; + if q.GetDevice(&mut qdev).is_ok() && qdev.as_ref().is_some_and(|d| d.as_raw() == dev_raw) { + queues.push((raw, q.clone())); + } + } + } + if queues.is_empty() { + return Some(Vec::new()); + } + let mut guard = HEAP_FENCES.lock().unwrap(); + let map = &mut guard.get_or_insert_with(|| QueueFences(HashMap::new())).0; + let mut marks = Vec::with_capacity(queues.len()); + for (key, q) in queues { + let (fence, val) = match map.entry(key) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => { + let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + e.insert((f, 0)) + } + }; + let next = *val + 1; + if q.Signal(&*fence, next).is_err() { + return None; + } + *val = next; + marks.push((fence.clone(), next)); + } + Some(marks) +} + /// The shader-visible PC heap of all console view heaps. struct Global { dev: ID3D12Device, @@ -83,8 +154,10 @@ struct Global { inc: u32, cap: u32, next: u32, - /// released ranges (first, count) + /// released ranges (first, count) proven GPU-idle free: Vec<(u32, u32)>, + /// released ranges awaiting live GPU queue completion before entering `free` + retired: VecDeque>, } // D3D12 descriptor heaps and devices are free-threaded @@ -189,6 +262,7 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { // come first next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), + retired: VecDeque::new(), }); } true @@ -282,6 +356,7 @@ unsafe fn set_window_views_checked(dev: &ID3D12Device, windows: &[(usize, usize) fn reserve_global(count: u32) -> Option { let mut g = GLOBAL.lock().unwrap(); let s = g.as_mut()?; + unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; let (cap, mut next) = (s.cap, s.next); let r = take_range(&mut s.free, &mut next, cap, count); s.next = next; @@ -307,13 +382,22 @@ fn page_of(h: &mut Heap, k: u32) -> Option<(u32, u32)> { Some((first, p as u32 * PAGE_SLOTS)) } -/// The shared range starting at `first` (`count` descriptors) is free again. +/// The shared range starting at `first` (`count` descriptors) is quarantined behind active GPU +/// queues before returning to `free`, preventing overwrites of live shader-visible descriptors. pub fn release_global(first: u32, count: u32) { if count == 0 { return; } + let dev = GLOBAL.lock().unwrap().as_ref().map(|s| s.dev.clone()); + let Some(dev) = dev else { return }; + let marks = unsafe { signal_live_queues_for(&dev) }; if let Some(s) = GLOBAL.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + if marks.as_ref().is_some_and(Vec::is_empty) { + merge_release(&mut s.free, first, count); + } else { + s.retired.push_back(RetiredRange { first, count, marks }); + } + unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; } } @@ -700,6 +784,7 @@ struct GlobalSampler { cap: u32, next: u32, free: Vec<(u32, u32)>, + retired: VecDeque>, } unsafe impl Send for GlobalSampler {} @@ -763,6 +848,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { // Reserve slot 0 as the immutable point-wrap zero sampler for empty/zeroed S# entries. next: 1, free: Vec::new(), + retired: VecDeque::new(), }); } true @@ -771,6 +857,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { fn reserve_global_sampler(count: u32) -> Option { let mut g = GLOBAL_SAMPLER.lock().unwrap(); let s = g.as_mut()?; + unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; let (cap, mut next) = (s.cap, s.next); let r = take_range(&mut s.free, &mut next, cap, count); s.next = next; @@ -797,8 +884,16 @@ fn release_global_sampler(first: u32, count: u32) { if count == 0 { return; } + let dev = GLOBAL_SAMPLER.lock().unwrap().as_ref().map(|s| s.dev.clone()); + let Some(dev) = dev else { return }; + let marks = unsafe { signal_live_queues_for(&dev) }; if let Some(s) = GLOBAL_SAMPLER.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + if marks.as_ref().is_some_and(Vec::is_empty) { + merge_release(&mut s.free, first, count); + } else { + s.retired.push_back(RetiredRange { first, count, marks }); + } + unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; } } @@ -907,7 +1002,7 @@ mod tests { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, - next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), + next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), retired: VecDeque::new(), }); let window = (&mut resource as *mut _ as usize, 0x10000); assert!(set_window_views_checked(&dev, &[window], true)); @@ -1102,7 +1197,7 @@ mod tests { *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), - cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), + cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), }); assert_eq!(reserve_global_sampler(4), Some(1)); assert_eq!(reserve_global_sampler(4), Some(5)); @@ -1161,12 +1256,12 @@ mod tests { *GLOBAL.lock().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), - cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), + cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), retired: VecDeque::new(), }); *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), - cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), + cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), }); if crate::gpu::uma::get().is_some() { assert!(register(0xC100, 16, 0x9000, 0, 16, true, true, true)); @@ -1227,4 +1322,33 @@ mod tests { assert_eq!(view_unmapped_index(false, 0), 0); assert_eq!(view_unmapped_index(false, 42), 84); } + + #[test] + fn retired_descriptor_ranges_stay_quarantined_until_all_queues_complete() { + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let f1 = Arc::new(AtomicU64::new(0)); + let f2 = Arc::new(AtomicU64::new(0)); + let mut retired: VecDeque>> = VecDeque::new(); + let mut free: Vec<(u32, u32)> = Vec::new(); + retired.push_back(RetiredRange { first: 64, count: 16, marks: Some(vec![(f1.clone(), 1), (f2.clone(), 1)]) }); + retired.push_back(RetiredRange { first: 80, count: 16, marks: Some(vec![(f1.clone(), 2), (f2.clone(), 1)]) }); + retired.push_back(RetiredRange { first: 96, count: 16, marks: None }); + + // While f2 is still pending, neither range may re-enter `free`. + f1.store(1, Ordering::SeqCst); + drain_retired_ranges(&mut retired, &mut free, |f| f.load(Ordering::SeqCst)); + assert!(free.is_empty() && retired.len() == 3); + + // Once both queues pass mark 1, only range 1 returns; range 2 waits for f1 == 2. + f2.store(1, Ordering::SeqCst); + drain_retired_ranges(&mut retired, &mut free, |f| f.load(Ordering::SeqCst)); + assert_eq!(free, vec![(64, 16)]); + assert_eq!(retired.len(), 2); + + // Passing mark 2 coalesces [80, 96) with [64, 80); failed-signal range stays quarantined. + f1.store(2, Ordering::SeqCst); + drain_retired_ranges(&mut retired, &mut free, |f| f.load(Ordering::SeqCst)); + assert_eq!(free, vec![(64, 32)]); + assert_eq!(retired.len(), 1); + } } From f3c05d0d9fd54cf54b582f6f565f9177c90809bd Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:32:59 +0100 Subject: [PATCH 126/258] D3D12.X: add commit-reserve floor and early unwatched texture recheck Windows charges ~1.03 GiB of virtual commit per GiB of GPU resources. Add a configurable commit-reserve floor (XCL_COMMIT_RESERVE_MB, default 4096 MiB, 0 disables) via GlobalMemoryStatusEx (ullAvailPageFile): below the floor, vram skips parking idle reserved textures in ReservedPool, reclaims even warm spare 64 MiB VRAM pools on a 250 ms cadence, and title_textures caps upload batches at 8 MiB to prevent persistent staging buffer growth. Also add early frame milestone 1 to STREAM_RECHECK_MILESTONES ([1, 4, 12, 40, 120, 400]) so late streaming writes into unwatched physical-page textures are caught before one-time decoration/face bake draws run. Tested: cargo check -p xcl --lib (0 errors, 0 new warnings); added commit_below_floor_enforces_reserve_and_zero_disables and updated unwatched milestone & low-commit batch cap assertions. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 46 +++++++++++------ crates/xcl/src/hle/d3d12x/vram.rs | 55 +++++++++++++++++++-- 2 files changed, 80 insertions(+), 21 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 4017b90c91..326568ba6f 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1146,7 +1146,8 @@ fn content_hash(b: &[u8]) -> u64 { /// Frame milestones (relative to last upload or detected content change) at which unwatched /// textures (e.g. physical-page / `MEM_MAPPED` views that `GetWriteWatch` cannot track) are /// re-fingerprinted to catch late streaming writes that land after an initial zeroed upload. -const STREAM_RECHECK_MILESTONES: [u64; 5] = [4, 12, 40, 120, 400]; +/// Milestone `1` catches late writes before one-time decoration/face bakes run. +const STREAM_RECHECK_MILESTONES: [u64; 6] = [1, 4, 12, 40, 120, 400]; /// Per-slice sample size (start, mid, end -> at most 48 KiB hashed per due texture). const STREAM_SAMPLE_SLICE: usize = 16 * 1024; @@ -1350,19 +1351,29 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) /// and keeps each GPU copy list short enough to avoid WDDM 2 s TDR when thousands of small /// textures stream at once. const BATCH_BYTES: usize = 32 << 20; +/// Tighter batch cap under low Windows commit headroom (`vram::commit_low`) so persistent texture +/// upload staging buffers stay small instead of growing to 64–144 MiB. +const BATCH_BYTES_LOW_COMMIT: usize = 8 << 20; const BATCH_ITEMS: usize = 256; /// Whether another upload `(next_dev, next_bytes)` still fits in the current batch of -/// `picked_count` textures totalling `picked_bytes` on `batch_dev`. An empty batch always takes -/// its first upload (even if larger than `BATCH_BYTES`) so progress is guaranteed. -fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_dev: usize, next_bytes: usize) -> bool { +/// `picked_count` textures totalling `picked_bytes` on `batch_dev` under byte cap `max_bytes`. +/// An empty batch always takes its first upload (even if larger than `max_bytes`) so progress is +/// guaranteed. +fn batch_fits_limit(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_dev: usize, next_bytes: usize, max_bytes: usize) -> bool { picked_count == 0 || (picked_count < BATCH_ITEMS && next_dev == batch_dev - && picked_bytes.saturating_add(next_bytes) <= BATCH_BYTES) + && picked_bytes.saturating_add(next_bytes) <= max_bytes) +} + +#[cfg(test)] +fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_dev: usize, next_bytes: usize) -> bool { + batch_fits_limit(picked_count, picked_bytes, batch_dev, next_dev, next_bytes, BATCH_BYTES) } -/// The uploads `todo`, in batches of up to `BATCH_BYTES` and `BATCH_ITEMS` (one list and one wait each). +/// The uploads `todo`, in batches of up to `BATCH_BYTES` (or `BATCH_BYTES_LOW_COMMIT` when Windows +/// commit is below reserve) and `BATCH_ITEMS` (one list and one wait each). unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { static N: AtomicU64 = AtomicU64::new(0); let warn = |e: &str| { @@ -1376,8 +1387,9 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { let mut bytes = 0usize; let mut device = 0usize; let skip_unchanged = unchanged_skip(); + let max_batch_bytes = if super::vram::commit_low() { BATCH_BYTES_LOW_COMMIT } else { BATCH_BYTES }; while let Some((_, u)) = todo.peek() { - if !batch_fits(picked.len(), bytes, device, u.device, u.tex.size() as usize) { + if !batch_fits_limit(picked.len(), bytes, device, u.device, u.tex.size() as usize, max_batch_bytes) { break; } let (r, u) = todo.next().unwrap(); @@ -2994,14 +3006,14 @@ mod tests { g.insert(gpu_res_id, StreamRecheck { base_frame: 100, stage: 0, last_fp: fp0 }); } - // Before first milestone (+4 frames -> frame 104), nothing is checked or re-queued. + // Before first milestone (+1 frame -> frame 101), nothing is checked or re-queued. backing[size - 16] = 0xAB; - unsafe { recheck_streamed_unwatched_at(&[], 103) }; + unsafe { recheck_streamed_unwatched_at(&[], 100) }; assert!(!TEXTURES.lock().unwrap().by_res.get(&res_id).unwrap().pending); - // At milestone 0 (frame 104), late write is detected: pending becomes true, schedule resets - // to base_frame=104, stage=0, and the gpu_written entry is pruned without re-queuing. - unsafe { recheck_streamed_unwatched_at(&[], 104) }; + // At milestone 0 (frame 101), late write is detected: pending becomes true, schedule resets + // to base_frame=101, stage=0, and the gpu_written entry is pruned without re-queuing. + unsafe { recheck_streamed_unwatched_at(&[], 101) }; { let mut t = TEXTURES.lock().unwrap(); let e = t.by_res.get_mut(&res_id).unwrap(); @@ -3014,17 +3026,19 @@ mod tests { let g = STREAM_RECHECK.lock().unwrap(); assert!(!g.contains_key(&gpu_res_id), "gpu_written texture must be pruned from STREAM_RECHECK"); let st = g.get(&res_id).copied().expect("schedule reset after change"); - assert_eq!((st.base_frame, st.stage), (104, 0)); + assert_eq!((st.base_frame, st.stage), (101, 0)); assert_ne!(st.last_fp, fp0); } - // Advance through all 5 milestones with no further writes: entry must not re-queue and must - // clean itself up after milestone 4 (+400 frames -> frame 504). - for f in [108, 116, 144, 224, 504] { + // Advance through all 6 milestones with no further writes: entry must not re-queue and must + // clean itself up after milestone 5 (+400 frames -> frame 501). + for f in [102, 105, 113, 141, 221, 501] { unsafe { recheck_streamed_unwatched_at(&[], f) }; assert!(!TEXTURES.lock().unwrap().by_res.get(&res_id).unwrap().pending, "unchanged texture must not re-queue at frame {f}"); } assert!(!STREAM_RECHECK.lock().unwrap().contains_key(&res_id), "entry must retire after final 400-frame milestone"); + assert!(batch_fits_limit(0, 0, 1, 1, BATCH_BYTES, BATCH_BYTES_LOW_COMMIT), "empty batch always makes progress"); + assert!(!batch_fits_limit(1, BATCH_BYTES_LOW_COMMIT, 1, 1, 1, BATCH_BYTES_LOW_COMMIT), "low-commit cap bounds batch size"); forget(res_id); forget(gpu_res_id); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index d2f6fd3402..a85889d66e 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -279,7 +279,7 @@ pub(super) unsafe fn recycle_ready(resource: usize) -> bool { let Some(info) = PARKING.lock().unwrap().as_mut().and_then(|m| m.remove(&resource)) else { return false; }; - if !reserved_pool_enabled() { + if !reserved_pool_enabled() || commit_low() { return false; } let evicted = { @@ -853,6 +853,38 @@ fn keep_spare_pools() -> usize { }) } +/// Default Windows virtual commit reserve floor (4 GiB) below which optional VRAM pool spares, +/// reserved-texture reuse caching, and large upload staging batches shed commit headroom. +const DEFAULT_COMMIT_RESERVE_MIB: u64 = 4096; + +/// `XCL_COMMIT_RESERVE_MB` (default `4096`, `0` disables): free Windows commit floor in bytes. +fn commit_reserve_bytes() -> u64 { + static FLOOR: std::sync::OnceLock = std::sync::OnceLock::new(); + *FLOOR.get_or_init(|| { + let mib = std::env::var("XCL_COMMIT_RESERVE_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(DEFAULT_COMMIT_RESERVE_MIB); + mib.saturating_mul(1024 * 1024) + }) +} + +fn avail_commit_bytes() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPageFile) +} + +fn commit_below_floor(avail_bytes: Option, floor_bytes: u64) -> bool { + floor_bytes > 0 && avail_bytes.is_some_and(|avail| avail < floor_bytes) +} + +/// True when Windows available virtual commit (`ullAvailPageFile`) is below the reserve floor. +pub(super) fn commit_low() -> bool { + commit_below_floor(avail_commit_bytes(), commit_reserve_bytes()) +} + /// Deferred `UpdateTileMappings(NULL)` operation awaiting completion of all in-flight device queues. enum PendingUnmapOp { /// Whole-resource unmap from `unmap_superseded` (skipped if `Target::mapping_gen` advanced). @@ -1022,10 +1054,11 @@ impl Pages { /// Sweep expired idle pages, drain cooled tiles, and reclaim any completely empty 64 MiB /// pool heaps (above the warm spare count), returning their `ID3D12Heap`s to be dropped /// outside `PAGES.lock()`. - fn sweep_and_reclaim(&mut self, now: std::time::Instant) -> Vec { + fn sweep_and_reclaim(&mut self, now: std::time::Instant, low_commit: bool) -> Vec { self.sweep(now); self.pool.drain_cooling_before(now, self.cool_bound()); - let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare_pools(), POOL_PAGES); + let keep_spare = if low_commit { 0 } else { keep_spare_pools() }; + let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare, POOL_PAGES); let mut dropped = Vec::with_capacity(reclaimed_ids.len()); for idx in reclaimed_ids { if let Some(h) = self.pools.take_heap(idx) { @@ -2118,10 +2151,12 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { super::list_x::note_internal_wait(key, "texture page mappings", &pages.fence, pages.value); pages.waited.insert(key, pages.value); } - if now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { + let low_commit = commit_low(); + let reclaim_interval = if low_commit { std::time::Duration::from_millis(250) } else { std::time::Duration::from_secs(1) }; + if now.duration_since(pages.last_reclaim) >= reclaim_interval { pages.last_reclaim = now; do_reclaim = true; - newly_reclaimed = pages.sweep_and_reclaim(now); + newly_reclaimed = pages.sweep_and_reclaim(now, low_commit); if !newly_reclaimed.is_empty() { pages.flush_signal(); unmap_mark = Some((pages.fence.clone(), pages.value)); @@ -3318,4 +3353,14 @@ mod tests { pool.drain_cooling_before(t_stall, Some(t0 + Duration::from_millis(2500))); assert_eq!(pool.free_total, 2); } + + #[test] + fn commit_below_floor_enforces_reserve_and_zero_disables() { + const FLOOR: u64 = 4 * 1024 * 1024 * 1024; + assert!(commit_below_floor(Some(FLOOR - 1), FLOOR)); + assert!(!commit_below_floor(Some(FLOOR), FLOOR)); + assert!(!commit_below_floor(Some(FLOOR + 1), FLOOR)); + assert!(!commit_below_floor(None, FLOOR)); + assert!(!commit_below_floor(Some(0), 0)); + } } From 80032a6d09ecabed6e3ed5e127faf64533136b54 Mon Sep 17 00:00:00 2001 From: ChAlanA <88502758+ChalanaGimhanaX@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:36:09 +0530 Subject: [PATCH 127/258] D3D12.X: fix null UAV fallback and MSAA/typeless companion SRVs --- crates/xcl/src/hle/d3d12x/real.rs | 317 +++++++++++++++++++++++++++++- 1 file changed, 307 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 43f3767207..0a291d9122 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2382,12 +2382,7 @@ unsafe extern "system" fn dev_create_uav_checked_x( rd.Format.0 ); } - let null_dim = desc.as_ref().map_or_else(|| default_uav_dimension(&rd), |d| d.ViewDimension); - let null_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT, - ViewDimension: null_dim, - ..Default::default() - }; + let null_desc = null_uav_desc(desc.as_ref(), Some(&rd)); return dev_create_uav_x(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_desc, cpu); } if let Some(ref c) = patched { @@ -2685,6 +2680,7 @@ fn null_uav_desc( use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_FLOAT; let dim = desc .map(|v| v.ViewDimension.0) + .filter(|&d| d != 0) .or_else(|| rd.map(resource_dim_to_view)) .unwrap_or(D3D12_UAV_DIMENSION_TEXTURE2D.0); match dim { @@ -2700,7 +2696,7 @@ fn null_uav_desc( Texture1DArray: D3D12_TEX1D_ARRAY_UAV { MipSlice: 0, FirstArraySlice: 0, ArraySize: 1 }, }, }, - 5 => D3D12_UNORDERED_ACCESS_VIEW_DESC { + 5 | 7 => D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_FLOAT, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { @@ -2722,6 +2718,37 @@ fn null_uav_desc( } } +/// Map a typeless or depth DXGI format to a concrete same-family SRV format so +/// `CreateShaderResourceView` never receives a `*_TYPELESS` or depth-only format. +fn concrete_srv_format(fmt: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT { + use windows::Win32::Graphics::Dxgi::Common::*; + match fmt { + DXGI_FORMAT_R32G32B32A32_TYPELESS => DXGI_FORMAT_R32G32B32A32_FLOAT, + DXGI_FORMAT_R32G32B32_TYPELESS => DXGI_FORMAT_R32G32B32_FLOAT, + DXGI_FORMAT_R16G16B16A16_TYPELESS => DXGI_FORMAT_R16G16B16A16_FLOAT, + DXGI_FORMAT_R32G32_TYPELESS => DXGI_FORMAT_R32G32_FLOAT, + DXGI_FORMAT_R32G8X24_TYPELESS | DXGI_FORMAT_D32_FLOAT_S8X24_UINT => DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS, + DXGI_FORMAT_R10G10B10A2_TYPELESS => DXGI_FORMAT_R10G10B10A2_UNORM, + DXGI_FORMAT_R8G8B8A8_TYPELESS => DXGI_FORMAT_R8G8B8A8_UNORM, + DXGI_FORMAT_R16G16_TYPELESS => DXGI_FORMAT_R16G16_FLOAT, + DXGI_FORMAT_R32_TYPELESS | DXGI_FORMAT_D32_FLOAT => DXGI_FORMAT_R32_FLOAT, + DXGI_FORMAT_R24G8_TYPELESS | DXGI_FORMAT_D24_UNORM_S8_UINT => DXGI_FORMAT_R24_UNORM_X8_TYPELESS, + DXGI_FORMAT_R8G8_TYPELESS => DXGI_FORMAT_R8G8_UNORM, + DXGI_FORMAT_R16_TYPELESS | DXGI_FORMAT_D16_UNORM => DXGI_FORMAT_R16_UNORM, + DXGI_FORMAT_R8_TYPELESS => DXGI_FORMAT_R8_UNORM, + DXGI_FORMAT_BC1_TYPELESS => DXGI_FORMAT_BC1_UNORM, + DXGI_FORMAT_BC2_TYPELESS => DXGI_FORMAT_BC2_UNORM, + DXGI_FORMAT_BC3_TYPELESS => DXGI_FORMAT_BC3_UNORM, + DXGI_FORMAT_BC4_TYPELESS => DXGI_FORMAT_BC4_UNORM, + DXGI_FORMAT_BC5_TYPELESS => DXGI_FORMAT_BC5_UNORM, + DXGI_FORMAT_B8G8R8A8_TYPELESS => DXGI_FORMAT_B8G8R8A8_UNORM, + DXGI_FORMAT_B8G8R8X8_TYPELESS => DXGI_FORMAT_B8G8R8X8_UNORM, + DXGI_FORMAT_BC6H_TYPELESS => DXGI_FORMAT_BC6H_UF16, + DXGI_FORMAT_BC7_TYPELESS => DXGI_FORMAT_BC7_UNORM, + f => f, + } +} + /// Companion SRV for an image UAV slot so translated shaders can read from the UAV's T# /// (`ResourceDescriptorHeap[slot.index]`). Returns `None` for buffer or unsupported dimensions. /// When `null_resource` is true (either `pResource == NULL` or `DENY_SHADER_RESOURCE`), @@ -2761,7 +2788,7 @@ fn uav_companion_srv( None => { let r = rd?; let dim = resource_dim_to_view(r); - if !matches!(dim, 2 | 3 | 4 | 5 | 8) { + if !matches!(dim, 2 | 3 | 4 | 5 | 6 | 7 | 8) { return None; } (dim, r.Format, 0, 0, r.DepthOrArraySize as u32, 0) @@ -2788,6 +2815,7 @@ fn uav_companion_srv( (mip, first_slice, array, plane) }; + let msaa = !null_resource && rd.is_some_and(|r| r.SampleDesc.Count > 1); let mut srv = match dim { 2 => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: fmt, @@ -2811,7 +2839,7 @@ fn uav_companion_srv( }, }, }, - 4 => D3D12_SHADER_RESOURCE_VIEW_DESC { + 4 if !msaa => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: fmt, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, @@ -2819,7 +2847,13 @@ fn uav_companion_srv( Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: mip, MipLevels: 1, PlaneSlice: plane, ResourceMinLODClamp: 0.0 }, }, }, - 5 => D3D12_SHADER_RESOURCE_VIEW_DESC { + 4 | 6 => D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DMS, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2DMS: D3D12_TEX2DMS_SRV::default() }, + }, + 5 if !msaa => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: fmt, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, @@ -2834,6 +2868,14 @@ fn uav_companion_srv( }, }, }, + 5 | 7 => D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DMSArray: D3D12_TEX2DMS_ARRAY_SRV { FirstArraySlice: first_slice, ArraySize: array_size }, + }, + }, 8 => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: fmt, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE3D, @@ -2850,6 +2892,7 @@ fn uav_companion_srv( srv = v; } } + srv.Format = concrete_srv_format(srv.Format); Some(srv) } @@ -9883,6 +9926,260 @@ void main() { ); } } + + #[test] + fn uav_companion_srv_msaa_typeless_and_null_uav_dimensions() { + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM, + DXGI_FORMAT_D32_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_TYPELESS, + DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, + }; + + let msaa_tex = |slices: u16, fmt: DXGI_FORMAT| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 32, + Height: 32, + DepthOrArraySize: slices, + MipLevels: 1, + Format: fmt, + SampleDesc: DXGI_SAMPLE_DESC { Count: 4, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + + // MSAA 2D texture -> TEXTURE2DMS (both default desc and explicit Texture2D UAV desc) + let ms2d = msaa_tex(1, DXGI_FORMAT_R8G8B8A8_UNORM); + let srv_ms2d_def = uav_companion_srv(Some(&ms2d), None, false).expect("MSAA 2D default companion SRV"); + assert_eq!((srv_ms2d_def.ViewDimension, srv_ms2d_def.Format), (D3D12_SRV_DIMENSION_TEXTURE2DMS, DXGI_FORMAT_R8G8B8A8_UNORM)); + let u2d = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let srv_ms2d = uav_companion_srv(Some(&ms2d), Some(&u2d), false).expect("MSAA 2D companion SRV"); + assert_eq!((srv_ms2d.ViewDimension, srv_ms2d.Format), (D3D12_SRV_DIMENSION_TEXTURE2DMS, DXGI_FORMAT_R8G8B8A8_UNORM)); + + // MSAA 2DArray texture -> TEXTURE2DMSARRAY with resolved slice range + let ms2da = msaa_tex(4, DXGI_FORMAT_R16G16B16A16_FLOAT); + let u2da = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: 0, FirstArraySlice: 1, ArraySize: u32::MAX, PlaneSlice: 0 }, + }, + }; + let srv_ms2da = uav_companion_srv(Some(&ms2da), Some(&u2da), false).expect("MSAA 2DArray companion SRV"); + assert_eq!((srv_ms2da.ViewDimension, srv_ms2da.Format), (D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY, DXGI_FORMAT_R16G16B16A16_FLOAT)); + assert_eq!(unsafe { (srv_ms2da.Anonymous.Texture2DMSArray.FirstArraySlice, srv_ms2da.Anonymous.Texture2DMSArray.ArraySize) }, (1, 3)); + + // Non-depth *_TYPELESS resources with desc == None / Format == UNKNOWN resolve to concrete same-family formats + for (typeless, want) in [ + (DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM), + (DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_FLOAT), + (DXGI_FORMAT_B8G8R8A8_TYPELESS, DXGI_FORMAT_B8G8R8A8_UNORM), + (DXGI_FORMAT_BC1_TYPELESS, DXGI_FORMAT_BC1_UNORM), + ] { + let rd = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, typeless, D3D12_RESOURCE_FLAG_NONE); + let s_def = uav_companion_srv(Some(&rd), None, false).expect("typeless default SRV"); + assert_eq!(s_def.Format, want, "default SRV for {typeless:?}"); + let u_unk = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + let s_unk = uav_companion_srv(Some(&rd), Some(&u_unk), false).expect("typeless UNKNOWN-format SRV"); + assert_eq!(s_unk.Format, want, "UNKNOWN-format SRV for {typeless:?}"); + } + + // Null-resource companion SRV never emits a typeless or depth format + let u_null_typeless = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R8G8B8A8_TYPELESS, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + assert_eq!(uav_companion_srv(None, Some(&u_null_typeless), true).unwrap().Format, DXGI_FORMAT_R8G8B8A8_UNORM); + let u_null_depth = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_D32_FLOAT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + assert_eq!(uav_companion_srv(None, Some(&u_null_depth), true).unwrap().Format, DXGI_FORMAT_R32_FLOAT); + + // null_uav_desc sets valid non-zero ArraySize / WSize and falls back to rd when ViewDimension == UNKNOWN + let rd1da = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 16, 1, 3, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let rd2da = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 3, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let rd3d = tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + let n1da = null_uav_desc(None, Some(&rd1da)); + let n2da = null_uav_desc(None, Some(&rd2da)); + let n3d = null_uav_desc(None, Some(&rd3d)); + assert_eq!((n1da.ViewDimension, unsafe { n1da.Anonymous.Texture1DArray.ArraySize }), (D3D12_UAV_DIMENSION_TEXTURE1DARRAY, 1)); + assert_eq!((n2da.ViewDimension, unsafe { n2da.Anonymous.Texture2DArray.ArraySize }), (D3D12_UAV_DIMENSION_TEXTURE2DARRAY, 1)); + assert_eq!((n3d.ViewDimension, unsafe { n3d.Anonymous.Texture3D.WSize }), (D3D12_UAV_DIMENSION_TEXTURE3D, 1)); + let unk_dim = D3D12_UNORDERED_ACCESS_VIEW_DESC::default(); + let n_unk = null_uav_desc(Some(&unk_dim), Some(&rd3d)); + assert_eq!((n_unk.ViewDimension, unsafe { n_unk.Anonymous.Texture3D.WSize }), (D3D12_UAV_DIMENSION_TEXTURE3D, 1)); + } + + /// D3D12 debug layer: verify `dev_create_uav_checked_x` null UAV fallback on Texture1DArray / + /// Texture2DArray / Texture3D and `dev_create_uav_x` companion SRVs on MSAA and non-depth + /// `*_TYPELESS` textures produce zero D3D12 validation errors (#2461). + #[test] + fn gpu_uav_null_fallback_and_msaa_typeless_companion_srv_debug_layer() { + const CHILD: &str = "XCL_TEST_UAV_DEBUG_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::real::uav_companion_srv_tests::gpu_uav_null_fallback_and_msaa_typeless_companion_srv_debug_layer", "--nocapture"]) + .env(CHILD, "1") + .env("XCL_UMA_MB", "64") + .env("XCL_COHERENT_MB", "64") + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + for line in stderr.lines().filter(|l| l.starts_with("SKIPPED ")) { + eprintln!("{line}"); + } + assert!( + output.status.success(), + "child failed ({:?}):\nstdout:\n{}\nstderr:\n{}", + output.status, + String::from_utf8_lossy(&output.stdout), + stderr + ); + return; + } + + unsafe { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::{ + DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_UNKNOWN, + }; + + match crate::gpu::agility::configuration_interface::(&CLSID_D3D12Debug) { + Ok(d) => d.EnableDebugLayer(), + Err(e) => { + crate::gpu::recomp::runner::skip_test(&format!("no D3D12 debug layer ({e})")); + return; + } + } + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Ok(iq) = dev.cast::() else { + crate::gpu::recomp::runner::skip_test("device has no D3D12InfoQueue"); + return; + }; + let take_errors = |q: &ID3D12InfoQueue| -> Vec { + let mut out = Vec::new(); + for i in 0..q.GetNumStoredMessages() { + let mut len = 0usize; + if q.GetMessage(i, None, &mut len).is_err() || len == 0 { + continue; + } + let mut buf = vec![0u64; len.div_ceil(8)]; + let m = buf.as_mut_ptr() as *mut D3D12_MESSAGE; + if q.GetMessage(i, Some(m), &mut len).is_ok() + && matches!((*m).Severity, D3D12_MESSAGE_SEVERITY_ERROR | D3D12_MESSAGE_SEVERITY_CORRUPTION) + { + let d = std::slice::from_raw_parts((*m).pDescription as *const u8, (*m).DescriptionByteLength.saturating_sub(1)); + out.push(String::from_utf8_lossy(d).into_owned()); + } + } + q.ClearStoredMessages(); + out + }; + + assert!(crate::gpu::uma::get().is_some(), "UMA init failed in test subprocess"); + adopt(dev.as_raw(), Kind::Device); + + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + let heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: 32, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }) + .expect("CPU descriptor heap"); + let heap_key = heap.as_raw() as usize; + assert!(super::super::console_heap::register( + heap_key, + 16, + heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, + 0, + inc, + false, + false, + false, + )); + let base_cpu = super::super::console_heap::start(heap_key).expect("console heap start"); + let slot_cpu = |k: u64| base_cpu + k * super::super::console_heap::SLOT as u64; + + let default_heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let make_tex = |desc: &D3D12_RESOURCE_DESC| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r) + .expect("CreateCommittedResource"); + r.unwrap() + }; + + let uav_flag = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let t1da_typeless = make_tex(&tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 16, 1, 3, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, uav_flag)); + let t2da_typeless = make_tex(&tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 3, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, uav_flag)); + let t3d_typeless = make_tex(&tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, uav_flag)); + let t2d_typeless_nouav = make_tex(&tex_desc(D3D12_RESOURCE_DIMENSION_TEXTURE2D, 16, 16, 1, 1, DXGI_FORMAT_R8G8B8A8_TYPELESS, D3D12_RESOURCE_FLAG_NONE)); + let msaa_desc = |slices: u16, fmt: DXGI_FORMAT| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: slices, + MipLevels: 1, + Format: fmt, + SampleDesc: DXGI_SAMPLE_DESC { Count: 4, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + ..Default::default() + }; + let ms2d = make_tex(&msaa_desc(1, DXGI_FORMAT_R8G8B8A8_UNORM)); + let ms2da = make_tex(&msaa_desc(3, DXGI_FORMAT_R16G16B16A16_FLOAT)); + + iq.ClearStoredMessages(); + + // 1. `dev_create_uav_checked_x` unsupported typed UAV fallback on 1DArray, 2DArray, 3D + dev_create_uav_checked_x(dev.as_raw(), t1da_typeless.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(0)); + dev_create_uav_checked_x(dev.as_raw(), t2da_typeless.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(1)); + dev_create_uav_checked_x(dev.as_raw(), t3d_typeless.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(2)); + let errs1 = take_errors(&iq); + assert!(errs1.is_empty(), "dev_create_uav_checked_x null UAV fallback debug errors: {errs1:#?}"); + + // 2. `dev_create_uav_x` companion SRV on MSAA 2D and MSAA 2DArray (no ALLOW_UNORDERED_ACCESS) + dev_create_uav_x(dev.as_raw(), ms2d.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(3)); + let u_ms2da = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_UAV { MipSlice: 0, FirstArraySlice: 1, ArraySize: u32::MAX, PlaneSlice: 0 }, + }, + }; + dev_create_uav_x(dev.as_raw(), ms2da.as_raw(), std::ptr::null_mut(), &u_ms2da, slot_cpu(4)); + let errs2 = take_errors(&iq); + assert!(errs2.is_empty(), "MSAA companion SRV debug errors: {errs2:#?}"); + + // 3. `dev_create_uav_x` companion SRV on non-depth *_TYPELESS texture with desc == NULL and Format == UNKNOWN + dev_create_uav_x(dev.as_raw(), t2d_typeless_nouav.as_raw(), std::ptr::null_mut(), std::ptr::null(), slot_cpu(5)); + let u_unk = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + ..Default::default() + }; + dev_create_uav_x(dev.as_raw(), t2d_typeless_nouav.as_raw(), std::ptr::null_mut(), &u_unk, slot_cpu(6)); + let errs3 = take_errors(&iq); + assert!(errs3.is_empty(), "typeless companion SRV debug errors: {errs3:#?}"); + + super::super::console_heap::unregister(heap_key); + } + } } From c3e73a77a60266837c66ba2ee108f1c4186668f0 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:35:00 +0100 Subject: [PATCH 128/258] D3D12.X: place shader io (u0) in VRAM and hoist preludes per segment Translated compute, graphics, and two-pass mesh shaders read their user SGPRs (io, root UAV u0) on entry from UMA coherent system memory over PCIe, stalling wavefronts on the first u0 load. Separately, any earlier compute dispatch on a command list set prelude_blocked = true for the rest of the list, preventing trailing two-pass ExecuteIndirect(DispatchMesh) bursts from hoisting into batched PRELUDE_SCALE_* passes (only 1 job hoisted across a 300s world-load run). Implement both runtime-only FPS improvements cleanly in ind.rs and list_x.rs (zero shader translation or DXIL cache-key changes): - Pool paired 64 KiB persistently-mapped UPLOAD and L1 VRAM DEFAULT (ALLOW_UNORDERED_ACCESS, UNORDERED_ACCESS state) IoBlock slabs (FREE_IO, 64 MiB cap, XCL_VRAM_IO=0 opt-out). During recording, ind_abi (io + dummy_res_va) and ind_two_pass_stage write into upload and bind the final ram GPU VA directly; prelude_list_for copies --- crates/xcl/src/hle/d3d12x/bind.rs | 601 ++++++++++++++++++++-------- crates/xcl/src/hle/d3d12x/list_x.rs | 22 + 2 files changed, 459 insertions(+), 164 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index ad4de4301b..374b869819 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -118,6 +118,29 @@ struct PreludeScaleJob { type PreludeEntry = (ID3D12CommandAllocator, ID3D12GraphicsCommandList, usize, i32); +/// Paired persistently-mapped `UPLOAD` slab and L1 VRAM `DEFAULT` (`ALLOW_UNORDERED_ACCESS`) slab +/// for a recording's `io` (`u0`) user-SGPR blocks. CPU writes `io` bytes into `upload` during +/// command-list recording and `prelude_list_for` copies `0..used` into `vram` once before the +/// segment executes, avoiding PCIe/system-RAM stalls on every shader's first `u0` load. +struct IoBlock { + vram: ID3D12Resource, + upload: ID3D12Resource, + mapped: usize, + vram_va: u64, + cap: u64, + used: u64, + dev_key: usize, +} + +impl Drop for IoBlock { + fn drop(&mut self) { + if self.mapped != 0 { + unsafe { self.upload.Unmap(0, None) }; + self.mapped = 0; + } + } +} + #[derive(Default)] struct State { layout: Option>, @@ -178,6 +201,8 @@ struct State { io_cache_cs: Option<(u64, Option, u64)>, io_cache_tp_cs: Option<(u64, u64)>, io_cache_tp_ms: Option<(u64, u64)>, + /// L1 VRAM `io` (`u0`) slabs populated during this recording and copied in `prelude_list_for` + io_blocks: Vec, } /// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its @@ -186,11 +211,17 @@ const SCRATCH_BLOCK: u64 = 1 << 20; const SCRATCH_CAP: u64 = 16 << 20; /// Most bytes of buffers kept for reuse (`FREE_RES`) const FREE_RES_CAP: u64 = 256 << 20; +/// Size of one pooled VRAM `io` (`u0`) slab (64 KiB = 256 distinct 256-byte `io` slots). +const IO_BLOCK_BYTES: u64 = 64 << 10; +/// Most bytes of VRAM `io` slabs kept for reuse (`FREE_IO`). +const FREE_IO_CAP: u64 = 64 << 20; /// Most recycled prelude (allocator, list) pairs kept for reuse (`FREE_PRELUDE`) -const FREE_PRELUDE_CAP: usize = 64; +const FREE_PRELUDE_CAP: usize = 256; static ALLOC_RES: Mutex>>> = Mutex::new(None); static FREE_RES: Mutex> = Mutex::new(Vec::new()); +static ALLOC_IO: Mutex>>> = Mutex::new(None); +static FREE_IO: Mutex> = Mutex::new(Vec::new()); static ALLOC_PRELUDE: Mutex>>> = Mutex::new(None); static FREE_PRELUDE: Mutex> = Mutex::new(Vec::new()); @@ -201,6 +232,13 @@ fn hold_res_until_reset(allocator: usize, mut bufs: Vec<(ID3D12Resource, u64, us ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); } +fn hold_io_until_reset(allocator: usize, mut blocks: Vec) { + if blocks.is_empty() || allocator == 0 { + return; + } + ALLOC_IO.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut blocks); +} + fn hold_prelude_until_reset(allocator: usize, entry: Option) { let Some(entry) = entry else { return }; if allocator == 0 { @@ -219,6 +257,16 @@ pub(super) fn release_allocator_res(allocator: usize) { } } } + if let Some(blocks) = ALLOC_IO.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { + let mut free = FREE_IO.lock().unwrap(); + for mut b in blocks { + b.used = 0; + let held: u64 = free.iter().map(|f| f.cap).sum(); + if io_pool_keeps(held, b.cap) { + free.push(b); + } + } + } if let Some(entries) = ALLOC_PRELUDE.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { let mut free = FREE_PRELUDE.lock().unwrap(); for e in entries { @@ -234,6 +282,121 @@ fn pool_keeps(count: usize, held: u64, bytes: u64) -> bool { count < 16 && held + bytes <= FREE_RES_CAP } +/// Whether `FREE_IO`, holding `held` bytes of VRAM `io` slabs, keeps one of `bytes` more. +fn io_pool_keeps(held: u64, bytes: u64) -> bool { + held.saturating_add(bytes) <= FREE_IO_CAP +} + +/// `XCL_VRAM_IO=0`: keep `io` (`u0`) user-SGPR buffers in UMA system RAM instead of L1 VRAM. +fn vram_io_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_VRAM_IO").map_or(true, |v| v.trim() != "0")) +} + +/// Return the device if `this` can place `io` (`u0`) slots in L1 VRAM (wrapped DIRECT/COMPUTE +/// command list whose prelude list runs before it on submit). +unsafe fn vram_io_device(this: *mut c_void) -> Option { + if !vram_io_on() + || super::title_list::wrapper_of(this).is_none() + || !matches!( + super::list_x::tracked_list_type(this), + Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE) + ) + { + return None; + } + super::real::list_device(this) +} + +unsafe fn create_io_block(dev: &ID3D12Device, cap: u64) -> Option { + let vram_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: cap, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut vram: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &vram_desc, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + None, + &mut vram, + ) + .ok()?; + let vram = vram?; + let _ = vram.SetName(windows::core::w!("xcl io vram")); + let vram_va = vram.GetGPUVirtualAddress(); + if vram_va == 0 { + return None; + } + let up_desc = D3D12_RESOURCE_DESC { + Flags: D3D12_RESOURCE_FLAG_NONE, + ..vram_desc + }; + let mut upload: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &up_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut upload, + ) + .ok()?; + let upload = upload?; + let _ = upload.SetName(windows::core::w!("xcl io upload")); + let mut mapped = std::ptr::null_mut(); + let empty_read = D3D12_RANGE { Begin: 0, End: 0 }; + upload.Map(0, Some(&empty_read), Some(&mut mapped)).ok()?; + if mapped.is_null() { + return None; + } + Some(IoBlock { + vram, + upload, + mapped: mapped as usize, + vram_va, + cap, + used: 0, + dev_key: dev.as_raw() as usize, + }) +} + +/// Write `bytes` into a 256-byte-aligned slot of `io_blocks` and return its L1 VRAM GPU VA. +unsafe fn alloc_vram_io_in(io_blocks: &mut Vec, allocator: usize, prelude_built: bool, dev: &ID3D12Device, bytes: &[u8]) -> Option { + if allocator == 0 || prelude_built { + return None; + } + let take = (bytes.len().max(16) as u64).next_multiple_of(256); + if let Some(b) = io_blocks.last_mut().filter(|b| b.used + take <= b.cap) { + let off = b.used; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), (b.mapped as *mut u8).add(off as usize), bytes.len()); + b.used += take; + return Some(b.vram_va + off); + } + let dev_key = dev.as_raw() as usize; + let mut block = { + let mut free = FREE_IO.lock().unwrap(); + free.iter().position(|b| b.dev_key == dev_key && b.cap >= take).map(|i| free.swap_remove(i)) + }; + if block.is_none() { + block = create_io_block(dev, take.max(IO_BLOCK_BYTES)); + } + let mut b = block?; + std::ptr::copy_nonoverlapping(bytes.as_ptr(), b.mapped as *mut u8, bytes.len()); + b.used = take; + let va = b.vram_va; + io_blocks.push(b); + Some(va) +} + static STATES: Mutex>> = Mutex::new(None); /// draws / dispatches of console code: with a translated pipeline, skipped, with a PC one @@ -277,6 +440,14 @@ pub(super) fn note_gpu_write(list: *mut c_void) { }); } +/// Allow indirect-argument prelude hoisting on a freshly split continuation segment whose +/// predecessor finished on the same queue with no cross-queue head fence wait. +pub(super) fn unblock_prelude(list: *mut c_void) { + with(list, |s| { + s.prelude_blocked = false; + }); +} + /// Resolve the PC backing allocator that actually owns `list`'s recording (`alloc_pool` can swap /// a title allocator to a new PC allocator while recordings on the old backing are still in flight, /// so UMA arena blocks and scratch buffers must stay pinned to the backing allocator until @@ -293,7 +464,7 @@ fn backing_allocator(list: *mut c_void, allocator: usize) -> usize { /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { let backing = backing_allocator(list, allocator); - let (old, blocks, res_bufs, prelude) = with(list, |s| { + let (old, blocks, res_bufs, io_blocks, prelude) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.pso = initial_pso; @@ -330,11 +501,13 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { if let Some(b) = s.res_buf.take() { res_bufs.push(b); } + let io_blocks = std::mem::take(&mut s.io_blocks); s.rs_cs = 0; - (old, std::mem::take(&mut s.uma), res_bufs, prelude) + (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude) }); console_list::hold_until_reset(old, blocks); hold_res_until_reset(old, res_bufs); + hold_io_until_reset(old, io_blocks); hold_prelude_until_reset(old, prelude); } @@ -373,7 +546,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u let (layout, args, layout_gfx, args_gfx, rs_gfx, rs_cs, pso, heaps) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.rs_cs, s.pso, s.heaps) }); - let (old, blocks, res_bufs, prelude) = with(to, |s| { + let (old, blocks, res_bufs, io_blocks, prelude) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.layout = layout; @@ -408,10 +581,12 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.io_cache_cs = None; s.io_cache_tp_cs = None; s.io_cache_tp_ms = None; - (old, std::mem::take(&mut s.uma), std::mem::take(&mut s.res_retired), prelude) + let io_blocks = std::mem::take(&mut s.io_blocks); + (old, std::mem::take(&mut s.uma), std::mem::take(&mut s.res_retired), io_blocks, prelude) }); console_list::hold_until_reset(old, blocks); hold_res_until_reset(old, res_bufs); + hold_io_until_reset(old, io_blocks); hold_prelude_until_reset(old, prelude); } @@ -439,6 +614,7 @@ pub(super) fn forget(list: *mut c_void) { s.res_retired.push(b); } hold_res_until_reset(s.allocator, s.res_retired); + hold_io_until_reset(s.allocator, s.io_blocks); hold_prelude_until_reset(s.allocator, s.prelude_owned.take()); } } @@ -925,6 +1101,7 @@ unsafe fn bind_two_pass_stage( let pso_raw = if compute_pass { tp.compute } else { real_mesh_pso } as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or(if compute_pass { "two-pass compute pipeline" } else { "two-pass mesh pipeline" })?; + let io_dev = vram_io_device(this); let (set_rs, uav_mask, views) = with(this, |s| -> Result<(bool, u8, [u64; 6]), String> { if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { let w = super::real::uma_window_vas(); @@ -962,9 +1139,15 @@ unsafe fn bind_two_pass_stage( } let io = two_pass_io(layout, args, table_p as u64, compute_pass, u.base(), s.heaps); let io_bytes = io.len() * 4; - let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(io.as_ptr().cast::(), io_p, io_bytes); - let va = uma_va_in(u, windows, io_p as usize).unwrap_or(first); + let io_slice = std::slice::from_raw_parts(io.as_ptr().cast::(), io_bytes); + let va = match io_dev.as_ref().and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), dev, io_slice)) { + Some(va) => va, + None => { + let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(io_slice.as_ptr(), io_p, io_bytes); + uma_va_in(u, windows, io_p as usize).unwrap_or(first) + } + }; if compute_pass { s.io_cache_tp_cs = Some((s.args_gen_gfx, va)); } else { @@ -1581,22 +1764,29 @@ unsafe fn alloc_prelude_scratch(this: *mut c_void, dev: &ID3D12Device, bytes: u6 Ok((b, 0, buf_idx)) } -/// Build (once per recording) and return the closed PC prelude command list that runs all hoisted -/// indirect-argument clamp/scale jobs for `seg` before `seg` executes on the queue. +/// Build (once per recording) and return the closed PC prelude command list that runs all VRAM +/// `io` (`u0`) uploads and hoisted indirect-argument clamp/scale jobs for `seg` before `seg` +/// executes on the queue. pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { - let (already, bufs, guards, scales) = with(seg, |s| { + let (already, io_copies, bufs, guards, scales) = with(seg, |s| { if let Some(ref built) = s.prelude_built { - return (Some(built.as_raw()), Vec::new(), Vec::new(), Vec::new()); - } - if s.prelude_guards.is_empty() && s.prelude_scales.is_empty() { - return (None, Vec::new(), Vec::new(), Vec::new()); - } - (None, s.prelude_bufs.clone(), s.prelude_guards.clone(), s.prelude_scales.clone()) + return (Some(built.as_raw()), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + } + let io_copies: Vec<(ID3D12Resource, ID3D12Resource, u64)> = s + .io_blocks + .iter() + .filter(|b| b.used > 0) + .map(|b| (b.vram.clone(), b.upload.clone(), b.used)) + .collect(); + if io_copies.is_empty() && s.prelude_guards.is_empty() && s.prelude_scales.is_empty() { + return (None, Vec::new(), Vec::new(), Vec::new(), Vec::new()); + } + (None, io_copies, s.prelude_bufs.clone(), s.prelude_guards.clone(), s.prelude_scales.clone()) }); if let Some(p) = already { return Some(p); } - if guards.is_empty() && scales.is_empty() { + if io_copies.is_empty() && guards.is_empty() && scales.is_empty() { return None; } let run = (|| -> Result { @@ -1605,24 +1795,6 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { return Err("unsupported list type for prelude".into()); } - let u = crate::gpu::uma::get().ok_or("no unified memory")?; - let win_vas = with(seg, |s| -> Result<[u64; 4], String> { - if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { - let w = super::real::uma_window_vas(); - if w.is_empty() { - return Err("unified memory is not open on the GPU".into()); - } - s.uma_windows = Some(w); - } - let w = s.uma_windows.as_deref().unwrap(); - let first = w[0]; - Ok([ - first, - w.get(1).copied().filter(|&v| v != 0).unwrap_or(first), - w.get(2).copied().filter(|&v| v != 0).unwrap_or(first), - w.get(3).copied().filter(|&v| v != 0).unwrap_or(first), - ]) - })?; let dev_key = dev.as_raw() as usize; let reused = { @@ -1642,139 +1814,201 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { } }; - // 1. Order prior queue writes into UMA and transition all prelude scratch buffers COMMON -> UAV. - let mut pre_barriers: Vec = Vec::with_capacity(1 + bufs.len()); - pre_barriers.push(D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), - }, - }); - for b in &bufs { + // 0. Upload all VRAM `io` (`u0`) slabs (`UNORDERED_ACCESS -> COPY_DEST -> CopyBufferRegion + // -> UNORDERED_ACCESS`) so `seg`'s shaders read user SGPRs from L1 VRAM. + if !io_copies.is_empty() { + let mut to_copy: Vec = Vec::with_capacity(io_copies.len()); + let mut to_uav: Vec = Vec::with_capacity(io_copies.len()); + for (vram, _, _) in &io_copies { + to_copy.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(vram.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_COPY_DEST, + }), + }, + }); + to_uav.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(vram.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_COPY_DEST, + StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + }), + }, + }); + } + list.ResourceBarrier(&to_copy); + for (vram, upload, used) in &io_copies { + list.CopyBufferRegion(vram, 0, upload, 0, *used); + } + list.ResourceBarrier(&to_uav); + for b in to_copy.iter_mut().chain(to_uav.iter_mut()) { + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); + } + } + + if !guards.is_empty() || !scales.is_empty() { + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + let win_vas = with(seg, |s| -> Result<[u64; 4], String> { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + let w = super::real::uma_window_vas(); + if w.is_empty() { + return Err("unified memory is not open on the GPU".into()); + } + s.uma_windows = Some(w); + } + let w = s.uma_windows.as_deref().unwrap(); + let first = w[0]; + Ok([ + first, + w.get(1).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(2).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(3).copied().filter(|&v| v != 0).unwrap_or(first), + ]) + })?; + + // 1. Order prior queue writes into UMA and transition all prelude scratch buffers COMMON -> UAV. + let mut pre_barriers: Vec = Vec::with_capacity(1 + bufs.len()); pre_barriers.push(D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { - Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { - pResource: std::mem::ManuallyDrop::new(Some(b.clone())), - Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - StateBefore: D3D12_RESOURCE_STATE_COMMON, - StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - }), + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), }, }); - } - list.ResourceBarrier(&pre_barriers); - for b in pre_barriers.iter_mut().skip(1) { - std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); - } - - // Helper to upload a packed `u32` job slice into `seg`'s UMA arena. - let upload_words = |words: &[u32]| -> Result { - let bytes = std::mem::size_of_val(words); - let p = with(seg, |s| s.arena.take(u, bytes.max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), p, bytes); - super::real::uma_va_of(p as usize).ok_or_else(|| "unified memory is not open on the GPU".into()) - }; - - let bind_windows = |list: &ID3D12GraphicsCommandList| { - for (k, &va) in win_vas.iter().enumerate() { - list.SetComputeRootUnorderedAccessView((2 + k) as u32, va); + for b in &bufs { + pre_barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(b.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_COMMON, + StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + }), + }, + }); + } + list.ResourceBarrier(&pre_barriers); + for b in pre_barriers.iter_mut().skip(1) { + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); } - }; - let shared_heap = super::console_heap::window_views_ready().then(super::console_heap::global_heap).flatten(); - if let Some(ref heap) = shared_heap { - list.SetDescriptorHeaps(&[Some(heap.clone())]); - } + // Helper to upload a packed `u32` job slice into `seg`'s UMA arena. + let upload_words = |words: &[u32]| -> Result { + let bytes = std::mem::size_of_val(words); + let p = with(seg, |s| s.arena.take(u, bytes.max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), p, bytes); + super::real::uma_va_of(p as usize).ok_or_else(|| "unified memory is not open on the GPU".into()) + }; - // 2. Emit batched guard dispatches grouped by prelude scratch buffer. - if !guards.is_empty() { - let (rs, pso) = if shared_heap.is_some() { prelude_guard_heap_pipeline(&dev)? } else { prelude_guard_pipeline(&dev)? }; - list.SetComputeRootSignature(&rs); - if shared_heap.is_none() { - bind_windows(&list); + let bind_windows = |list: &ID3D12GraphicsCommandList| { + for (k, &va) in win_vas.iter().enumerate() { + list.SetComputeRootUnorderedAccessView((2 + k) as u32, va); + } + }; + + let shared_heap = super::console_heap::window_views_ready().then(super::console_heap::global_heap).flatten(); + if let Some(ref heap) = shared_heap { + list.SetDescriptorHeaps(&[Some(heap.clone())]); } - list.SetPipelineState(&pso); - for (buf_idx, buf) in bufs.iter().enumerate() { - let batch: Vec<&PreludeGuardJob> = guards.iter().filter(|j| j.buf_idx == buf_idx).collect(); - if batch.is_empty() { - continue; + + // 2. Emit batched guard dispatches grouped by prelude scratch buffer. + if !guards.is_empty() { + let (rs, pso) = if shared_heap.is_some() { prelude_guard_heap_pipeline(&dev)? } else { prelude_guard_pipeline(&dev)? }; + list.SetComputeRootSignature(&rs); + if shared_heap.is_none() { + bind_windows(&list); } - let dst_va = buf.GetGPUVirtualAddress(); - list.SetComputeRootUnorderedAccessView(1, dst_va); - for chunk in batch.chunks(65_535 * 64) { - let mut words = Vec::with_capacity(4 + chunk.len() * 8); - words.extend_from_slice(&[chunk.len() as u32, 0, 0, 0]); - for j in chunk { - words.extend_from_slice(&[j.src_win, j.src_off, j.most, j.dst_off, j.lim_win, j.lim_off, 0, 0]); + list.SetPipelineState(&pso); + for (buf_idx, buf) in bufs.iter().enumerate() { + let batch: Vec<&PreludeGuardJob> = guards.iter().filter(|j| j.buf_idx == buf_idx).collect(); + if batch.is_empty() { + continue; + } + let dst_va = buf.GetGPUVirtualAddress(); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for chunk in batch.chunks(65_535 * 64) { + let mut words = Vec::with_capacity(4 + chunk.len() * 8); + words.extend_from_slice(&[chunk.len() as u32, 0, 0, 0]); + for j in chunk { + words.extend_from_slice(&[j.src_win, j.src_off, j.most, j.dst_off, j.lim_win, j.lim_off, 0, 0]); + } + let jobs_va = upload_words(&words)?; + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.Dispatch((chunk.len() as u32).div_ceil(64), 1, 1); } - let jobs_va = upload_words(&words)?; - list.SetComputeRootUnorderedAccessView(0, jobs_va); - list.Dispatch((chunk.len() as u32).div_ceil(64), 1, 1); } } - } - // 3. Emit batched scale dispatches grouped by prelude scratch buffer. - if !scales.is_empty() { - let (rs, pso) = if shared_heap.is_some() { prelude_scale_heap_pipeline(&dev)? } else { prelude_scale_pipeline(&dev)? }; - list.SetComputeRootSignature(&rs); - if shared_heap.is_none() { - bind_windows(&list); - } - list.SetPipelineState(&pso); - for (buf_idx, buf) in bufs.iter().enumerate() { - let batch: Vec<&PreludeScaleJob> = scales.iter().filter(|j| j.buf_idx == buf_idx).collect(); - if batch.is_empty() { - continue; + // 3. Emit batched scale dispatches grouped by prelude scratch buffer. + if !scales.is_empty() { + let (rs, pso) = if shared_heap.is_some() { prelude_scale_heap_pipeline(&dev)? } else { prelude_scale_pipeline(&dev)? }; + list.SetComputeRootSignature(&rs); + if shared_heap.is_none() { + bind_windows(&list); } - let dst_va = buf.GetGPUVirtualAddress(); - list.SetComputeRootUnorderedAccessView(1, dst_va); - for chunk in batch.chunks(65_535) { - let mut words = Vec::with_capacity(chunk.len() * 12); - for j in chunk { - words.extend_from_slice(&[ - j.count, j.stride, j.mesh_offset, j.split, j.cap, j.src_win, j.src_off, j.dst_off, j.has_cnt, j.cnt_win, j.cnt_off, 0, - ]); + list.SetPipelineState(&pso); + for (buf_idx, buf) in bufs.iter().enumerate() { + let batch: Vec<&PreludeScaleJob> = scales.iter().filter(|j| j.buf_idx == buf_idx).collect(); + if batch.is_empty() { + continue; + } + let dst_va = buf.GetGPUVirtualAddress(); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for chunk in batch.chunks(65_535) { + let mut words = Vec::with_capacity(chunk.len() * 12); + for j in chunk { + words.extend_from_slice(&[ + j.count, j.stride, j.mesh_offset, j.split, j.cap, j.src_win, j.src_off, j.dst_off, j.has_cnt, j.cnt_win, j.cnt_off, 0, + ]); + } + let jobs_va = upload_words(&words)?; + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.Dispatch(chunk.len() as u32, 1, 1); } - let jobs_va = upload_words(&words)?; - list.SetComputeRootUnorderedAccessView(0, jobs_va); - list.Dispatch(chunk.len() as u32, 1, 1); } } - } - // 4. Transition all prelude scratch buffers UAV -> INDIRECT_ARGUMENT (plus global UAV - // barrier if any guard jobs wrote `IO_GROUP_LIMIT` into UMA). - let mut post_barriers: Vec = Vec::with_capacity(bufs.len() + usize::from(!guards.is_empty())); - for b in &bufs { - post_barriers.push(D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { - Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { - pResource: std::mem::ManuallyDrop::new(Some(b.clone())), - Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, - StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, - StateAfter: GUARDED_ARGS_STATE, - }), - }, - }); - } - if !guards.is_empty() { - post_barriers.push(D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, - Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, - Anonymous: D3D12_RESOURCE_BARRIER_0 { - UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), - }, - }); - } - list.ResourceBarrier(&post_barriers); - for b in post_barriers.iter_mut().take(bufs.len()) { - std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); + // 4. Transition all prelude scratch buffers UAV -> GUARDED_ARGS_STATE (plus global UAV + // barrier if any guard jobs wrote `IO_GROUP_LIMIT` into UMA). + let mut post_barriers: Vec = Vec::with_capacity(bufs.len() + usize::from(!guards.is_empty())); + for b in &bufs { + post_barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::ManuallyDrop::new(Some(b.clone())), + Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: GUARDED_ARGS_STATE, + }), + }, + }); + } + if !guards.is_empty() { + post_barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }), + }, + }); + } + list.ResourceBarrier(&post_barriers); + for b in post_barriers.iter_mut().take(bufs.len()) { + std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); + } } list.Close().map_err(|e| format!("prelude list close: {e}"))?; @@ -1782,13 +2016,23 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { s.prelude_owned = Some((alloc, list.clone(), dev_key, ty.0)); s.prelude_built = Some(list.clone()); }); - static BATCHES: AtomicU64 = AtomicU64::new(0); - static TOTAL_JOBS: AtomicU64 = AtomicU64::new(0); - let n_jobs = (guards.len() + scales.len()) as u64; - let b = BATCHES.fetch_add(1, Ordering::Relaxed) + 1; - let tot = TOTAL_JOBS.fetch_add(n_jobs, Ordering::Relaxed) + n_jobs; - if b == 1 || (b.is_power_of_two() && b >= 16) { - crate::xlog_info!("D3D12.X: indirect prelude batch #{b} ({} guard + {} scale jobs, {tot} hoisted total)", guards.len(), scales.len()); + if !guards.is_empty() || !scales.is_empty() { + static BATCHES: AtomicU64 = AtomicU64::new(0); + static TOTAL_JOBS: AtomicU64 = AtomicU64::new(0); + let n_jobs = (guards.len() + scales.len()) as u64; + let b = BATCHES.fetch_add(1, Ordering::Relaxed) + 1; + let tot = TOTAL_JOBS.fetch_add(n_jobs, Ordering::Relaxed) + n_jobs; + if b == 1 || (b.is_power_of_two() && b >= 16) { + crate::xlog_info!("D3D12.X: indirect prelude batch #{b} ({} guard + {} scale jobs, {tot} hoisted total)", guards.len(), scales.len()); + } + } + if !io_copies.is_empty() { + static IO_BATCHES: AtomicU64 = AtomicU64::new(0); + let b = IO_BATCHES.fetch_add(1, Ordering::Relaxed) + 1; + if b == 1 || (b.is_power_of_two() && b >= 1024) { + let bytes: u64 = io_copies.iter().map(|(_, _, n)| *n).sum(); + crate::xlog_info!("D3D12.X: VRAM io (u0) prelude upload #{b} ({} slabs, {bytes} B)", io_copies.len()); + } } Ok(list) })(); @@ -2402,6 +2646,15 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } if let Some(msig) = dispatch_mesh_sig_of(sig) { + // If an earlier compute dispatch blocked prelude hoisting on this segment, split once + // before the two-pass DispatchMesh burst so all consecutive indirect mesh draws hoist + // into one batched `PRELUDE_SCALE_*` dispatch instead of inline compute/barrier bubbles. + let mut this = this; + if max > 0 && args != 0 && indirect_prelude_on() && with(this, |s| s.prelude_blocked && s.allocator != 0 && s.prelude_built.is_none()) { + if let Some(next) = super::list_x::split_for_prelude(this) { + this = next; + } + } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; let run = (|| -> Result<(), String> { if max == 0 || args == 0 { @@ -3515,6 +3768,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi let real_ptr = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&real_ptr).ok_or("pipeline")?; + let io_dev = vram_io_device(this); let (set_rs, uav_mask, views) = with(this, |s| -> Result<(bool, u8, [u64; 6]), String> { if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { let w = super::real::uma_window_vas(); @@ -3535,9 +3789,14 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi // Runtime VS/PS/CS shaders never write to `u1` (`res`), so one zeroed 256-byte slot // per recording suffices across all `bind_abi` draws and dispatches. if s.dummy_res_va == 0 { - let p = s.arena.take(u, 256, 256, &mut s.uma).ok_or("unified memory is full")?; - std::ptr::write_bytes(p, 0, 256); - s.dummy_res_va = uma_va_in(u, windows, p as usize).unwrap_or(first); + s.dummy_res_va = match io_dev.as_ref().and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), dev, &[0u8; 256])) { + Some(va) => va, + None => { + let p = s.arena.take(u, 256, 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::write_bytes(p, 0, 256); + uma_va_in(u, windows, p as usize).unwrap_or(first) + } + }; } let res_va = s.dummy_res_va; @@ -3572,9 +3831,15 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; io[crate::gpu::recomp::IO_GROUP_LIMIT] = group_limit; let io_bytes = io.len() * 4; - let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(io.as_ptr().cast::(), io_p, io_bytes); - let va = uma_va_in(u, windows, io_p as usize).unwrap_or(first); + let io_slice = std::slice::from_raw_parts(io.as_ptr().cast::(), io_bytes); + let va = match io_dev.as_ref().and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), dev, io_slice)) { + Some(va) => va, + None => { + let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(io_slice.as_ptr(), io_p, io_bytes); + uma_va_in(u, windows, io_p as usize).unwrap_or(first) + } + }; if group_limit == 0 { if gfx { s.io_cache_gfx = Some((s.args_gen_gfx, va)); @@ -5181,12 +5446,20 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) assert!(!s.arg_order_clean); assert_eq!(s.prelude_guards.len(), 1); }); - // Mid-list split (`from != to`) blocks hoisting on the continuation segment (Wait64 head). + // Mid-list split (`from != to`) blocks hoisting on the continuation segment (Wait64 head); + // `unblock_prelude` re-enables hoisting for splits without a head wait (`split_for_prelude`, `defer`). inherit_for_split(a, b, 0x7710_A001); with(b, |s| { assert!(s.prelude_blocked); assert!(s.prelude_guards.is_empty()); }); + unblock_prelude(b); + with(b, |s| { + assert!(!s.prelude_blocked); + }); + assert!(io_pool_keeps(0, IO_BLOCK_BYTES)); + assert!(io_pool_keeps(FREE_IO_CAP - IO_BLOCK_BYTES, IO_BLOCK_BYTES)); + assert!(!io_pool_keeps(FREE_IO_CAP, IO_BLOCK_BYTES)); // KickoffX non-split (`from == to`) starts a fresh post-kickoff segment and unblocks hoisting. inherit_for_split(a, a, 0x7710_A001); with(a, |s| { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 688c5b1431..a7e18f1698 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3113,11 +3113,33 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } super::bind::inherit_for_split(list, seg, alloc); super::bind::pass_arena(list, next_pc); + // A deferred-dispatch split has no head fence wait on `next_pc` (`seg` executes on the + // same queue before `next_pc`'s prelude), so `next_pc` may hoist indirect clamps again. + super::bind::unblock_prelude(next_pc); } super::title_list::activate_segment(wrapper, list, next_pc); Some(next_pc) } +/// Split `list` into a fresh continuation segment with an unblocked indirect-argument prelude +/// (used right before a two-pass `ExecuteIndirect(DispatchMesh)` burst after earlier compute +/// dispatches blocked hoisting on the current segment). Skips when predication or an occlusion +/// query is active so D3D12 command-list invariants stay intact. +pub(super) unsafe fn split_for_prelude(list: *mut c_void) -> Option<*mut c_void> { + let ok = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| { + s.allocator != 0 + && s.predication.is_none() + && s.occlusion.active.is_none() + && matches!(s.list_type, Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE)) + }); + if !ok { + return None; + } + let next = split(list, None)?; + super::bind::unblock_prelude(next); + Some(next) +} + /// A closed, empty segment of `wrapper`'s recording for a dispatch recorded at the submit, on the wrapper's own allocator. unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { let dev = device_of(list)?; From a747b3198f964664abb46c640deee7160c44472f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:36:11 +0100 Subject: [PATCH 129/258] D3D12.X: split pipeline library into immutable read handle and async save worker In Wave 11b (7582db3a), serializing Load*, StorePipeline, and Serialize on a single Mutex caused a 35-47 second convoy on compile workers and a 41.4 s exit flush whenever any Load* entered amdxc64 on a large shader. Split MmapPipelineLibrary into two independent ID3D12PipelineLibrary1 handles opened from the same read-only Arc: - read_lib: strictly immutable (never receives StorePipeline or Serialize), serving concurrent Load* calls lock-free per the D3D12 spec. - write_lib: owned exclusively by the dedicated xcl-plib-save worker thread and fed via an mpsc channel, so store() returns in ~1 us with zero driver lock contention and D3D12Core.dll never sees concurrent StorePipeline + Load* or Serialize races. - Bound shutdown flush() to a 5 s timeout after draining queued stores so exit never hangs. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/pso_library.rs | 313 ++++++++++++++++------- crates/xcl/src/hle/d3d12x/real.rs | 57 +---- 2 files changed, 218 insertions(+), 152 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_library.rs b/crates/xcl/src/hle/d3d12x/pso_library.rs index f7f5ae2a5a..9dd5a60d3e 100644 --- a/crates/xcl/src/hle/d3d12x/pso_library.rs +++ b/crates/xcl/src/hle/d3d12x/pso_library.rs @@ -10,8 +10,9 @@ use std::ffi::c_void; use std::os::windows::ffi::OsStrExt; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{mpsc, Arc, OnceLock}; +use std::time::{Duration, Instant}; use windows::core::{Interface, HSTRING}; use windows::Win32::Graphics::Direct3D12::*; @@ -349,27 +350,79 @@ fn cleanup_older_generations(dir: &Path, keep_gen: u64) { } } -/// Process-wide D3D12 pipeline library backed by a kept-open read-only `MappedBlob` and -/// generational zero-heap-copy serialization. +/// Minimum newly stored pipelines before triggering a periodic background generation save. +const SAVE_BATCH_THRESHOLD: u64 = 32; +/// Minimum spacing between periodic background saves while pipelines are streaming in. +const SAVE_MIN_INTERVAL: Duration = Duration::from_secs(15); +/// Idle delay after the last stored pipeline before flushing any remaining tail (`>= 1` dirty). +const SAVE_IDLE_FLUSH: Duration = Duration::from_secs(5); +/// Maximum time `flush()` waits on shutdown so exit can never hang behind a slow driver call. +const FLUSH_TIMEOUT: Duration = Duration::from_secs(5); + +/// Pure save-scheduling decision (unit-testable on CPU): +/// - Save immediately when `dirty >= SAVE_BATCH_THRESHOLD` and at least `SAVE_MIN_INTERVAL` +/// elapsed since the last save. +/// - Or save any tail (`dirty > 0`) once no new pipeline has been stored for `SAVE_IDLE_FLUSH`. +pub fn should_background_save(dirty: u64, now_ms: u64, last_store_ms: u64, last_save_ms: u64) -> bool { + if dirty == 0 { + return false; + } + let since_save = now_ms.saturating_sub(last_save_ms); + let since_store = now_ms.saturating_sub(last_store_ms); + (dirty >= SAVE_BATCH_THRESHOLD && since_save >= SAVE_MIN_INTERVAL.as_millis() as u64) + || (last_store_ms > 0 + && since_store >= SAVE_IDLE_FLUSH.as_millis() as u64 + && since_save >= SAVE_IDLE_FLUSH.as_millis() as u64) +} + +struct SendPso(ID3D12PipelineState); +unsafe impl Send for SendPso {} + +struct SendLib(ID3D12PipelineLibrary1); +unsafe impl Send for SendLib {} + +enum SaveCmd { + Store(String, SendPso), + Flush(mpsc::SyncSender>), +} + +unsafe fn create_empty_library(dev1: &ID3D12Device1) -> Option { + // Pass an explicit NULL pointer with length 0 rather than `&[]`, whose dangling + // non-null slice pointer vkd3d-proton rejects with E_INVALIDARG. + let mut lib: Option = None; + (Interface::vtable(dev1).CreatePipelineLibrary)( + Interface::as_raw(dev1), + std::ptr::null(), + 0, + &ID3D12PipelineLibrary1::IID, + &mut lib as *mut _ as *mut _, + ) + .ok() + .ok()?; + lib +} + +/// Process-wide D3D12 pipeline library split into two independent `ID3D12PipelineLibrary1` handles: +/// - `read_lib`: strictly immutable handle opened from the startup `MappedBlob`, serving concurrent +/// `Load*` calls lock-free per the D3D12 spec (never mutated by `StorePipeline` or `Serialize`). +/// - `write_lib`: owned exclusively by the dedicated `xcl-plib-save` worker thread, fed via an +/// `mpsc` channel so `store()` returns in ~1 µs with zero lock contention on compile workers and +/// `D3D12Core.dll` never sees concurrent `StorePipeline` + `Load*` or `Serialize` races. pub struct MmapPipelineLibrary { - lib: ID3D12PipelineLibrary1, - /// Kept alive for the entire lifetime of `lib` because D3D12 requires the initial blob memory - /// to remain valid until the `ID3D12PipelineLibrary` is destroyed. - _backing: Option, - store: LibraryStore, - dirty: AtomicU64, - saving: AtomicBool, - save_lock: Mutex<()>, - /// Serializes all `ID3D12PipelineLibrary1` operations (`Load*`, `StorePipeline`, - /// `GetSerializedSize`, `Serialize`). `D3D12Core.dll` is not thread-safe for concurrent - /// `StorePipeline` + `Load*` (races on internal lookup tables -> 0xc0000005). - lib_lock: Mutex<()>, + read_lib: Option, + /// Kept alive for the entire lifetime of `read_lib` because D3D12 requires the initial blob + /// memory to remain valid until the `ID3D12PipelineLibrary` is destroyed. + _read_backing: Option>, + /// Async command channel to the dedicated `xcl-plib-save` thread owning `write_lib`. + /// The mutex protects only the ~50 ns `mpsc::Sender::send` (never any D3D12 call). + save_tx: Option>>, + dirty: Arc, } -// `_backing` is read-only; `lib_lock` serializes all `ID3D12PipelineLibrary1` calls and -// `save_lock` serializes disk snapshots. -unsafe impl Send for MmapPipelineLibrary {} +// `read_lib` is strictly immutable after creation (`Load*` is free-threaded per D3D12 spec when +// never mutated by `StorePipeline` or `Serialize`); `save_tx` is synchronized by its Mutex. unsafe impl Sync for MmapPipelineLibrary {} +unsafe impl Send for MmapPipelineLibrary {} impl MmapPipelineLibrary { /// Open the latest memory-mapped pipeline library on `device`, falling back to a fresh empty @@ -380,6 +433,9 @@ impl MmapPipelineLibrary { } let dev1: ID3D12Device1 = device.cast().ok()?; let store = LibraryStore::for_adapter(adapter_name); + let mut read_lib: Option = None; + let mut backing: Option> = None; + if let Some((gen, blob)) = store.open_latest() { match dev1.CreatePipelineLibrary::(blob.as_slice()) { Ok(lib) => { @@ -387,15 +443,8 @@ impl MmapPipelineLibrary { "D3D12.X: opened memory-mapped pipeline library gen-{gen:08x} ({:.1} MiB file-backed)", blob.len() as f64 / (1024.0 * 1024.0) ); - return Some(Self { - lib, - _backing: Some(blob), - store, - dirty: AtomicU64::new(0), - saving: AtomicBool::new(false), - save_lock: Mutex::new(()), - lib_lock: Mutex::new(()), - }); + read_lib = Some(lib); + backing = Some(Arc::new(blob)); } Err(e) => { let stale_path = blob.path().to_path_buf(); @@ -420,27 +469,36 @@ impl MmapPipelineLibrary { } } } - // Pass an explicit NULL pointer with length 0 rather than `&[]`, whose dangling - // non-null slice pointer vkd3d-proton rejects with E_INVALIDARG. - let mut lib: Option = None; - (Interface::vtable(&dev1).CreatePipelineLibrary)( - Interface::as_raw(&dev1), - std::ptr::null(), - 0, - &ID3D12PipelineLibrary1::IID, - &mut lib as *mut _ as *mut _, - ) - .ok() - .ok()?; - let lib = lib?; + + // Open a separate write-only `ID3D12PipelineLibrary1` from the same read-only `MappedBlob` + // (zero extra RAM) so `xcl-plib-save` exclusively owns `StorePipeline` + `Serialize`. + // If a valid `backing` exists and the 2nd handle fails to open, disable saving for this + // run rather than overwriting the valid `.plib` with an empty generation. + let write_lib = match &backing { + Some(blob) => dev1.CreatePipelineLibrary::(blob.as_slice()).ok(), + None => create_empty_library(&dev1), + }; + if read_lib.is_none() && write_lib.is_none() { + return None; + } + + let dirty = Arc::new(AtomicU64::new(0)); + let save_tx = write_lib.map(|wlib| { + let (tx, rx) = mpsc::channel::(); + let write_backing = backing.clone(); + let dirty_worker = dirty.clone(); + let send_lib = SendLib(wlib); + let _ = std::thread::Builder::new().name("xcl-plib-save".into()).spawn(move || { + run_save_worker(send_lib, write_backing, store, rx, dirty_worker); + }); + std::sync::Mutex::new(tx) + }); + Some(Self { - lib, - _backing: None, - store, - dirty: AtomicU64::new(0), - saving: AtomicBool::new(false), - save_lock: Mutex::new(()), - lib_lock: Mutex::new(()), + read_lib, + _read_backing: backing, + save_tx, + dirty, }) } @@ -448,95 +506,152 @@ impl MmapPipelineLibrary { if key.is_empty() || desc.pRootSignature.is_none() || desc.CS.pShaderBytecode.is_null() || desc.CS.BytecodeLength == 0 { return None; } + let lib = self.read_lib.as_ref()?; let name = HSTRING::from(key); - let _g = self.lib_lock.lock().unwrap(); - self.lib.LoadComputePipeline(&name, desc).ok() + lib.LoadComputePipeline(&name, desc).ok() } pub unsafe fn load_graphics(&self, key: &str, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option { if key.is_empty() || desc.pRootSignature.is_none() { return None; } + let lib = self.read_lib.as_ref()?; let name = HSTRING::from(key); - let _g = self.lib_lock.lock().unwrap(); - self.lib.LoadGraphicsPipeline(&name, desc).ok() + lib.LoadGraphicsPipeline(&name, desc).ok() } pub unsafe fn load_stream(&self, key: &str, desc: &D3D12_PIPELINE_STATE_STREAM_DESC) -> Option { if key.is_empty() || desc.pPipelineStateSubobjectStream.is_null() || desc.SizeInBytes == 0 { return None; } + let lib = self.read_lib.as_ref()?; let name = HSTRING::from(key); - let _g = self.lib_lock.lock().unwrap(); - self.lib.LoadPipeline(&name, desc).ok() + lib.LoadPipeline(&name, desc).ok() } + /// Enqueue `(key, pso)` for the dedicated `xcl-plib-save` worker thread. Returns immediately + /// (~1 µs) with zero driver lock contention on compile workers. pub unsafe fn store(&self, key: &str, pso: &ID3D12PipelineState) -> bool { if key.is_empty() { return false; } - let name = HSTRING::from(key); - let _g = self.lib_lock.lock().unwrap(); - if self.lib.StorePipeline(&name, pso).is_ok() { - self.dirty.fetch_add(1, Ordering::Relaxed); - true - } else { - false - } + let Some(tx) = self.save_tx.as_ref() else { return false }; + tx.lock().unwrap().send(SaveCmd::Store(key.to_string(), SendPso(pso.clone()))).is_ok() } pub fn dirty_count(&self) -> u64 { self.dirty.load(Ordering::Relaxed) } - /// Serialize under `save_lock` (already held by caller), taking `lib_lock` so no concurrent - /// `StorePipeline` or `Load*` can race `GetSerializedSize` + `Serialize`. - unsafe fn save_locked(&self, min_dirty: u64) -> Option { - let dirty_before = self.dirty.load(Ordering::Acquire); - if dirty_before < min_dirty { + /// Blocking shutdown flush (e.g. `WM_CLOSE` or `XCL_RUN_SECONDS`): asks `xcl-plib-save` to + /// drain any queued `StorePipeline` calls and write a fresh `.plib` generation (bounded by + /// `FLUSH_TIMEOUT` so shutdown can never hang). + pub unsafe fn flush(&self) -> Option { + let tx = self.save_tx.as_ref()?; + let (reply_tx, reply_rx) = mpsc::sync_channel(1); + if tx.lock().unwrap().send(SaveCmd::Flush(reply_tx)).is_err() { return None; } - let (size, saved) = { - let _g = self.lib_lock.lock().unwrap(); - let size = self.lib.GetSerializedSize(); - let saved = if size > 0 { - self.store.write_generation(size, |buf| self.lib.Serialize(buf).is_ok()) - } else { - None - }; - (size, saved) + reply_rx.recv_timeout(FLUSH_TIMEOUT).ok().flatten() + } +} + +fn run_save_worker( + write_lib: SendLib, + _backing: Option>, + store: LibraryStore, + rx: mpsc::Receiver, + dirty_counter: Arc, +) { + let lib = write_lib.0; + let epoch = Instant::now(); + let now_ms = || epoch.elapsed().as_millis() as u64; + let mut dirty: u64 = 0; + let mut last_store_ms: u64 = 0; + let mut last_save_ms: u64 = 0; + + let save_now = |dirty: &mut u64, last_save_ms: &mut u64| -> Option { + if *dirty == 0 { + return None; + } + let count = *dirty; + let size = unsafe { lib.GetSerializedSize() }; + let saved = if size > 0 { + store.write_generation(size, |buf| unsafe { lib.Serialize(buf) }.is_ok()) + } else { + None }; - if let Some((gen, _)) = saved { - self.dirty.fetch_sub(dirty_before.min(self.dirty.load(Ordering::Relaxed)), Ordering::Relaxed); + if let Some((gen, path)) = saved { + *dirty = 0; + dirty_counter.store(0, Ordering::Release); + *last_save_ms = now_ms(); crate::xlog_info!( "D3D12.X: saved pipeline library gen-{gen:08x} ({:.1} MiB, {} new pipelines)", size as f64 / (1024.0 * 1024.0), - dirty_before + count ); + Some(path) + } else { + None } - saved.map(|(_, p)| p) - } + }; - /// Non-blocking periodic save: skips if another save is already in progress. Never replaces or - /// truncates the open `_backing` file. - pub unsafe fn save_if_dirty(&self, min_dirty: u64) -> Option { - if self.dirty.load(Ordering::Relaxed) < min_dirty { - return None; + let apply_store = |key: String, pso: SendPso, dirty: &mut u64, last_store_ms: &mut u64| { + let name = HSTRING::from(key); + if unsafe { lib.StorePipeline(&name, &pso.0) }.is_ok() { + *dirty += 1; + dirty_counter.store(*dirty, Ordering::Release); + *last_store_ms = now_ms(); } - if self.saving.swap(true, Ordering::AcqRel) { - return None; + drop(pso); + }; + + loop { + match rx.recv_timeout(Duration::from_secs(2)) { + Ok(SaveCmd::Store(key, pso)) => { + apply_store(key, pso, &mut dirty, &mut last_store_ms); + // Drain any burst of queued stores before checking periodic save. + let mut pending_flush = None; + while let Ok(cmd) = rx.try_recv() { + match cmd { + SaveCmd::Store(k, p) => apply_store(k, p, &mut dirty, &mut last_store_ms), + SaveCmd::Flush(reply) => { + pending_flush = Some(reply); + break; + } + } + } + if let Some(reply) = pending_flush { + let saved = save_now(&mut dirty, &mut last_save_ms); + let _ = reply.send(saved); + } else if should_background_save(dirty, now_ms(), last_store_ms, last_save_ms) { + save_now(&mut dirty, &mut last_save_ms); + } + } + Ok(SaveCmd::Flush(reply)) => { + let mut extra_flushes = Vec::new(); + while let Ok(cmd) = rx.try_recv() { + match cmd { + SaveCmd::Store(k, p) => apply_store(k, p, &mut dirty, &mut last_store_ms), + SaveCmd::Flush(r) => extra_flushes.push(r), + } + } + let saved = save_now(&mut dirty, &mut last_save_ms); + let _ = reply.send(saved.clone()); + for r in extra_flushes { + let _ = r.send(saved.clone()); + } + } + Err(mpsc::RecvTimeoutError::Timeout) => { + if should_background_save(dirty, now_ms(), last_store_ms, last_save_ms) { + save_now(&mut dirty, &mut last_save_ms); + } + } + Err(mpsc::RecvTimeoutError::Disconnected) => { + let _ = save_now(&mut dirty, &mut last_save_ms); + break; + } } - let _guard = self.save_lock.lock().unwrap(); - let saved = self.save_locked(min_dirty); - self.saving.store(false, Ordering::Release); - saved - } - - /// Blocking shutdown flush (e.g. `WM_CLOSE` or `XCL_RUN_SECONDS`): waits for any in-flight - /// background save on `save_lock` to complete cleanly before flushing remaining dirty entries. - pub unsafe fn flush(&self) -> Option { - let _guard = self.save_lock.lock().unwrap(); - self.save_locked(1) } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 0a291d9122..43c88adb1e 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -10195,15 +10195,9 @@ pub fn flush_pipeline_library() { mod pso_lib { use super::*; use crate::hle::d3d12x::pso_library::MmapPipelineLibrary; + #[cfg(test)] + use crate::hle::d3d12x::pso_library::should_background_save; use std::sync::Arc; - use std::time::{Duration, Instant}; - - /// Minimum newly stored pipelines before triggering a periodic background generation save. - const SAVE_BATCH_THRESHOLD: u64 = 32; - /// Minimum spacing between periodic background saves while pipelines are streaming in. - const SAVE_MIN_INTERVAL: Duration = Duration::from_secs(15); - /// Idle delay after the last stored pipeline before flushing any remaining tail (`>= 1` dirty). - const SAVE_IDLE_FLUSH: Duration = Duration::from_secs(5); struct LibState { device: usize, @@ -10214,45 +10208,6 @@ mod pso_lib { } static LIB_STATE: Mutex> = Mutex::new(None); - static LAST_STORE_MS: AtomicU64 = AtomicU64::new(0); - static LAST_SAVE_MS: AtomicU64 = AtomicU64::new(0); - static SAVER_STARTED: std::sync::Once = std::sync::Once::new(); - static EPOCH: OnceLock = OnceLock::new(); - - fn now_ms() -> u64 { - EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 - } - - /// Pure save-scheduling decision (unit-testable on CPU): - /// - Save immediately when `dirty >= SAVE_BATCH_THRESHOLD` and at least `SAVE_MIN_INTERVAL` - /// elapsed since the last save. - /// - Or save any tail (`dirty > 0`) once no new pipeline has been stored for `SAVE_IDLE_FLUSH`. - pub(super) fn should_background_save(dirty: u64, now_ms: u64, last_store_ms: u64, last_save_ms: u64) -> bool { - if dirty == 0 { - return false; - } - let since_save = now_ms.saturating_sub(last_save_ms); - let since_store = now_ms.saturating_sub(last_store_ms); - (dirty >= SAVE_BATCH_THRESHOLD && since_save >= SAVE_MIN_INTERVAL.as_millis() as u64) - || (last_store_ms > 0 && since_store >= SAVE_IDLE_FLUSH.as_millis() as u64 && since_save >= SAVE_IDLE_FLUSH.as_millis() as u64) - } - - fn ensure_saver_thread() { - SAVER_STARTED.call_once(|| { - let _ = std::thread::Builder::new().name("xcl-plib-save".into()).spawn(|| loop { - std::thread::sleep(Duration::from_secs(2)); - let lib = LIB_STATE.lock().unwrap().as_ref().and_then(|s| s.lib.clone()); - let Some(lib) = lib else { continue }; - let now = now_ms(); - let dirty = lib.dirty_count(); - if should_background_save(dirty, now, LAST_STORE_MS.load(Ordering::Acquire), LAST_SAVE_MS.load(Ordering::Acquire)) { - if unsafe { lib.save_if_dirty(1) }.is_some() { - LAST_SAVE_MS.store(now_ms(), Ordering::Release); - } - } - }); - }); - } unsafe fn library_for(device: *mut c_void) -> Option> { if cfg!(test) || device.is_null() || !super::super::pso_library::enabled() { @@ -10284,17 +10239,14 @@ mod pso_lib { hits: 0, stores: 0, }); - if ret.is_some() { - ensure_saver_thread(); - } ret } pub(super) fn flush_now() { let lib = LIB_STATE.lock().unwrap().as_ref().and_then(|s| s.lib.clone()); if let Some(lib) = lib { - if unsafe { lib.flush() }.is_some() { - LAST_SAVE_MS.store(now_ms(), Ordering::Release); + unsafe { + let _ = lib.flush(); } } } @@ -10655,7 +10607,6 @@ mod pso_lib { } let Some(pso) = ID3D12PipelineState::from_raw_borrowed(&pso_raw) else { return }; if lib.store(key, pso) { - LAST_STORE_MS.store(now_ms(), Ordering::Release); if let Some(s) = LIB_STATE.lock().unwrap().as_mut() { s.stores += 1; } From 69060d88ba66ea670ec88f43de0858a985753e94 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:52:16 +0100 Subject: [PATCH 130/258] D3D12.X: read back 256x256 float ocean heightmap textures to console memory On Xbox Series X, GPU-simulated 256x256 R32_FLOAT / R32G32_FLOAT ocean height and displacement textures placed in unified memory can be copied into a CPU-readable placed texture and sampled by CPU boat physics. On PC D3D12, placed textures live in private DEFAULT VRAM so CopyResource and CopyTextureRegion leave the console UMA bytes untouched (zeros). Add asynchronous, non-stalling GPU-to-UMA readback for placed 256x256 single-mip 2D R32_FLOAT and R32G32_FLOAT textures (opt-out XCL_WATER_READBACK=0): - Track matching placed textures ( a, ormat, Arc) on device_x::create_placed_resource_x, clearing stale entries on COM address reuse. - On list_x::copy_resource_x and full-subresource copy_texture_region_x (guarded by an AtomicBool fast path, skipping bundles), transition COPY_DEST -> COPY_SOURCE -> CopyTextureRegion -> COPY_DEST into a pooled persistently-mapped READBACK buffer (MAX_POOLED_WATER_RB = 16, recycled on drop) and enqueue cpu_writes::Write::ReadbackTexture. - Once the queue fence completes on xcl-cpu-writes, verify the full destination span is committed and writable, and tile the linear rows back into console memory (mirror_source(va) + plane.offset) using XCL's exact gpu::tiling::Chain::tile_level encoder. - Add unit tests verifying candidate descriptor filtering and bit-exact 256x256 R32_FLOAT / R32G32_FLOAT 64KB swizzle round-trip. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 279 +++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/device_x.rs | 19 +- crates/xcl/src/hle/d3d12x/list_x.rs | 72 +++++- 3 files changed, 364 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index b236e27877..1d71da1657 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -10,14 +10,149 @@ use std::collections::HashMap; use std::ffi::c_void; -use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; -use std::sync::{mpsc, Mutex, OnceLock}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::{mpsc, Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32_FLOAT}; use windows_sys::Win32::System::Threading as th; +use crate::hle::xg; + +/// `XCL_WATER_READBACK=0`: disable GPU->UMA readback of 256×256 `R32_FLOAT` / `R32G32_FLOAT` +/// placed ocean height/displacement textures. +pub(super) fn water_readback_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_WATER_READBACK").map_or(true, |v| v.trim() != "0")) +} + +/// Whether `desc` is a 256×256 single-mip 2D `R32_FLOAT` or `R32G32_FLOAT` texture (ocean +/// heightmap / displacement readback target used by CPU boat/water physics). +pub(super) fn is_water_readback_desc(desc: &D3D12_RESOURCE_DESC) -> bool { + desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && desc.Width == 256 + && desc.Height == 256 + && desc.DepthOrArraySize == 1 + && desc.MipLevels == 1 + && desc.SampleDesc.Count <= 1 + && matches!(desc.Format, DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_R32G32_FLOAT) +} + +#[derive(Clone)] +pub(super) struct WaterTarget { + pub va: usize, + pub format: DXGI_FORMAT, + pub row_pitch: u32, + pub tex: Arc, +} + +static WATER_TARGETS: Mutex>> = Mutex::new(None); +static HAS_WATER_TARGETS: AtomicBool = AtomicBool::new(false); + +pub(super) fn has_water_readback() -> bool { + HAS_WATER_TARGETS.load(Ordering::Acquire) +} + +pub(super) fn register_water_readback(res: usize, va: usize, format: DXGI_FORMAT, tex: Arc) { + if !water_readback_enabled() || res == 0 || va == 0 { + return; + } + let row_pitch = match format { + DXGI_FORMAT_R32_FLOAT => 256 * 4, + DXGI_FORMAT_R32G32_FLOAT => 256 * 8, + _ => return, + }; + WATER_TARGETS.lock().unwrap().get_or_insert_with(HashMap::new).insert( + res, + WaterTarget { va, format, row_pitch, tex }, + ); + HAS_WATER_TARGETS.store(true, Ordering::Release); +} + +pub(super) fn unregister_water_readback(res: usize) { + if !HAS_WATER_TARGETS.load(Ordering::Acquire) { + return; + } + let mut g = WATER_TARGETS.lock().unwrap(); + if let Some(m) = g.as_mut() { + m.remove(&res); + if m.is_empty() { + HAS_WATER_TARGETS.store(false, Ordering::Release); + } + } +} + +pub(super) fn water_readback_target(res: usize) -> Option { + if !water_readback_enabled() || !HAS_WATER_TARGETS.load(Ordering::Acquire) { + return None; + } + WATER_TARGETS.lock().unwrap().as_ref()?.get(&res).cloned() +} + +/// Pooled persistently-mapped `READBACK` buffer returned to `FREE_WATER_RB` on drop once +/// `xcl-cpu-writes` finishes swizzling the heightmap into console memory. +pub(super) struct WaterReadbackBuf { + pub buf: Option, + pub mapped: usize, + pub bytes: u64, + pub dev_key: usize, +} + +unsafe impl Send for WaterReadbackBuf {} +unsafe impl Sync for WaterReadbackBuf {} + +const MAX_POOLED_WATER_RB: usize = 16; +static FREE_WATER_RB: Mutex> = Mutex::new(Vec::new()); + +impl Drop for WaterReadbackBuf { + fn drop(&mut self) { + let Some(buf) = self.buf.take() else { return }; + let mapped = std::mem::replace(&mut self.mapped, 0); + let mut free = FREE_WATER_RB.lock().unwrap(); + if free.len() < MAX_POOLED_WATER_RB && mapped != 0 { + free.push((buf, mapped, self.bytes, self.dev_key)); + } else if mapped != 0 { + unsafe { buf.Unmap(0, None) }; + } + } +} + +/// Acquire a persistently-mapped `READBACK` buffer of at least `bytes` bytes for `dev`. +pub(super) unsafe fn take_water_readback_buf(dev: &ID3D12Device, bytes: u64) -> Option> { + let dev_key = dev.as_raw() as usize; + { + let mut free = FREE_WATER_RB.lock().unwrap(); + if let Some(i) = free.iter().position(|(_, _, cap, d)| *d == dev_key && *cap >= bytes) { + let (buf, mapped, cap, d) = free.swap_remove(i); + return Some(Arc::new(WaterReadbackBuf { buf: Some(buf), mapped, bytes: cap, dev_key: d })); + } + } + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let mut rb: Option = None; + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb).ok()?; + let rb = rb?; + let _ = rb.SetName(windows::core::w!("xcl water heightmap readback")); + let mut mapped = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut mapped)).ok()?; + if mapped.is_null() { + return None; + } + Some(Arc::new(WaterReadbackBuf { buf: Some(rb), mapped: mapped as usize, bytes, dev_key })) +} + /// A bottom-of-pipe write into memory outside unified memory, applied by the CPU once the /// queue's fence reaches the submission that recorded it. #[derive(Clone)] @@ -28,6 +163,10 @@ pub(super) enum Write { /// (`src`), copied atomically to `va` once the queue's fence completes. Holding `_buf` keeps /// the mapping alive until the worker finishes. ReadbackU64 { va: usize, src: usize, _buf: ID3D12Resource }, + /// A 256×256 `R32_FLOAT` / `R32G32_FLOAT` ocean height/displacement texture read back from + /// VRAM into a persistently mapped READBACK buffer, tiled back into console memory `dst_va` + /// with `tex.chain.tile_level` once the queue's fence completes. + ReadbackTexture { dst_va: usize, format: DXGI_FORMAT, row_pitch: u32, tex: Arc, buf: Arc }, } struct Job { @@ -77,6 +216,9 @@ fn worker() -> &'static Mutex> { let value = (*(*src as *const AtomicU64)).load(Ordering::Acquire); write_u64_now(*va, value); } + Write::ReadbackTexture { dst_va, format, row_pitch, tex, buf } => { + write_texture_now(*dst_va, *format, *row_pitch, tex, buf); + } } } } @@ -141,6 +283,97 @@ pub(super) unsafe fn max_u64_now(va: usize, value: u64) { } } +/// Whether the entire byte span `[va, va + bytes)` is committed, writable, and without `PAGE_GUARD`. +unsafe fn range_writable_now(va: usize, bytes: usize) -> bool { + if va == 0 || bytes == 0 { + return false; + } + let Some(end) = va.checked_add(bytes) else { return false }; + if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { + return true; + } + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_READWRITE}; + let mut cur = va; + while cur < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(cur as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.State != MEM_COMMIT { + return false; + } + if m.Protect & PAGE_GUARD != 0 || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 { + return false; + } + let region_end = (m.BaseAddress as usize).saturating_add(m.RegionSize); + if region_end <= cur { + return false; + } + cur = region_end; + } + true +} + +fn main_surface(tex: &xg::Texture) -> Option<(usize, &xg::Surface)> { + let plane = tex.planes.get(tex.main)?; + let xg::PlaneKind::Surface(ref s) = plane.kind else { return None }; + Some((plane.offset as usize, s)) +} + +/// Swizzle `linear` rows (`row_pitch` bytes per row, 256 rows) into Xbox console tiled layout +/// inside `dst` using the main plane's `Surface::chain.tile_level`. +fn tile_readback_into_slice(dst: &mut [u8], linear: &[u8], row_pitch: u32, tex: &xg::Texture) -> bool { + let Some((_, surface)) = main_surface(tex) else { return false }; + let Some(l0) = surface.chain.levels.first() else { return false }; + let bpe = surface.bpe as usize; + let packed_row = l0.width.saturating_mul(bpe); + let pitch = row_pitch as usize; + let slice_bytes = surface.chain.slice_bytes; + if packed_row == 0 || pitch < packed_row || slice_bytes == 0 || dst.len() < slice_bytes { + return false; + } + let Some(src_need) = pitch.checked_mul(l0.height) else { return false }; + if linear.len() < src_need { + return false; + } + if pitch == packed_row { + surface.chain.tile_level(&mut dst[..slice_bytes], 0, 0, &linear[..src_need]); + } else { + let mut packed = Vec::with_capacity(packed_row * l0.height); + for row in 0..l0.height { + let start = row * pitch; + packed.extend_from_slice(&linear[start..start + packed_row]); + } + surface.chain.tile_level(&mut dst[..slice_bytes], 0, 0, &packed); + } + true +} + +/// Write a completed GPU readback of a 256×256 ocean height/displacement texture back into +/// console memory in its Xbox XOR-swizzled layout. +unsafe fn write_texture_now(dst_va: usize, format: DXGI_FORMAT, row_pitch: u32, tex: &xg::Texture, buf: &WaterReadbackBuf) { + if buf.mapped == 0 { + return; + } + let Some((plane_off, surface)) = main_surface(tex) else { return }; + let Some(target_va) = super::title_textures::mirror_source(dst_va).checked_add(plane_off) else { return }; + let dst_bytes = surface.chain.slice_bytes; + if dst_bytes == 0 { + return; + } + let _open = crate::hle::kernelx::lazy::ensure(target_va, dst_bytes); + if !range_writable_now(target_va, dst_bytes) { + return; + } + let linear = std::slice::from_raw_parts(buf.mapped as *const u8, buf.bytes as usize); + let dst = std::slice::from_raw_parts_mut(target_va as *mut u8, dst_bytes); + if tile_readback_into_slice(dst, linear, row_pitch, tex) { + std::sync::atomic::fence(Ordering::Release); + static COUNT: AtomicU64 = AtomicU64::new(0); + let n = COUNT.fetch_add(1, Ordering::Relaxed) + 1; + if n == 1 || (n.is_power_of_two() && n >= 64) { + crate::xlog_info!("D3D12.X: water heightmap readback #{n} (256x256 fmt {}, -> {target_va:#x}, {dst_bytes} B)", format.0); + } + } +} + /// Whether `[va, va + bytes)` is memory the CPU can write for the GPU later. pub(super) fn writable(va: usize, bytes: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { @@ -272,4 +505,46 @@ mod tests { assert_eq!(*dst, expected); } } + + #[test] + fn water_readback_desc_matches_256_float_heightmaps_only() { + let base = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_FLOAT, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + assert!(is_water_readback_desc(&base)); + assert!(is_water_readback_desc(&D3D12_RESOURCE_DESC { Format: DXGI_FORMAT_R32G32_FLOAT, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 512, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { MipLevels: 2, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { DepthOrArraySize: 2, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, ..base })); + } + + #[test] + fn tile_readback_roundtrips_256_r32_and_r32g32_heightmaps() { + for (fmt, bpe) in [(DXGI_FORMAT_R32_FLOAT.0 as u32, 4usize), (DXGI_FORMAT_R32G32_FLOAT.0 as u32, 8usize)] { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&(D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 as u32).to_le_bytes()); + x[0x10..0x18].copy_from_slice(&256u64.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&256u32.to_le_bytes()); + x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); + x[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + x[0x2C..0x30].copy_from_slice(&0x11Bu32.to_le_bytes()); // console swizzle 64KB_R_X (0x100 | 27) + let tex = xg::Texture::new(&x).expect("256x256 console texture layout"); + let (_, surface) = main_surface(&tex).expect("main color surface"); + let linear: Vec = (0..(256 * 256 * bpe)).map(|i| ((i * 31 + 17) & 0xFF) as u8).collect(); + let mut tiled = vec![0u8; surface.chain.slice_bytes]; + assert!(tile_readback_into_slice(&mut tiled, &linear, (256 * bpe) as u32, &tex)); + assert_eq!(surface.chain.detile_level(&tiled, 0, 0), linear); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index b10da3e1da..a548f13dfd 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1128,11 +1128,18 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); let mut placed_hr = None; let mut pc_tex_desc: Option = None; + let mut water_tex: Option<(windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, crate::hle::xg::Texture)> = None; if !buffer { let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); pc_tex_desc = Some(pc); let timer = place_times::step(Step::Desc); - let console_bytes = crate::hle::xg::Texture::new(&x).ok().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); + let xg_tex = crate::hle::xg::Texture::new(&x).ok(); + let console_bytes = xg_tex.as_ref().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); + if console_bytes.is_some() && super::cpu_writes::is_water_readback_desc(&pc) { + if let Some(t) = xg_tex { + water_tex = Some((pc.Format, t)); + } + } drop(timer); if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { @@ -1143,6 +1150,11 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, real::note_title_address(*ppv as usize, va as usize); super::depth_uav::register_if_depth_uav(this, *ppv, &x, state, console_state); super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); + if let Some((fmt, t)) = water_tex { + super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, std::sync::Arc::new(t)); + } else if super::cpu_writes::has_water_readback() { + super::cpu_writes::unregister_water_readback(*ppv as usize); + } } return hr; } @@ -1158,6 +1170,11 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } }; if hr >= 0 && !buffer && !(*ppv).is_null() { + if let Some((fmt, t)) = water_tex { + super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, std::sync::Arc::new(t)); + } else if super::cpu_writes::has_water_readback() { + super::cpu_writes::unregister_water_readback(*ppv as usize); + } super::depth_uav::register_if_depth_uav(this, *ppv, &x, state, console_state); let aliased_to_gpu = pc_tex_desc.as_ref().is_some_and(|pc| { super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, pc, flags, state) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index a7e18f1698..7d8820f2fc 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4889,9 +4889,23 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds } } let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return }; + let water_dst = if d.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX + && d.Anonymous.SubresourceIndex == 0 + && x == 0 + && y == 0 + && z == 0 + && bx.is_null() + { + transmute_copy::<_, usize>(&d.pResource) + } else { + 0 + }; if !super::format_alias::try_copy_texture_region(this, &d, x, y, z, &s, bx) { pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); } + if water_dst != 0 { + maybe_enqueue_water_readback(this, water_dst); + } std::mem::forget((d, s)); // borrowed resource pointers } @@ -5023,6 +5037,57 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v pc::(this, PC_RESOLVE_SUBRESOURCE_REGION)(this, dst, dst_sub, x, y, src, src_sub, rect, format, mode) } +/// If `dst` is a tracked 256×256 `R32_FLOAT` / `R32G32_FLOAT` placed ocean height/displacement +/// texture, copy subresource 0 into a pooled `READBACK` buffer and queue asynchronous XOR-swizzled +/// writeback into console memory on `xcl-cpu-writes` after this submission's GPU fence completes. +unsafe fn maybe_enqueue_water_readback(this: *mut c_void, dst: usize) { + let Some(target) = super::cpu_writes::water_readback_target(dst) else { return }; + if list_type(this) == D3D12_COMMAND_LIST_TYPE_BUNDLE { + return; + } + let Some(dev) = device_of(this) else { return }; + let total_bytes = u64::from(target.row_pitch) * 256; + let Some(rb) = super::cpu_writes::take_water_readback_buf(&dev, total_bytes) else { return }; + let Some(rb_res) = rb.buf.as_ref() else { return }; + let src_loc = D3D12_TEXTURE_COPY_LOCATION { + pResource: transmute_copy(&dst), + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 }, + }; + let dst_loc = D3D12_TEXTURE_COPY_LOCATION { + pResource: transmute_copy(&rb_res.as_raw()), + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: target.format, + Width: 256, + Height: 256, + Depth: 1, + RowPitch: target.row_pitch, + }, + }, + }, + }; + transition(this, dst, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + pc::( + this, + PC_COPY_TEXTURE_REGION, + )(this, &dst_loc, 0, 0, 0, &src_loc, std::ptr::null()); + transition(this, dst, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + std::mem::forget((src_loc, dst_loc)); // borrowed resource pointers + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); + s.cpu_writes.push(super::cpu_writes::Write::ReadbackTexture { + dst_va: target.va, + format: target.format, + row_pitch: target.row_pitch, + tex: target.tex, + buf: rb, + }); +} + /// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address /// are copied as their own bytes (the PC resources also hold what lies before them) pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { @@ -5033,10 +5098,11 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi } let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src)); if dd == 0 && sd == 0 { - if super::format_alias::try_copy_resource(this, dst, src) { - return; + if !super::format_alias::try_copy_resource(this, dst, src) { + pc::(this, PC_COPY_RESOURCE)(this, dst, src); } - return pc::(this, PC_COPY_RESOURCE)(this, dst, src); + maybe_enqueue_water_readback(this, dst); + return; } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); copy_buffer_region_x(this, dst, 0, src, 0, n); From 4dfade69f3318e7e84017757249604f6e78a9a76 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:48:07 +0100 Subject: [PATCH 131/258] Shaders: warm memory-mapped ID3D12PipelineLibrary1 (.plib) in offline --precompile --pipelines Previously xcl shaders --precompile --pipelines --used-only only wrote GetCachedBlob() .pso files into dxil-cache/driver/, which on AMD RDNA4 are <= 1 KiB stub headers containing no compiled GPU ISA. Wire MmapPipelineLibrary into offline Pipelines::new / make_one / flush using the exact adapter string format of real::init() and shared real::compute_library_key (c-... for standard compute, sc-... for dispatch_chain split pieces) so offline prebuilds populate and reuse the exact same gen-*.plib directory as runtime execution (isolated under cfg!(test)). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 13 ++++++ crates/xcl/src/shaders.rs | 67 ++++++++++++++++++++++++++++++- 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 43c88adb1e..09bafc1cb9 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -10189,6 +10189,19 @@ pub fn flush_pipeline_library() { pso_lib::flush_now(); } +/// Deterministic cross-run `.plib` key for a translated compute pipeline (`c-...` for standard +/// 6-parameter ABI root signatures, `sc-...` for 8-parameter `dispatch_chain` root signatures), +/// shared between runtime PSO creation and offline `xcl shaders --precompile --pipelines`. +pub(crate) fn compute_library_key( + dxil: &[u8], + samplers: &[crate::gpu::recomp::pso::StaticSampler], + flags: i32, + chained: bool, +) -> String { + let key = pso_lib::compute_key(dxil, samplers, flags); + if chained { format!("s{key}") } else { key } +} + /// Runtime wiring for `pso_library::MmapPipelineLibrary`: deterministic cross-run pipeline keys, /// kept-open per-device library lookup, load/store helpers, and debounced background generational /// persistence (zero heap copy, never replaces an actively mapped `.plib`). diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0cd2ed7b3a..3bd1d90666 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1204,10 +1204,13 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl /// (the > 8 MB HLSL programs DXC compiles at `-O0`, #1269). struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, + library: Option, signatures: Mutex), windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, + lib_reused: AtomicUsize, + lib_stored: AtomicUsize, split_programs: AtomicUsize, split_pieces: AtomicUsize, /// programs over `max_dxil` with no blob yet, and their DXIL bytes @@ -1243,6 +1246,17 @@ mod pipeline_cap_tests { assert_eq!(pipeline_cap_kb(Some("off")), 8192); } + #[test] + fn offline_pipeline_library_key_matches_runtime_standard_and_split_keys() { + let dxil = b"DXBC-offline-precompile-test"; + let samplers = [([1u32, 2, 3, 4], false)]; + let std_key = crate::hle::d3d12x::real::compute_library_key(dxil, &samplers, 0, false); + let split_key = crate::hle::d3d12x::real::compute_library_key(dxil, &samplers, 0, true); + assert!(std_key.starts_with("c-")); + assert_eq!(split_key, format!("s{std_key}")); + assert_ne!(std_key, split_key); + } + #[test] fn stale_blob_cannot_bypass_the_offline_pipeline_cap() { use super::{Pipelines, recomp, Ordering}; @@ -1417,16 +1431,25 @@ impl Pipelines { unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; let sel = crate::gpu::adapter::Selector::from_env_or("auto"); - let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; + // Match `real::init`'s adapter string verbatim so offline `--precompile --pipelines` + // opens and populates the exact same `pso-library//gen-*.plib` directory. + let adapter_name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); + let library = (!cfg!(test)) + .then(|| crate::hle::d3d12x::pso_library::MmapPipelineLibrary::open_or_create(&dev, &adapter_name)) + .flatten(); let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); Ok(Pipelines { dev, + library, signatures: Mutex::new(Default::default()), made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), + lib_reused: AtomicUsize::new(0), + lib_stored: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), capped: AtomicUsize::new(0), @@ -1507,6 +1530,22 @@ impl Pipelines { CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr() as *const _, BytecodeLength: dxil.len() }, ..Default::default() }; + let lib_key = crate::hle::d3d12x::real::compute_library_key(dxil, samplers, desc.Flags.0, chained); + let has_override = path_override.is_some(); + if !has_override { + if let Some(lib) = self.library.as_ref() { + if unsafe { lib.load_compute(&lib_key, &desc) }.is_some() { + self.lib_reused.fetch_add(1, Ordering::Relaxed); + self.reused.fetch_add(1, Ordering::Relaxed); + let done = self.made.fetch_add(1, Ordering::Relaxed) + 1; + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + if done % 25 == 0 { + eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); + } + return; + } + } + } use crate::hle::d3d12x::real::driver_cache; let path = path_override.or_else(|| { #[cfg(test)] @@ -1575,13 +1614,26 @@ impl Pipelines { self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); let done = match r { - Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, + Ok(pso) => { + if !has_override { + if let Some(lib) = self.library.as_ref() { + if unsafe { lib.store(&lib_key, &pso) } { + self.lib_stored.fetch_add(1, Ordering::Relaxed); + } + } + } + self.made.fetch_add(1, Ordering::Relaxed) + 1 + } Err(_) => self.refused.fetch_add(1, Ordering::Relaxed) + 1, }; if done % 25 == 0 { eprintln!(" pipelines: {} made, {} refused", self.made.load(Ordering::Relaxed), self.refused.load(Ordering::Relaxed)); } } + + fn flush(&self) -> Option { + unsafe { self.library.as_ref()?.flush() } + } } /// A compute program a title used in an earlier run (`--used-only`): its pipeline's key, as the @@ -1726,8 +1778,19 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on println!("compute programs passed over (no earlier run used their pipeline): {}", unused.into_inner()); } if let Some(p) = pipelines { + let saved_plib = p.flush(); println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); + let lib_reused = p.lib_reused.load(Ordering::Relaxed); + let lib_stored = p.lib_stored.load(Ordering::Relaxed); + if lib_reused != 0 || lib_stored != 0 || saved_plib.is_some() { + println!( + "pipeline library (.plib): {} loaded, {} stored{}", + lib_reused, + lib_stored, + saved_plib.as_ref().map_or_else(String::new, |path| format!(" -> {}", path.display())) + ); + } let split_programs = p.split_programs.load(Ordering::Relaxed); if split_programs != 0 { println!("split compute programs: {} ({} pieces)", split_programs, p.split_pieces.load(Ordering::Relaxed)); From 44960c48810e93fd6518476b80e1adb679287fe8 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:48:02 +0100 Subject: [PATCH 132/258] D3D12.X: pool <=8 MiB upload staging buffers and reclaim idle staging Add a per-device power-of-2 upload staging buffer pool (<= 8 MiB per entry, 256 MiB total cap via XCL_STAGING_POOL_MB, 0 disables) in gpu::texture and wire periodic idle reclamation into present_x_frame. Uploader::staging reuses pooled buffers on miss/growth, returns replaced <= 8 MiB buffers to the pool after copy fence completion, and releases idle staging buffers untouched for >= 2 s and >= 30 frames (or > 4 MiB immediately when Windows commit is below the vram reserve floor). Includes pure-Rust unit tests covering bucketing, cap eviction, reuse, and idle reclaim. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/texture.rs | 285 ++++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/present.rs | 1 + 2 files changed, 279 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index cde3561492..34fcf6989a 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -207,12 +207,15 @@ pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D1 /// retail game most of its frame once it streamed textures: each of those D3D12 calls waits for /// the video memory manager, 200 – 650 ms apiece then. struct Uploader { + dev_key: usize, alloc: ID3D12CommandAllocator, list: ID3D12GraphicsCommandList, fence: ID3D12Fence, value: u64, /// (buffer, its mapped bytes, capacity) staging: Option<(ID3D12Resource, *mut u8, u64)>, + last_used_ms: u64, + last_used_frame: u64, } // D3D12 objects are free-threaded; the mapped pointer is only used by the holder of the uploader @@ -225,6 +228,149 @@ static UPLOADERS: std::sync::Mutex u64 { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 +} + +fn staging_pool_cap_bytes() -> u64 { + static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *CAP.get_or_init(|| { + std::env::var("XCL_STAGING_POOL_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(STAGING_POOL_DEFAULT_CAP, |mb| mb.saturating_mul(1 << 20)) + }) +} + +/// Power-of-2 bucket size for the shared upload staging pool (`<= 8 MiB`), or `None` if oversized. +fn staging_pool_bucket(bytes: u64) -> Option { + let cap = bytes.max(64 << 10).checked_next_power_of_two()?; + (cap <= STAGING_POOL_MAX_ITEM).then_some(cap) +} + +struct PooledStaging { + item: T, + last_ms: u64, + last_frame: u64, +} + +/// Power-of-2 upload staging buffer pool (`<= 8 MiB` per entry, bounded total capacity) with +/// idle reclamation after `STAGING_IDLE_MS` and `STAGING_IDLE_FRAMES`. +struct StagingPool { + buckets: std::collections::BTreeMap>>, + total_bytes: u64, + cap_bytes: u64, +} + +impl StagingPool { + fn new(cap_bytes: u64) -> Self { + Self { + buckets: std::collections::BTreeMap::new(), + total_bytes: 0, + cap_bytes, + } + } + + fn acquire(&mut self, bytes: u64) -> Option<(u64, T)> { + let bucket = staging_pool_bucket(bytes)?; + let list = self.buckets.get_mut(&bucket)?; + let entry = list.pop()?; + if list.is_empty() { + self.buckets.remove(&bucket); + } + self.total_bytes = self.total_bytes.saturating_sub(bucket); + Some((bucket, entry.item)) + } + + /// Return a GPU-idle power-of-2 buffer to the pool, or hand it back to the caller to drop if + /// pooling is disabled or the buffer exceeds `STAGING_POOL_MAX_ITEM` / `cap_bytes`. + fn release(&mut self, cap: u64, item: T, now_ms: u64, frame: u64) -> Option { + if self.cap_bytes == 0 || cap == 0 || !cap.is_power_of_two() || cap > STAGING_POOL_MAX_ITEM || cap > self.cap_bytes { + return Some(item); + } + while self.total_bytes.saturating_add(cap) > self.cap_bytes { + if !self.evict_oldest() { + return Some(item); + } + } + self.buckets.entry(cap).or_default().push(PooledStaging { item, last_ms: now_ms, last_frame: frame }); + self.total_bytes = self.total_bytes.saturating_add(cap); + None + } + + fn evict_oldest(&mut self) -> bool { + let mut victim: Option<(u64, usize, u64)> = None; + for (&cap, list) in &self.buckets { + for (idx, e) in list.iter().enumerate() { + if victim.is_none_or(|(_, _, ts)| e.last_ms < ts) { + victim = Some((cap, idx, e.last_ms)); + } + } + } + let Some((cap, idx, _)) = victim else { return false }; + if let Some(list) = self.buckets.get_mut(&cap) { + list.remove(idx); + if list.is_empty() { + self.buckets.remove(&cap); + } + self.total_bytes = self.total_bytes.saturating_sub(cap); + return true; + } + false + } + + fn trim_idle(&mut self, now_ms: u64, frame: u64, force_all: bool) -> (usize, u64) { + let mut freed_count = 0usize; + let mut freed_bytes = 0u64; + let mut empty_buckets = Vec::new(); + for (&cap, list) in &mut self.buckets { + let before = list.len(); + if force_all { + list.clear(); + } else { + list.retain(|e| { + let ms_idle = now_ms.saturating_sub(e.last_ms) >= STAGING_IDLE_MS; + let fr_idle = frame.saturating_sub(e.last_frame) >= STAGING_IDLE_FRAMES; + !(ms_idle && fr_idle) + }); + } + let dropped = before - list.len(); + if dropped > 0 { + freed_count += dropped; + let bytes = cap.saturating_mul(dropped as u64); + freed_bytes = freed_bytes.saturating_add(bytes); + self.total_bytes = self.total_bytes.saturating_sub(bytes); + } + if list.is_empty() { + empty_buckets.push(cap); + } + } + for cap in empty_buckets { + self.buckets.remove(&cap); + } + (freed_count, freed_bytes) + } +} + +struct MappedStaging(ID3D12Resource, *mut u8); + +// D3D12 resources are free-threaded; mapped pointer is owned exclusively while pooled or held. +unsafe impl Send for MappedStaging {} + +static STAGING_POOLS: std::sync::Mutex>>> = std::sync::Mutex::new(None); + fn staging_capacity(bytes: u64) -> Option { const LARGE: u64 = 64 << 20; const STEP: u64 = 16 << 20; @@ -241,20 +387,53 @@ impl Uploader { let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; list.Close().map_err(err)?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(err)?; - Ok(Uploader { alloc, list, fence, value: 0, staging: None }) + Ok(Uploader { + dev_key: windows::core::Interface::as_raw(dev) as usize, + alloc, + list, + fence, + value: 0, + staging: None, + last_used_ms: monotonic_ms(), + last_used_frame: CURRENT_FRAME.load(std::sync::atomic::Ordering::Relaxed), + }) } - /// An upload buffer of at least `bytes`, mapped: the one kept, or a bigger one. - unsafe fn staging(&mut self, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, *mut u8), String> { + /// An upload buffer of at least `bytes`, mapped: the one kept, a pooled power-of-2 buffer, + /// or a freshly allocated one. + unsafe fn staging(&mut self, dev: &ID3D12Device, bytes: u64, now_ms: u64, frame: u64) -> Result<(ID3D12Resource, *mut u8), String> { + self.last_used_ms = now_ms; + self.last_used_frame = frame; if let Some((b, p, cap)) = &self.staging { if *cap >= bytes { return Ok((b.clone(), *p)); } } let cap = staging_capacity(bytes).ok_or("texture upload buffer size overflow")?; - // A cached uploader has passed its last copy fence. Return this reference before - // acquiring the replacement so the growth path does not keep two buffers itself. - drop(self.staging.take()); + // A cached uploader has passed its last copy fence. Return its old `<= 8 MiB` buffer to + // the shared power-of-2 pool (or drop an oversized one) before acquiring the replacement + // so the growth path does not keep two oversized buffers alive simultaneously. + if let Some((old_b, old_p, old_cap)) = self.staging.take() { + if old_cap <= STAGING_POOL_MAX_ITEM && staging_pool_cap_bytes() > 0 { + let mut pools = STAGING_POOLS.lock().unwrap(); + let pool = pools + .get_or_insert_with(Default::default) + .entry(self.dev_key) + .or_insert_with(|| StagingPool::new(staging_pool_cap_bytes())); + let _ = pool.release(old_cap, MappedStaging(old_b, old_p), now_ms, frame); + } + } + if cap <= STAGING_POOL_MAX_ITEM && staging_pool_cap_bytes() > 0 { + let mut pools = STAGING_POOLS.lock().unwrap(); + if let Some((pooled_cap, MappedStaging(b, p))) = pools + .as_mut() + .and_then(|m| m.get_mut(&self.dev_key)) + .and_then(|pool| pool.acquire(cap)) + { + self.staging = Some((b.clone(), p, pooled_cap)); + return Ok((b, p)); + } + } let b = buffer(dev, cap)?; let mut p = std::ptr::null_mut(); b.Map(0, None, Some(&mut p)).map_err(err)?; @@ -263,6 +442,56 @@ impl Uploader { } } +/// Reclaim idle upload staging buffers (unused for `>= 2 s` and `>= 30` frames, or immediately +/// under low Windows commit headroom) to prevent post-streaming upload buffers from pinning +/// commit memory indefinitely. +pub fn trim_idle_staging(frame: u64, low_commit: bool) { + CURRENT_FRAME.store(frame, std::sync::atomic::Ordering::Relaxed); + if !low_commit && !frame.is_multiple_of(15) { + return; + } + let now_ms = monotonic_ms(); + let mut freed_bytes = 0u64; + let mut freed_count = 0usize; + { + let mut pools = STAGING_POOLS.lock().unwrap(); + if let Some(map) = pools.as_mut() { + for pool in map.values_mut() { + let (n, b) = pool.trim_idle(now_ms, frame, low_commit); + freed_count += n; + freed_bytes = freed_bytes.saturating_add(b); + } + } + } + { + let mut ups = UPLOADERS.lock().unwrap(); + if let Some(map) = ups.as_mut() { + for up in map.values_mut() { + let Some((_, _, cap)) = up.staging else { continue }; + let idle = now_ms.saturating_sub(up.last_used_ms) >= STAGING_IDLE_MS + && frame.saturating_sub(up.last_used_frame) >= STAGING_IDLE_FRAMES; + let shrink_low = low_commit && cap > STAGING_MIN; + if idle || shrink_low { + up.staging = None; + freed_count += 1; + freed_bytes = freed_bytes.saturating_add(cap); + } + } + } + } + if freed_bytes > 0 { + static LOGGED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if n < 4 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: released {freed_count} idle texture upload staging buffer(s) ({:.1} MiB{})", + freed_bytes as f64 / (1024.0 * 1024.0), + if low_commit { ", low commit" } else { "" } + ); + } + } +} + /// Several uploads on one list, one wait: (resource, subresources, states) each – the states /// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 /// order). A failure of one is returned with its index; the others still run. The texels go @@ -295,7 +524,9 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items put_back(key, up); return Ok(failed); } - let (staging, mapped) = up.staging(dev, total)?; + let now_ms = monotonic_ms(); + let frame = CURRENT_FRAME.load(std::sync::atomic::Ordering::Relaxed); + let (staging, mapped) = up.staging(dev, total, now_ms, frame)?; up.alloc.Reset().map_err(err)?; up.list.Reset(&up.alloc, None).map_err(err)?; for (k, l, base) in &planned { @@ -313,6 +544,8 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items std::mem::forget(up); return Err(copy_error(e)); } + up.last_used_ms = monotonic_ms(); + up.last_used_frame = CURRENT_FRAME.load(std::sync::atomic::Ordering::Relaxed); put_back(key, up); Ok(failed) } @@ -821,6 +1054,44 @@ mod tests { assert_eq!(staging_capacity(u64::MAX), None); } + #[test] + fn staging_pool_buckets_caps_reuses_and_reclaims_idle() { + let mib = 1u64 << 20; + assert_eq!(staging_pool_bucket(1), Some(64 << 10)); + assert_eq!(staging_pool_bucket(3 * mib), Some(4 * mib)); + assert_eq!(staging_pool_bucket(8 * mib), Some(8 * mib)); + assert_eq!(staging_pool_bucket(8 * mib + 1), None); + + // Disabled pool (cap 0) immediately returns released items. + let mut disabled = StagingPool::::new(0); + assert_eq!(disabled.release(4 * mib, 1, 0, 0), Some(1)); + + // Power-of-2 pooling with 12 MiB cap: LIFO reuse, oldest eviction on cap pressure, + // and idle reclamation only once BOTH >= 2 s and >= 30 frames have elapsed. + let mut pool = StagingPool::::new(12 * mib); + assert_eq!(pool.release(4 * mib, 10, 100, 1), None); + assert_eq!(pool.release(8 * mib, 20, 200, 2), None); + assert_eq!(pool.total_bytes, 12 * mib); + // Oversized (> 8 MiB) or non-power-of-2 buffers bypass the pool. + assert_eq!(pool.release(16 * mib, 99, 250, 3), Some(99)); + assert_eq!(pool.release(6 * mib, 98, 250, 3), Some(98)); + // Inserting another 4 MiB evicts the oldest (id 10, ts 100). + assert_eq!(pool.release(4 * mib, 30, 300, 4), None); + assert_eq!(pool.total_bytes, 12 * mib); + assert_eq!(pool.acquire(3 * mib), Some((4 * mib, 30))); + assert_eq!(pool.total_bytes, 8 * mib); + // Not idle yet: only time elapsed (frames < 30), or only frames elapsed (time < 2000ms). + assert_eq!(pool.trim_idle(5_000, 10, false), (0, 0)); + assert_eq!(pool.trim_idle(1_000, 100, false), (0, 0)); + // Both thresholds met -> idle 8 MiB buffer reclaimed. + assert_eq!(pool.trim_idle(2_200, 32, false), (1, 8 * mib)); + assert_eq!(pool.total_bytes, 0); + // Low-commit forced trim reclaims immediately regardless of idle age. + assert_eq!(pool.release(4 * mib, 40, 2_200, 32), None); + assert_eq!(pool.trim_idle(2_200, 32, true), (1, 4 * mib)); + assert_eq!(pool.total_bytes, 0); + } + fn select_large_upload_device_with( selector: &crate::gpu::adapter::Selector, make_factory: impl FnOnce() -> Result, diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index fd9fa17e3a..d66186e216 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -129,6 +129,7 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u } } super::real::stop_if_device_removed(); + crate::gpu::texture::trim_idle_staging(frames, super::vram::commit_low()); if !PRESENTX.swap(true, Ordering::Relaxed) { crate::xlog_info!("D3D12.X: PresentX – the title presents its own frames ({plane_count} plane(s))"); } From f968bfb50f2f7172ea4099764849576cd1abe15a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:48:02 +0100 Subject: [PATCH 133/258] D3D12.X: add sky-following stand-in ambient and reflection clamp Provide sky-following indirect diffuse ambient with depth-crease AO and reflection clamping when ray-traced indirect illumination is gated off (XCL_AMBIENT=auto|sky|off, default auto while XCL_RT_GATE holds back BVH traversal). - Classify ps_sky_paraboloid_reflection, CS_ScreenProbes_TemporalResolve, and CS_UpdateHistory from console shader metadata with AtomicBool fast-path guards. - Capture strictly 128x128 R16G16B16A16_FLOAT 2D sky dome draws (ignoring R11G11B10_FLOAT to prevent 3x frame flicker) into an internal texture and reduce its mean RGB via a 1-group SM 5.0 compute pass into an RWStructuredBuffer. - Track 2D float UAVs and depth SRVs by GLOBAL descriptor heap index (surviving CopyDescriptorsSimple and inline copies, evicted on resource release), applying ambient fill + depth-crease AO and TypedUAVLoad-checked reflection clamping via a 256-group rotating private descriptor ring and list_x::restore_after_internal_pass. - Includes unit tests for mode/classifier, format filter, target matching, transfer curve, and SM 5.0 D3DCompile. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/ambient.rs | 1048 +++++++++++++++++++++ crates/xcl/src/hle/d3d12x/bind.rs | 16 + crates/xcl/src/hle/d3d12x/console_heap.rs | 3 + crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 14 + 5 files changed, 1082 insertions(+) create mode 100644 crates/xcl/src/hle/d3d12x/ambient.rs diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs new file mode 100644 index 0000000000..fc76f75b34 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -0,0 +1,1048 @@ +//! Sky-following stand-in ambient lighting when ray-traced indirect illumination is gated off. +//! +//! When `XCL_RT_GATE` holds back ray-traced indirect lighting passes, screen-space probe resolve +//! (`CS_ScreenProbes_TemporalResolve`) receives no ray-traced bounce irradiance (leaving foliage, +//! cloth, and indoor shadows dark or corrupted) and reflection history (`CS_UpdateHistory`) can +//! retain unoccluded sky glare indoors. +//! +//! Controlled by `XCL_AMBIENT`: +//! * `auto` (default): active only while `XCL_RT_GATE` is holding back BVH traversal. +//! * `sky` / `1` / `on`: always active. +//! * `0` / `off` / `none`: disabled. +//! +//! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, +//! `XCL_AMBIENT_REFLECT`. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows::core::{Interface, PCSTR}; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::*; + +use super::console_list::{Layout, Param}; +use super::{list_x, present, real}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + Off, + Auto, + Sky, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Config { + mode: Mode, + gain: f32, + power: f32, + least: f32, + ao: f32, + reflect: f32, +} + +impl Default for Config { + fn default() -> Self { + Self { + mode: Mode::Auto, + gain: 0.55, + power: 0.65, + least: 0.025, + ao: 0.55, + reflect: 0.50, + } + } +} + +fn parse_mode(raw: Option<&str>) -> Mode { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("0" | "off" | "none" | "false") => Mode::Off, + Some("sky" | "1" | "on" | "true") => Mode::Sky, + _ => Mode::Auto, + } +} + +fn env_f32(name: &str, default: f32, lo: f32, hi: f32) -> f32 { + std::env::var(name) + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|v| v.is_finite()) + .map_or(default, |v| v.clamp(lo, hi)) +} + +fn config() -> &'static Config { + static CFG: OnceLock = OnceLock::new(); + CFG.get_or_init(|| { + let def = Config::default(); + let raw = std::env::var("XCL_AMBIENT").ok(); + Config { + mode: parse_mode(raw.as_deref()), + gain: env_f32("XCL_AMBIENT_GAIN", def.gain, 0.0, 8.0), + power: env_f32("XCL_AMBIENT_POWER", def.power, 0.1, 4.0), + least: env_f32("XCL_AMBIENT_LEAST", def.least, 0.0, 2.0), + ao: env_f32("XCL_AMBIENT_AO", def.ao, 0.0, 1.0), + reflect: env_f32("XCL_AMBIENT_REFLECT", def.reflect, 0.05, 4.0), + } + }) +} + +/// Whether sky-following stand-in ambient tracking is enabled (`XCL_AMBIENT != 0/off`). +pub fn enabled() -> bool { + config().mode != Mode::Off +} + +/// Whether stand-in ambient passes should currently execute. +pub fn active() -> bool { + match config().mode { + Mode::Off => false, + Mode::Sky => true, + Mode::Auto => !real::bvh_traversal_allowed(), + } +} + +/// Role of a console shader identified from FSSM/container metadata. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum PassRole { + SkyDome, + TemporalResolve, + ReflectionHistory, +} + +fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool { + if needle.is_empty() || haystack.len() < needle.len() { + return false; + } + haystack.windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle)) +} + +fn classify_ps(blob: &[u8]) -> Option { + if contains_ascii_ci(blob, b"ps_sky_paraboloid_reflection") { + Some(PassRole::SkyDome) + } else { + None + } +} + +fn classify_cs(blob: &[u8]) -> Option { + if contains_ascii_ci(blob, b"CS_ScreenProbes_TemporalResolve") { + Some(PassRole::TemporalResolve) + } else if contains_ascii_ci(blob, b"CS_UpdateHistory") { + Some(PassRole::ReflectionHistory) + } else { + None + } +} + +static PSO_ROLES: RwLock>> = RwLock::new(None); +static HAS_SKY_PSO: AtomicBool = AtomicBool::new(false); +static HAS_CS_PSO: AtomicBool = AtomicBool::new(false); + +pub(super) fn note_graphics_pso(pso: usize, ps: Option<&[u8]>) { + if pso == 0 || !enabled() { + return; + } + if let Some(role) = ps.and_then(classify_ps) { + PSO_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, role); + HAS_SKY_PSO.store(true, Ordering::Release); + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!("D3D12.X: ambient: tracked sky paraboloid PSO {pso:#x}"); + } + } +} + +pub(super) fn note_compute_pso(pso: usize, cs: &[u8]) { + if pso == 0 || !enabled() { + return; + } + if let Some(role) = classify_cs(cs) { + PSO_ROLES.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, role); + HAS_CS_PSO.store(true, Ordering::Release); + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_info!("D3D12.X: ambient: tracked {role:?} compute PSO {pso:#x}"); + } + } +} + +#[inline] +pub(super) fn has_sky_psos() -> bool { + HAS_SKY_PSO.load(Ordering::Relaxed) +} + +#[inline] +pub(super) fn has_compute_psos() -> bool { + HAS_CS_PSO.load(Ordering::Relaxed) +} + +fn role_of(pso: usize) -> Option { + if pso == 0 { + return None; + } + PSO_ROLES.read().unwrap().as_ref()?.get(&pso).copied() +} + +/// Descriptor-heap view metadata indexed by `GLOBAL` heap descriptor index (`T# word 0`), so +/// descriptors copied via either `CopyDescriptorsSimple` or inline title `memcpy` resolve cleanly. +#[derive(Clone, Copy, Debug)] +struct ViewEntry { + res: usize, + fmt: i32, + is_uav: bool, +} + +static VIEW_SLOTS: RwLock>> = RwLock::new(None); +static HAS_VIEW_SLOTS: AtomicBool = AtomicBool::new(false); + +fn is_ambient_uav_format(fmt: i32) -> bool { + matches!(fmt, 10 | 26) // R16G16B16A16_FLOAT, R11G11B10_FLOAT +} + +fn is_depth_srv_format(fmt: i32) -> bool { + // R32_FLOAT (41), R24_UNORM_X8_TYPELESS (46), R32_FLOAT_X8X24_TYPELESS (21), R16_UNORM (56) + matches!(fmt, 41 | 46 | 21 | 56) +} + +fn is_depth_resource_format(fmt: i32) -> bool { + matches!(fmt, 19 | 20 | 39 | 40 | 44 | 45 | 53 | 55) +} + +/// Record a 2D texture UAV or depth SRV written at `GLOBAL` descriptor index `slot_index`. +pub(super) fn note_descriptor(slot_index: u32, res: usize, fmt: i32, res_fmt: i32, is_uav: bool) { + if !enabled() || slot_index == 0 { + return; + } + if res == 0 { + if HAS_VIEW_SLOTS.load(Ordering::Relaxed) { + if let Some(m) = VIEW_SLOTS.write().unwrap().as_mut() { + m.remove(&slot_index); + } + } + return; + } + let keep = if is_uav { + is_ambient_uav_format(fmt) + } else { + is_depth_srv_format(fmt) && is_depth_resource_format(res_fmt) + }; + let mut g = VIEW_SLOTS.write().unwrap(); + if keep { + g.get_or_insert_with(HashMap::new) + .insert(slot_index, ViewEntry { res, fmt, is_uav }); + HAS_VIEW_SLOTS.store(true, Ordering::Release); + } else if let Some(m) = g.as_mut() { + m.remove(&slot_index); + } +} + +/// Evict any cached descriptor entries referencing a destroyed resource so stale raw pointers +/// are never dereferenced during dispatch lookup. +pub(super) fn forget_resource(res: usize) { + if res == 0 || !HAS_VIEW_SLOTS.load(Ordering::Relaxed) { + return; + } + if let Some(m) = VIEW_SLOTS.write().unwrap().as_mut() { + m.retain(|_, v| v.res != res); + } +} + +/// Propagate view metadata when `CopyDescriptorsSimple` renumbers a T# from `src_index` to `dst_index`. +pub(super) fn copy_descriptor(src_index: u32, dst_index: u32) { + if !enabled() || src_index == dst_index { + return; + } + let entry = VIEW_SLOTS.read().unwrap().as_ref().and_then(|m| m.get(&src_index).copied()); + let mut g = VIEW_SLOTS.write().unwrap(); + match entry { + Some(v) => { + g.get_or_insert_with(HashMap::new).insert(dst_index, v); + } + None => { + if let Some(m) = g.as_mut() { + m.remove(&dst_index); + } + } + } +} + +fn is_sky_dome_target(rd: &D3D12_RESOURCE_DESC) -> bool { + rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && rd.Width == 128 + && rd.Height == 128 + && rd.Format == DXGI_FORMAT_R16G16B16A16_FLOAT + && rd.SampleDesc.Count == 1 +} + +/// Match a screen-space resolve/reflection output UAV against dispatch grid dimensions. +fn matches_dispatch_target(rd: &D3D12_RESOURCE_DESC, groups: [u32; 3]) -> bool { + if rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D + || rd.SampleDesc.Count != 1 + || rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 + || !is_ambient_uav_format(rd.Format.0) + { + return false; + } + let w = rd.Width as u32; + let h = rd.Height; + if w < 64 || h < 64 || groups[0] == 0 || groups[1] == 0 { + return false; + } + let max_w = groups[0].saturating_mul(32); + let max_h = groups[1].saturating_mul(32); + let min_w = groups[0].saturating_mul(4); + let min_h = groups[1].saturating_mul(4); + w >= min_w && w <= max_w && h >= min_h && h <= max_h +} + +/// Compute scalar/RGB stand-in sky level (mirrors the GPU `sky_reduce_cs` transfer curve). +#[cfg(test)] +fn sky_transfer(mean_rgb: [f32; 3], gain: f32, power: f32, least: f32) -> [f32; 3] { + [ + gain * mean_rgb[0].max(0.0).powf(power) + least, + gain * mean_rgb[1].max(0.0).powf(power) + least, + gain * mean_rgb[2].max(0.0).powf(power) + least, + ] +} + +// --------------------------------------------------------------------------------------- +// Internal D3D12 compute pipelines & per-device rotating descriptor ring +// --------------------------------------------------------------------------------------- + +/// Rotating groups of 3 descriptors (`t0` SRV, `u0` UAV, `u1` UAV) in our private shader-visible +/// heap so back-to-back in-flight dispatches never overwrite descriptors still read by the GPU. +const RING_GROUPS: u32 = 256; +const GROUP_SLOTS: u32 = 3; + +struct AmbientDevice { + rs: ID3D12RootSignature, + reduce_pso: ID3D12PipelineState, + fill_pso: ID3D12PipelineState, + reflect_pso: ID3D12PipelineState, + sky_copy: ID3D12Resource, + sky_level: ID3D12Resource, + dummy_depth: ID3D12Resource, + heap: ID3D12DescriptorHeap, + heap_cpu: u64, + heap_gpu: u64, + inc: u32, + next_group: AtomicU32, + sky_ready: AtomicBool, +} + +unsafe impl Send for AmbientDevice {} +unsafe impl Sync for AmbientDevice {} + +static DEVICES: Mutex>>>> = Mutex::new(None); + +fn compile_cs_sm5(src: &str) -> Option> { + unsafe { + let mut blob = None; + let r = D3DCompile( + src.as_ptr() as *const c_void, + src.len(), + PCSTR::null(), + None, + None, + PCSTR(b"main\0".as_ptr()), + PCSTR(b"cs_5_0\0".as_ptr()), + 0, + 0, + &mut blob, + None, + ); + match (r, blob) { + (Ok(()), Some(b)) => Some(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec()), + _ => None, + } + } +} + +const SKY_REDUCE_HLSL: &str = r#" +Texture2D sky_tex : register(t0); +RWStructuredBuffer sky_level : register(u0); +cbuffer C : register(b0) { + float gain; + float power; + float least; + float _p3; + uint _u4; + uint _u5; + uint _u6; + uint _u7; +}; +groupshared float3 gs_sum[64]; +[numthreads(8, 8, 1)] +void main(uint3 gtid : SV_GroupThreadID, uint gidx : SV_GroupIndex) { + float3 acc = float3(0.0, 0.0, 0.0); + uint x0 = gtid.x * 16; + uint y0 = gtid.y * 16; + [loop] + for (uint dy = 0; dy < 16; ++dy) { + [loop] + for (uint dx = 0; dx < 16; ++dx) { + float3 c = sky_tex.Load(int3(int(x0 + dx), int(y0 + dy), 0)).rgb; + if (all(isfinite(c))) { + acc += clamp(c, 0.0, 16.0); + } + } + } + gs_sum[gidx] = acc * (1.0 / 256.0); + GroupMemoryBarrierWithGroupSync(); + [unroll] + for (uint s = 32; s > 0; s >>= 1) { + if (gidx < s) { + gs_sum[gidx] += gs_sum[gidx + s]; + } + GroupMemoryBarrierWithGroupSync(); + } + if (gidx == 0) { + float3 mean_rgb = max(gs_sum[0] * (1.0 / 64.0), 0.0); + float3 level = gain * pow(mean_rgb, power) + least; + float lum = dot(level, float3(0.2126, 0.7152, 0.0722)); + sky_level[0] = float4(level, lum); + } +} +"#; + +const AMBIENT_FILL_HLSL: &str = r#" +Texture2D depth_tex : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint depth_w; + uint depth_h; + uint has_depth; + float ao_strength; + float _p6; + float _p7; +}; +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height) return; + float3 amb = sky_level[0].rgb; + float ao = 1.0; + if (has_depth != 0 && depth_w > 0 && depth_h > 0) { + int2 dc = int2( + min((tid.x * depth_w) / max(width, 1u), depth_w - 1), + min((tid.y * depth_h) / max(height, 1u), depth_h - 1) + ); + float d0 = depth_tex.Load(int3(dc, 0)); + if (isfinite(d0) && d0 > 1e-6 && d0 < 0.99999) { + int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); + float d1 = depth_tex.Load(int3(clamp(dc + int2(2, 0), int2(0, 0), maxc), 0)); + float d2 = depth_tex.Load(int3(clamp(dc - int2(2, 0), int2(0, 0), maxc), 0)); + float d3 = depth_tex.Load(int3(clamp(dc + int2(0, 2), int2(0, 0), maxc), 0)); + float d4 = depth_tex.Load(int3(clamp(dc - int2(0, 2), int2(0, 0), maxc), 0)); + float avg = 0.25 * (d1 + d2 + d3 + d4); + float crease = saturate(abs(avg - d0) / max(d0, 1e-4) * 3.0); + ao = 1.0 - ao_strength * crease; + } + } + out_uav[tid.xy] = float4(amb * ao, 1.0); +} +"#; + +const REFLECT_CLAMP_HLSL: &str = r#" +Texture2D _unused : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint _u2; + uint _u3; + uint _u4; + float reflect_scale; + float _p6; + float _p7; +}; +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height) return; + float4 cur = out_uav[tid.xy]; + float3 rgb = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + float3 cap = max(sky_level[0].rgb * reflect_scale, float3(0.005, 0.005, 0.005)); + out_uav[tid.xy] = float4(min(rgb, cap), isfinite(cur.a) ? cur.a : 1.0); +} +"#; + +unsafe fn build_device(dev: &ID3D12Device) -> Option { + let reduce_bc = compile_cs_sm5(SKY_REDUCE_HLSL)?; + let fill_bc = compile_cs_sm5(AMBIENT_FILL_HLSL)?; + let reflect_bc = compile_cs_sm5(REFLECT_CLAMP_HLSL)?; + + // Shared compute RS: [0] 8 root constants (b0), [1] 1 SRV (t0), [2] 2 UAVs (u0..u1) + let srv_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_SRV, + NumDescriptors: 1, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let uav_range = D3D12_DESCRIPTOR_RANGE { + RangeType: D3D12_DESCRIPTOR_RANGE_TYPE_UAV, + NumDescriptors: 2, + BaseShaderRegister: 0, + RegisterSpace: 0, + OffsetInDescriptorsFromTableStart: 0, + }; + let params = [ + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Constants: D3D12_ROOT_CONSTANTS { ShaderRegister: 0, RegisterSpace: 0, Num32BitValues: 8 }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &srv_range }, + }, + }, + D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + Anonymous: D3D12_ROOT_PARAMETER_0 { + DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE { NumDescriptorRanges: 1, pDescriptorRanges: &uav_range }, + }, + }, + ]; + let rs_desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: params.len() as u32, + pParameters: params.as_ptr(), + ..Default::default() + }; + let mut rs_blob = None; + D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut rs_blob, None).ok()?; + let rs_blob = rs_blob?; + + let dev_raw = dev.as_raw(); + type CreateRsFn = unsafe extern "system" fn(*mut c_void, u32, *const c_void, usize, *const c_void, *mut *mut c_void) -> i32; + type CreateCsFn = unsafe extern "system" fn(*mut c_void, *const D3D12_COMPUTE_PIPELINE_STATE_DESC, *const c_void, *mut *mut c_void) -> i32; + type CreateHeapFn = unsafe extern "system" fn(*mut c_void, *const D3D12_DESCRIPTOR_HEAP_DESC, *const c_void, *mut *mut c_void) -> i32; + type IncSizeFn = unsafe extern "system" fn(*mut c_void, D3D12_DESCRIPTOR_HEAP_TYPE) -> u32; + type CreateResFn = unsafe extern "system" fn( + *mut c_void, + *const D3D12_HEAP_PROPERTIES, + D3D12_HEAP_FLAGS, + *const D3D12_RESOURCE_DESC, + D3D12_RESOURCE_STATES, + *const D3D12_CLEAR_VALUE, + *const c_void, + *mut *mut c_void, + ) -> i32; + + let create_rs: CreateRsFn = std::mem::transmute(real::orig_fn(dev_raw, 16)); + let create_cs: CreateCsFn = std::mem::transmute(real::orig_fn(dev_raw, 11)); + let create_heap: CreateHeapFn = std::mem::transmute(real::orig_fn(dev_raw, 14)); + let inc_size: IncSizeFn = std::mem::transmute(real::orig_fn(dev_raw, 15)); + let create_res: CreateResFn = std::mem::transmute(real::orig_fn(dev_raw, 27)); + + let mut rs_raw = std::ptr::null_mut(); + if create_rs(dev_raw, 0, rs_blob.GetBufferPointer(), rs_blob.GetBufferSize(), &ID3D12RootSignature::IID as *const _ as *const c_void, &mut rs_raw) < 0 || rs_raw.is_null() { + return None; + } + let rs = ID3D12RootSignature::from_raw(rs_raw); + + let make_cs = |bc: &[u8]| -> Option { + let mut d = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(rs.clone())), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bc.as_ptr() as *const c_void, BytecodeLength: bc.len() }, + ..Default::default() + }; + let mut raw = std::ptr::null_mut(); + let hr = create_cs(dev_raw, &d, &ID3D12PipelineState::IID as *const _ as *const c_void, &mut raw); + ManuallyDrop::drop(&mut d.pRootSignature); + (hr >= 0 && !raw.is_null()).then(|| ID3D12PipelineState::from_raw(raw)) + }; + let reduce_pso = make_cs(&reduce_bc)?; + let fill_pso = make_cs(&fill_bc)?; + let reflect_pso = make_cs(&reflect_bc)?; + + let default_hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let make_res = |rd: &D3D12_RESOURCE_DESC, init: D3D12_RESOURCE_STATES| -> Option { + let mut raw = std::ptr::null_mut(); + let hr = create_res(dev_raw, &default_hp, D3D12_HEAP_FLAG_NONE, rd, init, std::ptr::null(), &ID3D12Resource::IID as *const _ as *const c_void, &mut raw); + (hr >= 0 && !raw.is_null()).then(|| ID3D12Resource::from_raw(raw)) + }; + + let sky_copy = make_res( + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )?; + let sky_level = make_res( + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COMMON, + )?; + let dummy_depth = make_res( + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )?; + + let heap_desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + NumDescriptors: RING_GROUPS * GROUP_SLOTS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, + NodeMask: 0, + }; + let mut heap_raw = std::ptr::null_mut(); + if create_heap(dev_raw, &heap_desc, &ID3D12DescriptorHeap::IID as *const _ as *const c_void, &mut heap_raw) < 0 || heap_raw.is_null() { + return None; + } + let heap = ID3D12DescriptorHeap::from_raw(heap_raw); + let heap_cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr as u64; + let heap_gpu = heap.GetGPUDescriptorHandleForHeapStart().ptr; + let inc = inc_size(dev_raw, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + + Some(AmbientDevice { + rs, + reduce_pso, + fill_pso, + reflect_pso, + sky_copy, + sky_level, + dummy_depth, + heap, + heap_cpu, + heap_gpu, + inc, + next_group: AtomicU32::new(0), + sky_ready: AtomicBool::new(false), + }) +} + +unsafe fn get_device(dev: &ID3D12Device) -> Option> { + let key = dev.as_raw() as usize; + { + let g = DEVICES.lock().unwrap(); + if let Some(entry) = g.as_ref().and_then(|m| m.get(&key)) { + return entry.clone(); + } + } + let built = build_device(dev).map(std::sync::Arc::new); + DEVICES.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, built.clone()); + built +} + +impl AmbientDevice { + fn alloc_group(&self) -> (u64, u64) { + let g = self.next_group.fetch_add(1, Ordering::Relaxed) % RING_GROUPS; + let off = (g * GROUP_SLOTS) as u64 * self.inc as u64; + (self.heap_cpu + off, self.heap_gpu + off) + } +} + +unsafe fn uav_barrier(list: *mut c_void, res_raw: usize) { + let b = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { + pResource: std::mem::transmute_copy(&res_raw), + }), + }, + }; + list_x::pc_resource_barriers(list, &[b]); +} + +unsafe fn typed_uav_load_supported(dev: &ID3D12Device, fmt: DXGI_FORMAT) -> bool { + let mut fs = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: fmt, ..Default::default() }; + dev.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &mut fs as *mut _ as *mut c_void, std::mem::size_of_val(&fs) as u32).is_ok() + && (fs.Support2.0 & D3D12_FORMAT_SUPPORT2_UAV_TYPED_LOAD.0 != 0) +} + +/// Called right after a translated graphics draw completes: if the PSO is the sky paraboloid +/// reflection shader targeting a `128x128 R16G16B16A16_FLOAT` 2D render target, snapshot it +/// and update the sky-following ambient level buffer on the GPU. +pub(super) unsafe fn after_draw(list: *mut c_void, pso_resolved: usize) { + if !has_sky_psos() || !active() || role_of(pso_resolved) != Some(PassRole::SkyDome) { + return; + } + if list_x::tracked_list_type(list) != Some(D3D12_COMMAND_LIST_TYPE_DIRECT) { + return; + } + let Some(rt0) = present::rt0_resource(list as usize) else { return }; + let rt_ptr = rt0 as *mut c_void; + let Some(rt_res) = ID3D12Resource::from_raw_borrowed(&rt_ptr) else { return }; + if !is_sky_dome_target(&rt_res.GetDesc()) { + return; + } + let Some(cl) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) else { return }; + let mut dev: Option = None; + if cl.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Some(ad) = get_device(&dev) else { return }; + + let sky_raw = ad.sky_copy.as_raw() as usize; + list_x::transition(list, rt0, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE); + list_x::transition(list, sky_raw, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + list_x::pc_copy_resource(list, sky_raw, rt0); + list_x::transition(list, sky_raw, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list_x::transition(list, rt0, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET); + + let (cpu0, gpu0) = ad.alloc_group(); + let inc = ad.inc as u64; + let dev_raw = dev.as_raw(); + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrvFn = std::mem::transmute(real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); + + let sky_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }; + let level_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: 1, StructureByteStride: 16, ..Default::default() }, + }, + }; + create_srv(dev_raw, ad.sky_copy.as_raw(), &sky_srv, cpu0 as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 14)); + + let cfg = config(); + let consts = [cfg.gain.to_bits(), cfg.power.to_bits(), cfg.least.to_bits(), 0, 0, 0, 0, 0]; + set_heaps(list, 1, &heap_raw); + set_cs_rs(list, ad.rs.as_raw()); + set_pso(list, ad.reduce_pso.as_raw()); + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + set_cs_table(list, 1, gpu0); + set_cs_table(list, 2, gpu0 + inc); + dispatch(list, 1, 1, 1); + uav_barrier(list, ad.sky_level.as_raw() as usize); + ad.sky_ready.store(true, Ordering::Release); + list_x::restore_after_internal_pass(list, false, true); + + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: ambient: captured 128x128 R16G16B16A16_FLOAT sky dome ({rt0:#x})"); + } +} + +/// Inspect a compute dispatch's bound descriptor tables and root constants/CBVs to locate its +/// output screen-space float UAV (and optional depth SRV for crease AO). +unsafe fn find_dispatch_views(layout: &Layout, args: &[u8], groups: [u32; 3]) -> (Option<(usize, i32, u32, u32)>, Option<(usize, i32, u32, u32)>) { + let Some(u) = crate::gpu::uma::get() else { return (None, None) }; + let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + let mut tables: Vec = Vec::new(); + let mut indices: Vec = Vec::new(); + for p in &layout.params { + match *p { + Param::Constants { at, count } => { + for k in 0..count.min(32) as usize { + if let Some(v) = word(at as usize + 4 * k) { + if v < (1 << 20) { + indices.push(v); + } + } + } + } + Param::Descriptor { at } => { + let lo = word(at as usize).unwrap_or(0) as u64; + let hi = word(at as usize + 4).unwrap_or(0) as u64; + let va = (lo | (hi << 32)) as usize; + if va != 0 && crate::gpu::shader::readable(va, 256) { + for k in 0..64usize { + let v = ((va + 4 * k) as *const u32).read_unaligned(); + if v < (1 << 20) { + indices.push(v); + } + } + } + } + Param::Table { at } => { + if let Some(t) = word(at as usize) { + if t != 0 { + tables.push(t); + } + } + } + } + } + // Also probe direct table slots 0..16 in case descriptors are bound directly without bindless indices. + for k in 0..16u32 { + indices.push(k); + } + + let mut uav_hit: Option<(usize, i32, u32, u32)> = None; + let mut depth_hit: Option<(usize, i32, u32, u32)> = None; + let slots = VIEW_SLOTS.read().unwrap(); + let Some(map) = slots.as_ref() else { return (None, None) }; + + for &t in &tables { + for &idx in &indices { + let Some(off) = (t as usize).checked_add(32usize.saturating_mul(idx as usize)) else { continue }; + let Some(addr) = u.base().checked_add(off) else { continue }; + if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { + continue; + } + let w0 = (addr as *const u32).read_unaligned(); + let w3 = ((addr + 12) as *const u32).read_unaligned(); + // Image T# descriptors have type >= 8 in bits [31:28] of word 3. + if (w3 >> 28) < 8 { + continue; + } + let Some(&ve) = map.get(&w0) else { continue }; + let ptr = ve.res as *mut c_void; + let Some(res) = ID3D12Resource::from_raw_borrowed(&ptr) else { continue }; + let rd = res.GetDesc(); + if ve.is_uav && uav_hit.is_none() && matches_dispatch_target(&rd, groups) { + uav_hit = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height)); + } else if !ve.is_uav + && depth_hit.is_none() + && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && rd.SampleDesc.Count == 1 + && rd.Width >= 64 + && rd.Height >= 64 + { + depth_hit = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height)); + } + if uav_hit.is_some() && depth_hit.is_some() { + return (uav_hit, depth_hit); + } + } + } + (uav_hit, depth_hit) +} + +/// Called right after a translated compute dispatch completes: when RT is gated off and a sky +/// dome sample has been captured, replace `CS_ScreenProbes_TemporalResolve` with sky-following +/// ambient + depth-crease AO and clamp `CS_UpdateHistory` reflections to `reflect * ambient`. +pub(super) unsafe fn after_compute_dispatch( + list: *mut c_void, + pso_resolved: usize, + groups: [u32; 3], + layout: Option<&Layout>, + args: &[u8], +) { + if !has_compute_psos() || !active() { + return; + } + let Some(role) = role_of(pso_resolved) else { return }; + if !matches!(role, PassRole::TemporalResolve | PassRole::ReflectionHistory) { + return; + } + let ty = list_x::tracked_list_type(list); + if !matches!(ty, Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE)) { + return; + } + let Some(layout) = layout else { return }; + let Some(cl) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) else { return }; + let mut dev: Option = None; + if cl.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let Some(ad) = get_device(&dev) else { return }; + if !ad.sky_ready.load(Ordering::Acquire) { + return; + } + + let (uav_opt, depth_opt) = find_dispatch_views(layout, args, groups); + let Some((uav_res, uav_fmt, w, h)) = uav_opt else { return }; + if role == PassRole::ReflectionHistory && !typed_uav_load_supported(&dev, DXGI_FORMAT(uav_fmt)) { + return; + } + + let (cpu0, gpu0) = ad.alloc_group(); + let inc = ad.inc as u64; + let dev_raw = dev.as_raw(); + type CreateSrvFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, usize); + type CreateUavFn = unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, usize); + let create_srv: CreateSrvFn = std::mem::transmute(real::orig_fn(dev_raw, 18)); + let create_uav: CreateUavFn = std::mem::transmute(real::orig_fn(dev_raw, 19)); + + let (depth_raw, depth_fmt, depth_w, depth_h, has_depth) = match (role, depth_opt) { + (PassRole::TemporalResolve, Some((r, f, dw, dh))) => (r as *mut c_void, DXGI_FORMAT(f), dw, dh, 1u32), + _ => (ad.dummy_depth.as_raw(), DXGI_FORMAT_R32_FLOAT, 1, 1, 0u32), + }; + let depth_srv = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: depth_fmt, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, + }, + }; + let out_uav_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(uav_fmt), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }, + }, + }; + let level_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT_UNKNOWN, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { FirstElement: 0, NumElements: 1, StructureByteStride: 16, ..Default::default() }, + }, + }; + create_srv(dev_raw, depth_raw, &depth_srv, cpu0 as usize); + create_uav(dev_raw, uav_res as *mut c_void, std::ptr::null_mut(), &out_uav_desc, (cpu0 + inc) as usize); + create_uav(dev_raw, ad.sky_level.as_raw(), std::ptr::null_mut(), &level_uav, (cpu0 + 2 * inc) as usize); + + uav_barrier(list, uav_res); + + let heap_raw = ad.heap.as_raw() as usize; + let set_heaps: unsafe extern "system" fn(*mut c_void, u32, *const usize) = std::mem::transmute(real::orig_fn(list, 28)); + let set_cs_rs: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 29)); + let set_pso: unsafe extern "system" fn(*mut c_void, *mut c_void) = std::mem::transmute(real::orig_fn(list, 25)); + let set_cs_table: unsafe extern "system" fn(*mut c_void, u32, u64) = std::mem::transmute(real::orig_fn(list, 31)); + let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 35)); + let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 14)); + + let cfg = config(); + let (pso, consts) = match role { + PassRole::TemporalResolve => ( + ad.fill_pso.as_raw(), + [w, h, depth_w, depth_h, has_depth, cfg.ao.to_bits(), 0, 0], + ), + PassRole::ReflectionHistory => ( + ad.reflect_pso.as_raw(), + [w, h, 0, 0, 0, cfg.reflect.to_bits(), 0, 0], + ), + PassRole::SkyDome => return, + }; + set_heaps(list, 1, &heap_raw); + set_cs_rs(list, ad.rs.as_raw()); + set_pso(list, pso); + set_cs_consts(list, 0, 8, consts.as_ptr(), 0); + set_cs_table(list, 1, gpu0); + set_cs_table(list, 2, gpu0 + inc); + dispatch(list, w.div_ceil(8), h.div_ceil(8), 1); + uav_barrier(list, uav_res); + list_x::restore_after_internal_pass(list, false, true); + + static LOGGED: AtomicU64 = AtomicU64::new(0); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!("D3D12.X: ambient: applied {role:?} stand-in on {w}x{h} fmt {uav_fmt} (depth AO: {has_depth})"); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mode_and_shader_classification_match_expected_passes() { + assert_eq!(parse_mode(None), Mode::Auto); + assert_eq!(parse_mode(Some("auto")), Mode::Auto); + assert_eq!(parse_mode(Some("sky")), Mode::Sky); + assert_eq!(parse_mode(Some("1")), Mode::Sky); + assert_eq!(parse_mode(Some("0")), Mode::Off); + assert_eq!(parse_mode(Some("off")), Mode::Off); + + assert_eq!(classify_ps(b"\0PRIVps_sky_paraboloid_reflection\0"), Some(PassRole::SkyDome)); + assert_eq!(classify_ps(b"\0PS_Sky_Paraboloid_Reflection_V2\0"), Some(PassRole::SkyDome)); + assert_eq!(classify_ps(b"\0ps_gbuffer_opaque\0"), None); + + assert_eq!(classify_cs(b"ILDN\0CS_ScreenProbes_TemporalResolve\0"), Some(PassRole::TemporalResolve)); + assert_eq!(classify_cs(b"ILDN\0CS_UpdateHistory_16\0"), Some(PassRole::ReflectionHistory)); + assert_eq!(classify_cs(b"ILDN\0CS_CullInstances\0"), None); + } + + #[test] + fn sky_dome_filter_rejects_r11g11b10_and_wrong_sizes() { + let mut rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 128, + Height: 128, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + ..Default::default() + }; + assert!(is_sky_dome_target(&rd)); + + // Must ignore the brighter 128x128 R11G11B10_FLOAT pass to prevent frame flicker. + rd.Format = DXGI_FORMAT_R11G11B10_FLOAT; + assert!(!is_sky_dome_target(&rd)); + + rd.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; + rd.Width = 256; + assert!(!is_sky_dome_target(&rd)); + } + + #[test] + fn dispatch_target_matching_and_sky_transfer_curve() { + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1280, + Height: 720, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + assert!(matches_dispatch_target(&rd, [160, 90, 1])); + assert!(!matches_dispatch_target(&rd, [16, 16, 1])); + + let night = sky_transfer([0.0, 0.0, 0.0], 0.55, 0.65, 0.025); + assert!((night[0] - 0.025).abs() < 1e-6); + let day = sky_transfer([1.0, 0.9, 1.2], 0.55, 0.65, 0.025); + assert!(day[2] > day[0] && day[0] > night[0]); + } + + #[test] + fn sm5_ambient_hlsl_shaders_compile_cleanly() { + assert!(compile_cs_sm5(SKY_REDUCE_HLSL).is_some(), "SKY_REDUCE_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(AMBIENT_FILL_HLSL).is_some(), "AMBIENT_FILL_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(REFLECT_CLAMP_HLSL).is_some(), "REFLECT_CLAMP_HLSL failed D3DCompile"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 374b869819..fad492f490 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3152,10 +3152,18 @@ pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); if let Some(list) = graphics_bound(this) { if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { + if super::ambient::has_sky_psos() { + let pso = pso_for_draw(with(this, |s| s.pso)); + super::ambient::after_draw(this, pso); + } return; } super::list_x::sync_title_buffers(this, None, first_vertex, vertices, if first_instance != 0 { instances.max(2) } else { instances }); list.DrawInstanced(vertices, instances, first_vertex, first_instance); + if super::ambient::has_sky_psos() { + let pso = pso_for_draw(with(this, |s| s.pso)); + super::ambient::after_draw(this, pso); + } } } @@ -3169,6 +3177,10 @@ pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, i if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); + if super::ambient::has_sky_psos() { + let pso = pso_for_draw(with(this, |s| s.pso)); + super::ambient::after_draw(this, pso); + } } } @@ -3687,6 +3699,10 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis let mark = super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [x, y, z]); let r = super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]); super::culprit::after_dispatch(list, mark); + if super::ambient::has_compute_psos() { + let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); + super::ambient::after_compute_dispatch(this, pso, [x, y, z], layout.as_deref(), &args); + } with(this, |s| { s.arg_order_clean = false; s.prelude_blocked = true; diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 902ff97fc6..eb7e75e569 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -674,6 +674,9 @@ pub fn copy_words(src: &Slot, dst: &Slot) { write(dst, &w[..n]); if !src.sampler { note_resource(dst, resource_at(src.at).unwrap_or(0)); + if w[3] >> 28 >= 8 { + super::ambient::copy_descriptor(src.index, dst.index); + } } } diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index a90571f9f5..42e4a80a74 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -10,6 +10,7 @@ #![allow(non_snake_case)] mod alloc_pool; +mod ambient; pub mod bind; pub mod console_heap; pub mod console_list; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 09bafc1cb9..15477001d0 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1821,6 +1821,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } super::depth_uav::forget(this as usize); super::format_alias::forget(this as usize); + super::ambient::forget_resource(this as usize); let gone = UMA_BUFFERS.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { if u.is_sparse(p) { @@ -2557,6 +2558,7 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } } let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { + super::ambient::note_descriptor(slot.index, 0, 0, 0, false); // A null image SRV was already created and published at `slot.index`. Writing `[0; 8]` // would point shaders at `ResourceDescriptorHeap[0]` (memory window 0 / uninitialized), // so write a valid T# referencing `slot.index` with the view's format class and type. @@ -2570,11 +2572,13 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, return super::console_heap::write(&slot, &[0; 8]); }; if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { + super::ambient::note_descriptor(slot.index, 0, 0, 0, false); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true)); } let rdesc = r.GetDesc(); + super::ambient::note_descriptor(slot.index, res as usize, desc.as_ref().map_or(rdesc.Format.0, |v| v.Format.0), rdesc.Format.0, false); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { Some(t) => super::console_heap::write(&slot, &t), None => { @@ -2956,6 +2960,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, super::console_heap::publish(&slot, true); super::console_heap::note_resource(&slot, res as usize); let Some(r) = ID3D12Resource::from_raw_borrowed(&uav_res) else { + super::ambient::note_descriptor(slot.index, 0, 0, 0, true); // A null image UAV was already created and published at `slot.index + 1`. Create a // matching null companion SRV at `slot.index` and write a valid T# referencing // `slot.index` so shaders never fall back to `ResourceDescriptorHeap[0]` / `[1]`. @@ -2974,6 +2979,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, }; let rd = uav_rd_opt.unwrap(); if let Some(v) = uav_desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { + super::ambient::note_descriptor(slot.index, 0, 0, 0, true); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, false)); @@ -2994,6 +3000,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } None => (rd.Format, resource_dim_to_view(&rd), rd.DepthOrArraySize as u32, 0), }; + super::ambient::note_descriptor(slot.index, uav_res as usize, format.0, rd.Format.0, true); let Some((fmt, ty, w, h, d, _)) = view_shape(r, format, dim, array, 1) else { note_buffer_view(); return super::console_heap::write(&slot, &[0; 8]); @@ -4863,6 +4870,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } note_compute_threads(*ppv as usize, cs); note_bvh_traversal(*ppv as usize, cs); + super::ambient::note_compute_pso(*ppv as usize, cs); note_translated_compute(0, ppv); TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); return Some(Ok(0)); @@ -4884,6 +4892,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } note_compute_threads(*ppv as usize, cs); note_bvh_traversal(*ppv as usize, cs); + super::ambient::note_compute_pso(*ppv as usize, cs); note_translated_compute(S_OK, ppv); return Some(Ok(S_OK)); } @@ -4915,6 +4924,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } note_compute_threads(*ppv as usize, cs); note_bvh_traversal(*ppv as usize, cs); + super::ambient::note_compute_pso(*ppv as usize, cs); note_translated_compute(hr, ppv); crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", @@ -5868,6 +5878,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); if super::present::trace_frame() { @@ -5945,6 +5956,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const } note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", shader_bytes(&d.PS))]); + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); if super::present::trace_frame() { @@ -7033,6 +7045,7 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri let hr = finish_two_pass(this, &out, tp, rs, "MS", riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); + super::ambient::note_graphics_pso(*ppv as usize, console_ps); if let Some(tp) = two_pass_of(*ppv as usize) { super::dred::label_text(tp.compute, || format!("compute pass of ms {:016x}", crate::gpu::shader::fnv64(ms))); } @@ -7111,6 +7124,7 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE let hr = finish_two_pass(this, &out, tp, rs, "GS", riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))]); + super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); } hr } From fd1ed900776120f9a8e220c628f8ac96491af92a Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:58:13 +0100 Subject: [PATCH 134/258] D3D12.X: break sparse::STATE <-> kernelx::AWAY deadlock in gpu_view With XCL_GPU_VIEW_BUFFERS=1, DirectStorage/XMemMapPhysicalPages holds kernelx::AWAY while calling sparse::committed/decommitted (sparse::STATE), whereas gpu_view::sync and gpu_view::base_for held sparse::STATE while querying kernelx::mirrors::mapped_source / physical_page_at (kernelx::AWAY), causing an ABBA deadlock. Move all kernelx queries outside sparse::STATE: pre-resolve tile CPU sources and hole masks before lock_state() in gpu_view::base_for, and split gpu_view::sync into prepare_sync() (before lock_state() in sparse::before_execute) + apply_sync() (under STATE with zero kernelx locks). Added regression test prepare_sync_does_not_require_state_lock. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/sparse.rs | 5 +- crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 104 ++++++++++++++----- 2 files changed, 81 insertions(+), 28 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index c2f86c4dab..4801a3b9b1 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1682,6 +1682,9 @@ pub fn note_watch(t: std::time::Duration, pages: usize) { /// memory, and `queue` GPU-waits for that and for new tile mappings. pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) { let t0 = std::time::Instant::now(); + // Phase 1 of GPU-view sync runs BEFORE `lock_state()` so `kernelx::AWAY` / `mirrors` locks + // are never acquired while holding `sparse::STATE` (ABBA deadlock with `XMemMapPhysicalPages`). + let gpu_view_prep = if gpu_view::on() { gpu_view::prepare_sync() } else { None }; let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; s.note_queue(queue); @@ -1739,7 +1742,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: s.upload_dirty(&dirty_runs); } if gpu_view::on() { - gpu_view::sync(s, dirty); + gpu_view::apply_sync(s, dirty, gpu_view_prep); } PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); { diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs index 3aa28019ab..f5cf32d0ef 100644 --- a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -321,7 +321,23 @@ pub fn base_for(va: usize, len: usize) -> Option { *MIRRORS.lock().unwrap().get_or_insert_with(Mirrors::default).extents.entry((first, n)).or_insert(w) } }; - // (held: STATE, then MIRRORS, as in `sync`) + // Resolve every tile's CPU source and committed-page hole mask BEFORE locking `sparse::STATE` + // so `STATE` is never held across `kernelx::AWAY` / `mirrors` locks (preventing ABBA deadlock + // with `XMemMapPhysicalPages` / `CopyPageMappingsBatchX` which hold `AWAY` -> `STATE`). + let resolved: Vec<(usize, usize, u16)> = (t0..t1) + .step_by(TILE) + .map(|t| { + let src = super::super::title_textures::mirror_source(t) & !(TILE - 1); + let holes = unsafe { query_tile_holes(src) }; + (t, src, holes) + }) + .collect(); + let resolved_of = |t: usize| -> (usize, u16) { + resolved + .binary_search_by_key(&t, |&(k, _, _)| k) + .map_or((t, 0xFFFF), |i| (resolved[i].1, resolved[i].2)) + }; + // (held: STATE, then MIRRORS, as in `apply_sync`) let mut g = lock_state(); let s = g.as_mut()?; let mut mg = MIRRORS.lock().unwrap(); @@ -366,13 +382,13 @@ pub fn base_for(va: usize, len: usize) -> Option { } let (a, b) = (new[i], win + (new[i] - first)); // SAFETY: the tiles are address space of a window, with no CPU memory behind them - unsafe { s.ensure_mapped(b, (j - i) * TILE, |w| query_tile_holes(super::super::title_textures::mirror_source(a + (w - b)))) }; + unsafe { s.ensure_mapped(b, (j - i) * TILE, |w| resolved_of(a + (w - b)).1) }; for &t in &new[i..j] { let w = win + (t - first); if s.mapped.contains_key(&w) { - let src = super::super::title_textures::mirror_source(t) & !(TILE - 1); + let (src, holes) = resolved_of(t); m.show(w, t, src); - if unsafe { query_tile_holes(src) } != 0xFFFF { + if holes != 0xFFFF { m.backed.insert(t); } } @@ -412,34 +428,59 @@ pub fn sources() -> Vec<(usize, usize)> { MIRRORS.lock().unwrap().as_ref().map_or(Vec::new(), |m| m.by_read.keys().map(|&r| (r, r + TILE)).collect()) } -/// `State::mirror_up` for a submit (`before_execute`; `s` is the locked state). A page the title -/// mapped elsewhere or now has no mapping at all is looked at again when the mappings of a GPU -/// view change, and a few tiles in turn otherwise. -pub(super) unsafe fn sync(s: &mut State, dirty: &[usize]) { +/// Pre-checked GPU-view tile liveness & backing-address updates collected outside `sparse::STATE` +/// so `apply_sync` never acquires `kernelx::AWAY` / `mirrors` locks while holding `sparse::STATE`. +pub(super) struct PreparedSync { + checked: Vec<(usize, bool, usize, u16)>, +} + +/// Phase 1 of GPU-view sync (called BEFORE locking `sparse::STATE`): snapshot candidate tiles +/// under `MIRRORS`, drop `MIRRORS`, and query `kernelx` backing mappings with no locks held. +pub(super) unsafe fn prepare_sync() -> Option { + let look: Vec<(usize, bool)> = { + let mut g = MIRRORS.lock().unwrap(); + let m = g.as_mut().filter(|m| m.tiles() != 0)?; + let gen = crate::hle::kernelx::gpu_view_map_gen(); + let titles: Vec = m.read.keys().copied().collect(); + let picked: Vec = if std::mem::replace(&mut m.gen, gen) != gen { + titles + } else { + let n = titles.len().max(1); + (0..SWEEP_PER_SUBMIT.min(titles.len())).map(|i| titles[(m.turn + i) % n]).collect() + }; + m.turn = m.turn.wrapping_add(SWEEP_PER_SUBMIT); + picked.into_iter().map(|t| (t, m.backed.contains(&t))).collect() + }; + let mut checked = Vec::with_capacity(look.len()); + for (t, was_backed) in look { + let (dead, r) = check_title_tile(t, was_backed); + let holes = if !dead && !was_backed { query_tile_holes(r) } else { 0xFFFF }; + checked.push((t, dead, r, holes)); + } + Some(PreparedSync { checked }) +} + +/// Phase 2 of GPU-view sync (`before_execute`; `s` is the locked `sparse::STATE`): apply +/// pre-checked liveness/remap updates and upload dirty mirrored pages with zero `kernelx` locks. +pub(super) unsafe fn apply_sync(s: &mut State, dirty: &[usize], prepared: Option) { let mut g = MIRRORS.lock().unwrap(); let Some(m) = g.as_mut().filter(|m| m.tiles() != 0) else { return }; m.epoch = m.epoch.wrapping_add(1); - let gen = crate::hle::kernelx::gpu_view_map_gen(); - let titles: Vec = m.read.keys().copied().collect(); - let look: Vec = if std::mem::replace(&mut m.gen, gen) != gen { - titles - } else { - let n = titles.len().max(1); - (0..SWEEP_PER_SUBMIT.min(titles.len())).map(|i| titles[(m.turn + i) % n]).collect() - }; - m.turn = m.turn.wrapping_add(SWEEP_PER_SUBMIT); let mut dead_wins: Vec = Vec::new(); - for t in look { - let was_backed = m.backed.contains(&t); - let (dead, r) = check_title_tile(t, was_backed); - if dead { - dead_wins.extend(m.evict_title_if_idle(t)); - continue; - } - if !was_backed && query_tile_holes(r) != 0xFFFF { - m.backed.insert(t); + if let Some(prep) = prepared { + for (t, dead, r, holes) in prep.checked { + if !m.read.contains_key(&t) { + continue; + } + if dead { + dead_wins.extend(m.evict_title_if_idle(t)); + continue; + } + if holes != 0xFFFF { + m.backed.insert(t); + } + m.set_read(t, r); } - m.set_read(t, r); } if !dead_wins.is_empty() { let evicted = dead_wins.len(); @@ -634,4 +675,13 @@ mod tests { VirtualFree(window as *mut c_void, 0, MEM_RELEASE); } } + + #[test] + fn prepare_sync_does_not_require_state_lock() { + // Holding `sparse::STATE` on the current thread must not block `prepare_sync`, proving + // Phase 1 runs without `STATE` and cannot ABBA-deadlock against `kernelx::AWAY -> STATE`. + let _held = STATE.lock().unwrap(); + let prep = unsafe { prepare_sync() }; + let _ = prep; + } } From 6d7dcbb9abf8ff9c196acd008a4269d7a87a9cf4 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:58:14 +0100 Subject: [PATCH 135/258] D3D12.X: read non-UMA title_bytes safely via read_committed title_textures::title_bytes previously borrowed a raw slice for any readable address outside alias::in_space(at). Sparse reservations and title VirtualAlloc heaps outside the permanently-committed coherent UMA window can be concurrently decommitted by another thread between readable() and detile/hash reads, causing intermittent 0xc0000005 access violations. Borrow directly only inside uma.in_committed_window(at, len); read all other addresses via read_committed (ReadProcessMemory). Added unit test title_bytes_outside_uma_copies_safely_via_read_committed. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 326568ba6f..6b2b0e477c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1886,12 +1886,12 @@ unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> V out } -/// The title's bytes at `at`: where they are when all of them are readable (a copy first cost -/// as much as the detile of a video frame), else read page run by page run. +/// The title's bytes at `at`: borrowed directly only inside the permanently-committed coherent +/// UMA window; any other address (alias spaces, sparse reservations, or title heaps) can be +/// concurrently decommitted by another thread between a readability check and the read, so read +/// page run by page run via `read_committed` (`ReadProcessMemory`) without faulting. unsafe fn title_bytes(at: usize, len: usize) -> std::borrow::Cow<'static, [u8]> { - // (in a space of physical pages the title maps and unmaps them all the time, so a page can go - // away between the check and the read: `read_committed` copies without faulting) - if !crate::hle::kernelx::alias::in_space(at) && crate::gpu::shader::readable(at, len) { + if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(at, len)) { std::borrow::Cow::Borrowed(std::slice::from_raw_parts(at as *const u8, len)) } else { std::borrow::Cow::Owned(read_committed(at, len)) @@ -3367,4 +3367,15 @@ mod tests { } } } + + #[test] + fn title_bytes_outside_uma_copies_safely_via_read_committed() { + let mut buf = vec![0x5Au8; 4096]; + buf[0] = 0x11; + buf[4095] = 0xEE; + let got = unsafe { title_bytes(buf.as_ptr() as usize, buf.len()) }; + assert!(matches!(got, std::borrow::Cow::Owned(_)), "non-UMA allocations must copy via read_committed so concurrent decommits cannot fault"); + assert_eq!(got.len(), 4096); + assert_eq!((got[0], got[1], got[4095]), (0x11, 0x5A, 0xEE)); + } } From f42c5e268335eecabe2a98f35829ba9ad81029e5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:07:56 +0100 Subject: [PATCH 136/258] d3d12x: fix prelude/VRAM-io lifetime, snapshot RTV/DSV, expand water 1. Fix Wave 12 VRAM io / prelude lifecycle fault on async-compute + deferred dispatches: - Add read-only title_list::raw_segments() (no prelude_list_for side effect) and use it in list_x::deferred_segment and list_x::record_deferred so mid-recording inspection never builds/freezes preludes early or attaches own_alloc to a transient prelude command list. - Add bind::rebind_allocator() after alloc_pool::reset_list in KickoffX and record_deferred, and resolve backing_allocator(to, allocator) in bind::inherit_for_split so in-flight io_blocks and prelude lists stay pinned to the true PC backing allocator until GPU completion. - Name internal prelude command lists/allocators ("xcl prelude") for DRED. 2. Snapshot CPU RTV/DSV descriptors at OMSetRenderTargets bind time into a per-device private CPU-only shadow pool (Arc, lock-free in-place reuse when unshared, Drop recycling, XCL_RT_SNAPSHOT=0 opt-out) so mid-list splits and KickoffX resets never replay overwritten guest slots. 3. Expand ocean water readback to all 4 verified single-mip 2D textures: 256x256 R32_FLOAT/R32G32_FLOAT, 64x64 R32G32_FLOAT, and 128x128 R16G16_UINT. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 46 ++- crates/xcl/src/hle/d3d12x/cpu_writes.rs | 66 ++-- crates/xcl/src/hle/d3d12x/device_x.rs | 12 +- crates/xcl/src/hle/d3d12x/list_x.rs | 401 ++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/title_list.rs | 28 +- 5 files changed, 491 insertions(+), 62 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index fad492f490..28d9ca770c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -534,15 +534,49 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { }); } +/// Update `list`'s tracked backing allocator after `alloc_pool::reset_list` rotates `list` onto a +/// fresh PC command allocator (e.g., `KickoffX` or `record_deferred`), retiring any prior +/// recording buffers on the old allocator first. +pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { + let backing = backing_allocator(list, allocator); + let (old, blocks, res_bufs, io_blocks, prelude) = with(list, |s| { + if s.allocator == backing { + return (0, Vec::new(), Vec::new(), Vec::new(), None); + } + let old = std::mem::replace(&mut s.allocator, backing); + s.arena = Default::default(); + s.scratch = Default::default(); + s.scratch_next = 0; + s.scratch_taken = 0; + s.prelude_scratch = Default::default(); + s.prelude_bufs.clear(); + s.prelude_guards.clear(); + s.prelude_scales.clear(); + let prelude = s.prelude_owned.take(); + s.prelude_built = None; + s.dummy_res_va = 0; + s.io_cache_gfx = None; + s.io_cache_cs = None; + s.io_cache_tp_cs = None; + s.io_cache_tp_ms = None; + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } + let io_blocks = std::mem::take(&mut s.io_blocks); + (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude) + }); + console_list::hold_until_reset(old, blocks); + hold_res_until_reset(old, res_bufs); + hold_io_until_reset(old, io_blocks); + hold_prelude_until_reset(old, prelude); +} + /// Carry bound pipeline and root-signature / root-argument state from `from` to `to` across a /// deferred mid-list split (`to` records into `allocator` with its own fresh UMA arena while /// `from` retains its previously allocated blocks until `allocator` resets). pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { - let backing = if allocator != 0 && super::alloc_pool::enabled() { - super::alloc_pool::current(allocator) - } else { - allocator - }; + let backing = backing_allocator(to, allocator); let (layout, args, layout_gfx, args_gfx, rs_gfx, rs_cs, pso, heaps) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.rs_cs, s.pso, s.heaps) }); @@ -1809,7 +1843,9 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { } None => { let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).map_err(|e| format!("prelude allocator create: {e}"))?; + let _ = a.SetName(windows::core::w!("xcl prelude alloc")); let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &a, None).map_err(|e| format!("prelude list create: {e}"))?; + let _ = l.SetName(windows::core::w!("xcl prelude")); (a, l) } }; diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 1d71da1657..b245384115 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -16,34 +16,42 @@ use std::sync::{mpsc, Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D12::*; -use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32_FLOAT}; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_FORMAT_R16G16_UINT, DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32_FLOAT}; use windows_sys::Win32::System::Threading as th; use crate::hle::xg; -/// `XCL_WATER_READBACK=0`: disable GPU->UMA readback of 256×256 `R32_FLOAT` / `R32G32_FLOAT` -/// placed ocean height/displacement textures. +/// `XCL_WATER_READBACK=0`: disable GPU->UMA readback of placed ocean height/displacement/buoyancy +/// textures (`256×256` `R32_FLOAT`/`R32G32_FLOAT`, `64×64` `R32G32_FLOAT`, `128×128` `R16G16_UINT`). pub(super) fn water_readback_enabled() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| std::env::var("XCL_WATER_READBACK").map_or(true, |v| v.trim() != "0")) } -/// Whether `desc` is a 256×256 single-mip 2D `R32_FLOAT` or `R32G32_FLOAT` texture (ocean -/// heightmap / displacement readback target used by CPU boat/water physics). +/// Whether `desc` matches one of the 4 verified single-mip 2D ocean height/displacement/buoyancy +/// readback textures used by CPU water/boat physics: +/// - `256×256` `R32_FLOAT` (`41`) or `R32G32_FLOAT` (`16`) +/// - `64×64` `R32G32_FLOAT` (`16`) +/// - `128×128` `R16G16_UINT` (`36`) pub(super) fn is_water_readback_desc(desc: &D3D12_RESOURCE_DESC) -> bool { desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D - && desc.Width == 256 - && desc.Height == 256 && desc.DepthOrArraySize == 1 && desc.MipLevels == 1 && desc.SampleDesc.Count <= 1 - && matches!(desc.Format, DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_R32G32_FLOAT) + && matches!( + (desc.Width, desc.Height, desc.Format), + (256, 256, DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_R32G32_FLOAT) + | (64, 64, DXGI_FORMAT_R32G32_FLOAT) + | (128, 128, DXGI_FORMAT_R16G16_UINT) + ) } #[derive(Clone)] pub(super) struct WaterTarget { pub va: usize, pub format: DXGI_FORMAT, + pub width: u32, + pub height: u32, pub row_pitch: u32, pub tex: Arc, } @@ -55,18 +63,21 @@ pub(super) fn has_water_readback() -> bool { HAS_WATER_TARGETS.load(Ordering::Acquire) } -pub(super) fn register_water_readback(res: usize, va: usize, format: DXGI_FORMAT, tex: Arc) { +pub(super) fn register_water_readback(res: usize, va: usize, format: DXGI_FORMAT, width: u32, height: u32, tex: Arc) { if !water_readback_enabled() || res == 0 || va == 0 { return; } - let row_pitch = match format { - DXGI_FORMAT_R32_FLOAT => 256 * 4, - DXGI_FORMAT_R32G32_FLOAT => 256 * 8, + let bpe: u32 = match format { + DXGI_FORMAT_R32_FLOAT | DXGI_FORMAT_R16G16_UINT => 4, + DXGI_FORMAT_R32G32_FLOAT => 8, _ => return, }; + let Some(row_bytes) = width.checked_mul(bpe) else { return }; + // Align to D3D12_TEXTURE_DATA_PITCH_ALIGNMENT (256 B); all 4 verified formats are exact multiples. + let row_pitch = row_bytes.next_multiple_of(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT); WATER_TARGETS.lock().unwrap().get_or_insert_with(HashMap::new).insert( res, - WaterTarget { va, format, row_pitch, tex }, + WaterTarget { va, format, width, height, row_pitch, tex }, ); HAS_WATER_TARGETS.store(true, Ordering::Release); } @@ -369,7 +380,8 @@ unsafe fn write_texture_now(dst_va: usize, format: DXGI_FORMAT, row_pitch: u32, static COUNT: AtomicU64 = AtomicU64::new(0); let n = COUNT.fetch_add(1, Ordering::Relaxed) + 1; if n == 1 || (n.is_power_of_two() && n >= 64) { - crate::xlog_info!("D3D12.X: water heightmap readback #{n} (256x256 fmt {}, -> {target_va:#x}, {dst_bytes} B)", format.0); + let (w, h) = surface.chain.levels.first().map_or((0, 0), |l| (l.width, l.height)); + crate::xlog_info!("D3D12.X: water heightmap readback #{n} ({w}x{h} fmt {}, -> {target_va:#x}, {dst_bytes} B)", format.0); } } } @@ -507,7 +519,7 @@ mod tests { } #[test] - fn water_readback_desc_matches_256_float_heightmaps_only() { + fn water_readback_desc_matches_verified_water_textures_only() { let base = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 256, @@ -520,6 +532,10 @@ mod tests { }; assert!(is_water_readback_desc(&base)); assert!(is_water_readback_desc(&D3D12_RESOURCE_DESC { Format: DXGI_FORMAT_R32G32_FLOAT, ..base })); + assert!(is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 64, Height: 64, Format: DXGI_FORMAT_R32G32_FLOAT, ..base })); + assert!(is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 128, Height: 128, Format: DXGI_FORMAT_R16G16_UINT, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 64, Height: 64, Format: DXGI_FORMAT_R32_FLOAT, ..base })); + assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 256, Height: 256, Format: DXGI_FORMAT_R16G16_UINT, ..base })); assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM, ..base })); assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { Width: 512, ..base })); assert!(!is_water_readback_desc(&D3D12_RESOURCE_DESC { MipLevels: 2, ..base })); @@ -528,22 +544,28 @@ mod tests { } #[test] - fn tile_readback_roundtrips_256_r32_and_r32g32_heightmaps() { - for (fmt, bpe) in [(DXGI_FORMAT_R32_FLOAT.0 as u32, 4usize), (DXGI_FORMAT_R32G32_FLOAT.0 as u32, 8usize)] { + fn tile_readback_roundtrips_all_verified_water_textures() { + for (dim, fmt, bpe) in [ + (256u32, DXGI_FORMAT_R32_FLOAT.0 as u32, 4usize), + (256u32, DXGI_FORMAT_R32G32_FLOAT.0 as u32, 8usize), + (64u32, DXGI_FORMAT_R32G32_FLOAT.0 as u32, 8usize), + (128u32, DXGI_FORMAT_R16G16_UINT.0 as u32, 4usize), + ] { let mut x = [0u8; 0x38]; x[0..4].copy_from_slice(&(D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 as u32).to_le_bytes()); - x[0x10..0x18].copy_from_slice(&256u64.to_le_bytes()); - x[0x18..0x1C].copy_from_slice(&256u32.to_le_bytes()); + x[0x10..0x18].copy_from_slice(&(dim as u64).to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&dim.to_le_bytes()); x[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); x[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); x[0x20..0x24].copy_from_slice(&fmt.to_le_bytes()); x[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); x[0x2C..0x30].copy_from_slice(&0x11Bu32.to_le_bytes()); // console swizzle 64KB_R_X (0x100 | 27) - let tex = xg::Texture::new(&x).expect("256x256 console texture layout"); + let tex = xg::Texture::new(&x).expect("console water texture layout"); let (_, surface) = main_surface(&tex).expect("main color surface"); - let linear: Vec = (0..(256 * 256 * bpe)).map(|i| ((i * 31 + 17) & 0xFF) as u8).collect(); + let n = dim as usize; + let linear: Vec = (0..(n * n * bpe)).map(|i| ((i * 31 + 17) & 0xFF) as u8).collect(); let mut tiled = vec![0u8; surface.chain.slice_bytes]; - assert!(tile_readback_into_slice(&mut tiled, &linear, (256 * bpe) as u32, &tex)); + assert!(tile_readback_into_slice(&mut tiled, &linear, (n * bpe) as u32, &tex)); assert_eq!(surface.chain.detile_level(&tiled, 0, 0), linear); } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index a548f13dfd..4ab93e9a44 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1128,7 +1128,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); let mut placed_hr = None; let mut pc_tex_desc: Option = None; - let mut water_tex: Option<(windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, crate::hle::xg::Texture)> = None; + let mut water_tex: Option<(windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, u32, u32, crate::hle::xg::Texture)> = None; if !buffer { let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); pc_tex_desc = Some(pc); @@ -1137,7 +1137,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, let console_bytes = xg_tex.as_ref().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); if console_bytes.is_some() && super::cpu_writes::is_water_readback_desc(&pc) { if let Some(t) = xg_tex { - water_tex = Some((pc.Format, t)); + water_tex = Some((pc.Format, pc.Width as u32, pc.Height, t)); } } drop(timer); @@ -1150,8 +1150,8 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, real::note_title_address(*ppv as usize, va as usize); super::depth_uav::register_if_depth_uav(this, *ppv, &x, state, console_state); super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); - if let Some((fmt, t)) = water_tex { - super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, std::sync::Arc::new(t)); + if let Some((fmt, w, h, t)) = water_tex { + super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, w, h, std::sync::Arc::new(t)); } else if super::cpu_writes::has_water_readback() { super::cpu_writes::unregister_water_readback(*ppv as usize); } @@ -1170,8 +1170,8 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, } }; if hr >= 0 && !buffer && !(*ppv).is_null() { - if let Some((fmt, t)) = water_tex { - super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, std::sync::Arc::new(t)); + if let Some((fmt, w, h, t)) = water_tex { + super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, w, h, std::sync::Arc::new(t)); } else if super::cpu_writes::has_water_readback() { super::cpu_writes::unregister_water_readback(*ppv as usize); } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 7d8820f2fc..2d8a67830c 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -21,7 +21,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Condvar, LazyLock, Mutex, OnceLock}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, OnceLock}; use std::time::{Duration, Instant}; use windows::core::Interface; @@ -387,16 +387,114 @@ impl PendingWait { } } -/// Recorded `OMSetRenderTargets` state for `KickoffX` restoration and `XCL_TRACE_FRAME`. +/// Number of per-list `(8 RTV + 1 DSV)` shadow slots per allocated CPU descriptor heap chunk. +const RT_SHADOW_CHUNK_SLOTS: u32 = 256; + +fn rt_snapshot_enabled() -> bool { + static ENABLED: OnceLock = OnceLock::new(); + *ENABLED.get_or_init(|| std::env::var("XCL_RT_SNAPSHOT").map(|v| v != "0").unwrap_or(true)) +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +struct RtShadowEntry { + rtv_base: usize, + rtv_inc: usize, + dsv_handle: usize, +} + +struct RtShadowPool { + /// Private CPU-only RTV/DSV descriptor heaps kept alive for the device's lifetime so copied + /// handles remain valid across mid-recording splits and `KickoffX` resets. + _heaps: Vec<(ID3D12DescriptorHeap, ID3D12DescriptorHeap)>, + free: Vec, +} + +static RT_SHADOW_POOLS: Mutex>> = Mutex::new(None); + +/// Owned slot in a device's private CPU-only RTV/DSV shadow heaps. +/// +/// D3D12 consumes CPU RTV/DSV descriptors synchronously when `OMSetRenderTargets` is recorded, +/// so recycling the slot on `Drop` (once every `Bindings` clone referencing it is gone) needs no +/// GPU fence wait. +#[derive(Debug, PartialEq, Eq)] +struct RtShadowSlot { + dev_key: usize, + entry: RtShadowEntry, +} + +impl Drop for RtShadowSlot { + fn drop(&mut self) { + let mut g = RT_SHADOW_POOLS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(pool) = g.as_mut().and_then(|m| m.get_mut(&self.dev_key)) { + pool.free.push(self.entry); + } + } +} + +unsafe fn alloc_rt_shadow_slot(dev: &ID3D12Device) -> Option> { + let dev_key = dev.as_raw() as usize; + { + let mut g = RT_SHADOW_POOLS.lock().unwrap(); + if let Some(entry) = g.as_mut().and_then(|m| m.get_mut(&dev_key)).and_then(|p| p.free.pop()) { + return Some(Arc::new(RtShadowSlot { dev_key, entry })); + } + } + let rtv_desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: RT_SHADOW_CHUNK_SLOTS * D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }; + let dsv_desc = D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: RT_SHADOW_CHUNK_SLOTS, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }; + let rtv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&rtv_desc).ok()?; + let dsv_heap: ID3D12DescriptorHeap = dev.CreateDescriptorHeap(&dsv_desc).ok()?; + let rtv_start = rtv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let dsv_start = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let rtv_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let dsv_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + if rtv_start == 0 || dsv_start == 0 || rtv_inc == 0 || dsv_inc == 0 { + return None; + } + let slots_per_rtv = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize; + let mut new_entries = Vec::with_capacity(RT_SHADOW_CHUNK_SLOTS as usize); + for i in 0..RT_SHADOW_CHUNK_SLOTS as usize { + new_entries.push(RtShadowEntry { + rtv_base: rtv_start + i * slots_per_rtv * rtv_inc, + rtv_inc, + dsv_handle: dsv_start + i * dsv_inc, + }); + } + let entry = new_entries.pop()?; + let mut g = RT_SHADOW_POOLS.lock().unwrap(); + let pool = g.get_or_insert_with(HashMap::new).entry(dev_key).or_insert_with(|| RtShadowPool { + _heaps: Vec::new(), + free: Vec::new(), + }); + pool._heaps.push((rtv_heap, dsv_heap)); + pool.free.extend(new_entries); + Some(Arc::new(RtShadowSlot { dev_key, entry })) +} + +/// Recorded `OMSetRenderTargets` state for `KickoffX` / split restoration and `XCL_TRACE_FRAME`. #[derive(Clone, Debug, PartialEq, Eq)] struct RenderTargets { /// Requested `NumRenderTargetDescriptors` (clamped to D3D12 max 8; 0 if `handles` is empty). num_targets: u32, - /// Saved descriptor handles: 1 base handle when `single != 0` and `num_targets > 0`, + /// Saved guest descriptor handles: 1 base handle when `single != 0` and `num_targets > 0`, /// otherwise `num_targets` handles. handles: Vec, single: i32, dsv: Option, + /// Private CPU-descriptor snapshot taken at bind time so later mid-list splits and + /// `KickoffX` resets never replay a guest RTV/DSV slot the title already overwrote. + shadow: Option>, + shadow_has_rtvs: bool, + shadow_has_dsv: bool, } /// What console code set on a list that a PC Reset clears: `KickoffX` closes, submits and @@ -651,7 +749,97 @@ pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const // handle when `RTsSingleHandleToDescriptorRange != 0` or `num_targets` handles otherwise. let handles = if read_count == 0 { Vec::new() } else { std::slice::from_raw_parts(rtvs, read_count).to_vec() }; let d = dsv.as_ref().copied(); - with_bindings(this, |b| b.render_targets = Some(RenderTargets { num_targets, handles, single, dsv: d })); + + let want_rtv = num_targets > 0 && !handles.is_empty() && handles.iter().all(|&h| h != 0); + let want_dsv = d.is_some_and(|dh| dh != 0); + + // Check whether `this` is a tracked real D3D12 command list (fake test lists never call + // `on_create`, so `list_type` is `None` and we must not invoke COM `GetDevice` on them). + // When this list already owns an unshared shadow slot (`strong_count == 1`), detach it for + // lock-free in-place reuse outside `LISTS`. + let (is_real_list, prev_slot) = if rt_snapshot_enabled() && (want_rtv || want_dsv) { + let mut g = LISTS.lock().unwrap(); + if let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) { + let real_list = s.list_type.is_some(); + let reuse = if real_list { + s.bindings + .render_targets + .as_mut() + .and_then(|rt| { + if rt.shadow.as_ref().is_some_and(|a| Arc::strong_count(a) == 1) { + rt.shadow.take() + } else { + None + } + }) + } else { + None + }; + (real_list, reuse) + } else { + (false, None) + } + } else { + (false, None) + }; + + let mut shadow: Option> = None; + let mut shadow_has_rtvs = false; + let mut shadow_has_dsv = false; + + if is_real_list { + if let Some(dev) = device_of(this) { + let dev_key = dev.as_raw() as usize; + let slot = match prev_slot { + Some(existing) if existing.dev_key == dev_key => Some(existing), + _ => alloc_rt_shadow_slot(&dev), + }; + if let Some(slot) = slot { + if want_rtv { + if single != 0 { + dev.CopyDescriptorsSimple( + num_targets, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: slot.entry.rtv_base }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: handles[0] }, + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + ); + } else { + for (i, &h) in handles.iter().enumerate() { + dev.CopyDescriptorsSimple( + 1, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: slot.entry.rtv_base + i * slot.entry.rtv_inc }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: h }, + D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + ); + } + } + shadow_has_rtvs = true; + } + if let Some(dh) = d.filter(|&dh| dh != 0) { + dev.CopyDescriptorsSimple( + 1, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: slot.entry.dsv_handle }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dh }, + D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + ); + shadow_has_dsv = true; + } + shadow = Some(slot); + } + } + } + + with_bindings(this, |b| { + b.render_targets = Some(RenderTargets { + num_targets, + handles, + single, + dsv: d, + shadow, + shadow_has_rtvs, + shadow_has_dsv, + }); + }); } /// Set again what `b` holds (after KickoffX's Reset or a deferred mid-list split). @@ -684,14 +872,26 @@ unsafe fn restore_bindings(this: *mut c_void, b: &Bindings, ty: D3D12_COMMAND_LI pc::(this, PC_IA_SET_VERTEX_BUFFERS)(this, slot, 1, v); } if let Some(rt) = &b.render_targets { - let d = rt.dsv.unwrap_or(0); - let (n, rts_ptr) = if rt.handles.is_empty() { (0, std::ptr::null()) } else { (rt.num_targets, rt.handles.as_ptr()) }; + let rtv_shadow_base = rt.shadow.as_ref().map_or(0, |slot| slot.entry.rtv_base); + let (n, rts_ptr, single) = if rt.shadow.is_some() && rt.shadow_has_rtvs && rt.num_targets > 0 { + (rt.num_targets, &rtv_shadow_base as *const usize, 1) + } else if rt.handles.is_empty() { + (0, std::ptr::null(), rt.single) + } else { + (rt.num_targets, rt.handles.as_ptr(), rt.single) + }; + let dsv_opt = if let Some(slot) = rt.shadow.as_ref().filter(|_| rt.shadow_has_dsv) { + Some(slot.entry.dsv_handle) + } else { + rt.dsv + }; + let d = dsv_opt.unwrap_or(0); pc::(this, PC_OM_SET_RENDER_TARGETS)( this, n, rts_ptr, - rt.single, - if rt.dsv.is_some() { &d } else { std::ptr::null() }, + single, + if dsv_opt.is_some() { &d } else { std::ptr::null() }, ); } } @@ -2839,7 +3039,7 @@ const WANTED_AT_ONCE: usize = 4; /// Records the deferred dispatches of `wrapper`'s recording, waiting for their pipelines as a bind did. pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { let mut segs = Vec::new(); - super::title_list::push_segments(wrapper, &mut segs); + super::title_list::raw_segments(wrapper, &mut segs); let Some(&first) = segs.first() else { return }; segs.retain(|&seg| seg == first || LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(seg as usize))).is_some_and(|s| s.deferred.is_some())); let mut last: Option<*mut c_void> = None; @@ -2870,6 +3070,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { super::bind::dispatch_dropped(); continue; } + super::bind::rebind_allocator(seg, own as usize); reset_copy_scratch(seg); super::dred::reset(seg); if !heaps.is_empty() { @@ -3144,7 +3345,7 @@ pub(super) unsafe fn split_for_prelude(list: *mut c_void) -> Option<*mut c_void> unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { let dev = device_of(list)?; let mut segs = Vec::new(); - super::title_list::push_segments(wrapper, &mut segs); + super::title_list::raw_segments(wrapper, &mut segs); let first = *segs.first()? as usize; let own = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&first)?.own_alloc.clone()); let own = match own { @@ -3433,16 +3634,20 @@ pub(super) unsafe fn before_close(list: *mut c_void) { } } -/// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. +/// Clear active predication and snapshotted render-target state when +/// `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); super::format_alias::list_reset(list as usize); - if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + if list.is_null() { return; } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { - s.predication = None; - s.pred_in_state = false; + s.bindings.render_targets = None; + if PREDICATION_USED.load(Ordering::Acquire) { + s.predication = None; + s.pred_in_state = false; + } } } @@ -3695,6 +3900,10 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } + // `alloc_pool::reset_list` can rotate `target` onto a fresh PC backing allocator because + // the pre-kickoff submit is now in flight; sync `bind`'s allocator so subsequent VRAM `io` + // slabs and prelude lists stay pinned to the new backing allocator rather than the old one. + super::bind::rebind_allocator(target, alloc); reset_copy_scratch(target); // `KickoffX` calls PC `Reset` directly (bypassing `real::cl_reset`), so rotate DRED markers here. super::dred::reset(target); @@ -5037,16 +5246,17 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v pc::(this, PC_RESOLVE_SUBRESOURCE_REGION)(this, dst, dst_sub, x, y, src, src_sub, rect, format, mode) } -/// If `dst` is a tracked 256×256 `R32_FLOAT` / `R32G32_FLOAT` placed ocean height/displacement -/// texture, copy subresource 0 into a pooled `READBACK` buffer and queue asynchronous XOR-swizzled -/// writeback into console memory on `xcl-cpu-writes` after this submission's GPU fence completes. +/// If `dst` is a tracked placed ocean height/displacement/buoyancy texture (`256×256` +/// `R32_FLOAT`/`R32G32_FLOAT`, `64×64` `R32G32_FLOAT`, or `128×128` `R16G16_UINT`), copy +/// subresource 0 into a pooled `READBACK` buffer and queue asynchronous XOR-swizzled writeback +/// into console memory on `xcl-cpu-writes` after this submission's GPU fence completes. unsafe fn maybe_enqueue_water_readback(this: *mut c_void, dst: usize) { let Some(target) = super::cpu_writes::water_readback_target(dst) else { return }; if list_type(this) == D3D12_COMMAND_LIST_TYPE_BUNDLE { return; } let Some(dev) = device_of(this) else { return }; - let total_bytes = u64::from(target.row_pitch) * 256; + let total_bytes = u64::from(target.row_pitch) * u64::from(target.height); let Some(rb) = super::cpu_writes::take_water_readback_buf(&dev, total_bytes) else { return }; let Some(rb_res) = rb.buf.as_ref() else { return }; let src_loc = D3D12_TEXTURE_COPY_LOCATION { @@ -5062,8 +5272,8 @@ unsafe fn maybe_enqueue_water_readback(this: *mut c_void, dst: usize) { Offset: 0, Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: target.format, - Width: 256, - Height: 256, + Width: target.width, + Height: target.height, Depth: 1, RowPitch: target.row_pitch, }, @@ -8333,4 +8543,155 @@ mod tests { on_release(list); assert!(!real::dispatch_chain::has_shared_for_test(list)); } + + #[test] + fn render_target_snapshot_survives_guest_slot_overwrite_and_recycles() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; + use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4}; + + unsafe { + let Ok(fac) = CreateDXGIFactory1::() else { + return; + }; + let Ok(warp) = fac.EnumWarpAdapter::() else { + return; + }; + let mut dev: Option = None; + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() { + return; + } + let dev = dev.unwrap(); + let dev_key = dev.as_raw() as usize; + + let tex_desc = |format, flags| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 16, + Height: 16, + DepthOrArraySize: 1, + MipLevels: 1, + Format: format, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: flags, + ..Default::default() + }; + let make_tex = |format, flags, state| -> ID3D12Resource { + let mut r: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &tex_desc(format, flags), + state, + None, + &mut r, + ) + .unwrap(); + r.unwrap() + }; + let rt_a = make_tex(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RENDER_TARGET); + let rt_b = make_tex(DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, D3D12_RESOURCE_STATE_RENDER_TARGET); + let ds_a = make_tex(DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_RESOURCE_STATE_DEPTH_WRITE); + let ds_b = make_tex(DXGI_FORMAT_D32_FLOAT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, D3D12_RESOURCE_STATE_DEPTH_WRITE); + + let rtv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, + NumDescriptors: 2, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }) + .unwrap(); + let dsv_heap: ID3D12DescriptorHeap = dev + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, + NumDescriptors: 1, + Flags: D3D12_DESCRIPTOR_HEAP_FLAG_NONE, + NodeMask: 0, + }) + .unwrap(); + let rtv_inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let rtv0 = rtv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + let rtv1 = rtv0 + rtv_inc; + let dsv0 = dsv_heap.GetCPUDescriptorHandleForHeapStart().ptr; + dev.CreateRenderTargetView(&rt_a, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: rtv0 }); + dev.CreateRenderTargetView(&rt_b, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: rtv1 }); + dev.CreateDepthStencilView(&ds_a, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dsv0 }); + + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + let raw = list.as_raw(); + real::adopt(raw, real::Kind::CommandList); + on_create(raw, alloc.as_raw() as usize, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + + // 1. Separate-handle MRT + DSV bind creates a private shadow snapshot. + let handles = [rtv0, rtv1]; + note_render_targets(raw, 2, handles.as_ptr(), 0, &dsv0); + let split_clone = LISTS.lock().unwrap().as_ref().unwrap().get(&(raw as usize)).unwrap().bindings.clone(); + let rt_snap = split_clone.render_targets.as_ref().expect("render_targets recorded"); + assert!(rt_snap.shadow_has_rtvs && rt_snap.shadow_has_dsv); + let first_entry = rt_snap.shadow.as_ref().expect("shadow slot allocated").entry; + assert_ne!(first_entry.rtv_base, rtv0); + assert_ne!(first_entry.dsv_handle, dsv0); + + // Overwrite the guest RTV/DSV slots with different resources, then restore the split clone. + dev.CreateRenderTargetView(&rt_b, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: rtv0 }); + dev.CreateDepthStencilView(&ds_b, None, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dsv0 }); + restore_bindings(raw, &split_clone, D3D12_COMMAND_LIST_TYPE_DIRECT); + + // 2. While `split_clone` holds a reference (`strong_count == 2`), rebinding on `raw` + // must allocate a distinct shadow slot rather than overwriting `split_clone`'s snapshot. + note_render_targets(raw, 1, &rtv0, 1, std::ptr::null()); + let second_entry = LISTS + .lock() + .unwrap() + .as_ref() + .unwrap() + .get(&(raw as usize)) + .unwrap() + .bindings + .render_targets + .as_ref() + .and_then(|rt| rt.shadow.as_ref()) + .expect("second shadow slot allocated") + .entry; + assert_ne!(second_entry.rtv_base, first_entry.rtv_base, "shared split snapshot must not be clobbered"); + + // 3. Rebinding again with `strong_count == 1` reuses the same shadow slot in place. + note_render_targets(raw, 0, std::ptr::null(), 0, &dsv0); + let reused = LISTS + .lock() + .unwrap() + .as_ref() + .unwrap() + .get(&(raw as usize)) + .unwrap() + .bindings + .render_targets + .clone() + .expect("depth-only recorded"); + assert!(!reused.shadow_has_rtvs && reused.shadow_has_dsv); + assert_eq!(reused.shadow.as_ref().unwrap().entry, second_entry, "unshared shadow slot should be reused in place"); + drop(reused); + + // 4. Restoring and closing the PC command list succeeds cleanly, and dropping all + // references recycles every shadow slot back to the pool. + let b_depth = LISTS.lock().unwrap().as_ref().unwrap().get(&(raw as usize)).unwrap().bindings.clone(); + restore_bindings(raw, &b_depth, D3D12_COMMAND_LIST_TYPE_DIRECT); + drop(b_depth); + drop(split_clone); + on_release(raw as usize); + + let ext = *(raw as *const *const usize); + *(raw as *mut usize) = *ext.sub(1); + list.Close().unwrap(); + + let free_count = RT_SHADOW_POOLS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&dev_key)) + .map_or(0, |p| p.free.len()); + assert_eq!(free_count, RT_SHADOW_CHUNK_SLOTS as usize, "all shadow slots must recycle on release"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index e2c068aab9..bcb184cb08 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -287,10 +287,11 @@ pub fn backing(list: *mut c_void) -> Option<*mut c_void> { unsafe { (*(list as *const usize) == vtable()).then(|| *((list as usize + F_PRIMARY) as *const *mut c_void)) } } -/// Expand a console list object into all of its recorded PC command list segments (in exact -/// recording order), inserting any hoisted indirect-argument prelude list right before the -/// segment that consumes it. Returns `false` if `list` is not a `title_list` wrapper. -pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { +/// Expand a console list object into its raw recorded PC command list segments (in exact +/// recording order) WITHOUT building or inserting prelude command lists. Use this for +/// read-only inspection (`deferred_segment`, `record_deferred`) so mid-recording queries never +/// freeze `prelude_list_for` early or mistake a prelude list for `wrapper`'s first segment. +pub fn raw_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { let Some(primary) = backing(list) else { return false; }; @@ -301,15 +302,24 @@ pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { let extras: Vec<*mut c_void> = book.map_or_else(Vec::new, |b| b.extra_active.iter().map(|&s| s as *mut c_void).collect()); (first, extras) }; - let push_with_prelude = |seg: *mut c_void, out: &mut Vec<*mut c_void>| { + out.push(first); + out.extend(extras); + true +} + +/// Expand a console list object into all of its recorded PC command list segments (in exact +/// recording order), inserting any hoisted indirect-argument / VRAM-io prelude list right before +/// the segment that consumes it. Returns `false` if `list` is not a `title_list` wrapper. +pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { + let mut raw = Vec::new(); + if !raw_segments(list, &mut raw) { + return false; + } + for seg in raw { if let Some(prelude) = unsafe { super::bind::prelude_list_for(seg) } { out.push(prelude); } out.push(seg); - }; - push_with_prelude(first, out); - for seg in extras { - push_with_prelude(seg, out); } true } From 123ef325e30740ef97a0efa7676b3b86b94a238d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:08:12 +0100 Subject: [PATCH 137/258] D3D12.X: default XCL_RT_GATE to hold without compiling and cap preload compile slots Eliminate the +12.2 GB commit spike, >90 s giant-shader compile stall, and 82-101 s foreground PSO starvation observed on world entry (100% cache-safe): - Extend XCL_RT_GATE in real.rs to three modes: hold (default, also 1/unset), auto (unlock on BVH builder dispatch), and 0/off/allow. In hold mode, maybe_rt_gated_compute_pso hands RT traversal (image_bvh*_intersect_ray) and RT companion compute shaders (e.g. 95cc13288a27a96e) a shared lightweight stand-in immediately via pso_async::submit_gated without translating, enqueueing, or calling CreateComputePipelineState (0 ms, 0 MB RAM). Also guard pso_async::resolve and resolve_spared so auto mode never enqueues bvh_traversal shaders before bvh_traversal_allowed(). Pairs cleanly with XCL_AMBIENT=auto (!bvh_traversal_allowed()). - Track wanted_waiters in real.rs Slots and pass is_preload_worker() to big_compile_turn_with so THREAD_PRIORITY_LOWEST xcl-pso-pre-* threads hold at most 1 slot per lane (*n == 0) and yield whenever any foreground wanted compile is waiting, keeping tight-commit slots immediately available for foreground two-pass MS PSO and compute compiles. - Add unit tests submit_gated_maps_driver_without_pending_or_enqueue, parse_rt_gate_mode coverage, and preload_never_takes_second_slot_or_starves_wanted_compile. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 48 +++++- crates/xcl/src/hle/d3d12x/real.rs | 204 +++++++++++++++++++++++-- 2 files changed, 241 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 4d6b738bb4..f564adf5fd 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1243,6 +1243,32 @@ impl Pending { } } +/// Register a permanently gated stand-in pipeline (e.g. RT compute held back under +/// `XCL_RT_GATE=hold`) with `done = true`, `job = None`, `sent = true`, and `real = 0`. +/// Never enqueues a worker job, never translates or calls `CreateComputePipelineState`, maps +/// `standin -> driver` cleanly via `stand()` for `SetPipelineState`/`resolve`/`resolve_wait`, +/// reports `is_pending(standin) == false`, and releases cleanly via `released()`. +pub fn submit_gated(standin: usize, driver: usize) { + let p = Arc::new(Pending { + job: Mutex::new(None), + sent: std::sync::atomic::AtomicBool::new(true), + real: AtomicUsize::new(0), + driver: AtomicUsize::new(driver), + done: Mutex::new(true), + cv: Condvar::new(), + compute: true, + key: 0, + used: Default::default(), + orphan: Default::default(), + late: std::sync::atomic::AtomicBool::new(true), + spared: std::sync::atomic::AtomicBool::new(false), + bvh_traversal: std::sync::atomic::AtomicBool::new(true), + deprioritized: std::sync::atomic::AtomicBool::new(true), + demand: Default::default(), + }); + PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p); +} + /// Stand-in `standin` is no driver object (`standin::shell`): binds get `driver` in its place. /// Told before the title has the stand-in. pub fn shared(standin: usize, driver: usize) { @@ -1258,8 +1284,12 @@ pub fn resolve(pso: usize) -> usize { p.note_use(); match p.real.load(Ordering::Acquire) { 0 => { - // a lazy one is wanted now: to the workers + // a lazy one is wanted now: to the workers (unless RT-gated while BVH traversal is + // held back, so gated RT shaders never enqueue or burn driver compile RAM) let stand = p.stand(pso); + if p.bvh_traversal.load(Ordering::Acquire) && !super::real::bvh_traversal_allowed() { + return stand; + } if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p); } @@ -1454,6 +1484,9 @@ static FRAME_WAIT: Mutex = Mutex::new(FrameWaitBudget::new()); fn resolve_spared(p: &Arc, pso: usize) -> usize { match p.real.load(Ordering::Acquire) { 0 => { + if p.bvh_traversal.load(Ordering::Acquire) && !super::real::bvh_traversal_allowed() { + return p.stand(pso); + } if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p.clone()); } @@ -1680,4 +1713,17 @@ mod pso_queue_tests { b.record(1, std::time::Duration::from_millis(5)); assert_eq!(b.remaining(2, cap), std::time::Duration::from_millis(12)); } + + #[test] + fn submit_gated_maps_driver_without_pending_or_enqueue() { + let standin = 0x7E57_9A7Eu64 as usize; + let driver = 0x7E57_D12Eu64 as usize; + submit_gated(standin, driver); + assert!(!is_pending(standin), "gated stand-in must not appear pending"); + assert_eq!(resolve(standin), driver); + assert_eq!(resolve_wait(standin), driver); + assert_eq!(resolve_for_bind(standin), driver); + assert_eq!(released(standin), 0); + assert_eq!(resolve(standin), standin); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 15477001d0..c37e3a1acb 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1919,14 +1919,45 @@ static BVH_BUILD_READY: std::sync::atomic::AtomicBool = std::sync::atomic::Atomi /// At least one `DispatchX(..., 0x20)` BVH builder PSO failed or stayed pending: gate stays closed. static BVH_BUILD_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +/// Policy for gating RT traversal (`image_bvh*_intersect_ray`) and RT companion compute shaders +/// (`XCL_RT_GATE`): +/// - `hold` / `1` / unset (default): hold RT shaders back without translating, enqueueing, or +/// compiling them (0 ms compile, 0 MB RAM, no unguarded null-BVH traversal faults). Pairs +/// cleanly with `XCL_AMBIENT=auto` (`!bvh_traversal_allowed()`). +/// - `auto`: hold back RT shaders until a `DispatchX(..., 0x20)` BVH builder pass succeeds with +/// zero failed builder PSOs. +/// - `0` / `off` / `allow`: disable gating; compile and run RT shaders freely. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RtGateMode { + Off, + Auto, + Hold, +} + +fn parse_rt_gate_mode(raw: Option<&str>) -> RtGateMode { + match raw.map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("0" | "off" | "false" | "allow") => RtGateMode::Off, + Some("auto") => RtGateMode::Auto, + _ => RtGateMode::Hold, + } +} + +fn rt_gate_mode() -> RtGateMode { + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| parse_rt_gate_mode(std::env::var("XCL_RT_GATE").ok().as_deref())) +} + fn bvh_gate_enabled() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_RT_GATE").map_or(true, |v| v.trim() != "0")) + rt_gate_mode() != RtGateMode::Off } /// Whether BVH traversal compute shaders (`image_bvh*_intersect_ray`) are allowed to run. pub(super) fn bvh_traversal_allowed() -> bool { - !bvh_gate_enabled() || (BVH_BUILD_READY.load(Ordering::Acquire) && !BVH_BUILD_FAILED.load(Ordering::Acquire)) + match rt_gate_mode() { + RtGateMode::Off => true, + RtGateMode::Hold => false, + RtGateMode::Auto => BVH_BUILD_READY.load(Ordering::Acquire) && !BVH_BUILD_FAILED.load(Ordering::Acquire), + } } /// Whether any BVH builder pass failed (all-or-nothing gate disables further partial builds). @@ -1936,7 +1967,9 @@ pub(super) fn bvh_builder_failed() -> bool { pub(super) fn note_bvh_builder_dispatched() { if !BVH_BUILD_FAILED.load(Ordering::Acquire) && !BVH_BUILD_READY.swap(true, Ordering::AcqRel) { - crate::xlog_info!("D3D12.X: BVH builder dispatch ready — enabling RT traversal shaders"); + if rt_gate_mode() == RtGateMode::Auto { + crate::xlog_info!("D3D12.X: BVH builder dispatch ready — enabling RT traversal shaders"); + } } } @@ -4415,13 +4448,14 @@ enum SlotLimit { /// A counting semaphore: background driver compiles of big programs at once. struct Slots { n: Mutex, + wanted_waiters: AtomicUsize, cv: std::sync::Condvar, limit: SlotLimit, } impl Slots { const fn fixed(most: usize, wanted_most: usize) -> Self { - Self { n: Mutex::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Fixed(most, wanted_most) } + Self { n: Mutex::new(0), wanted_waiters: AtomicUsize::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Fixed(most, wanted_most) } } fn most(&self) -> usize { @@ -4450,15 +4484,46 @@ impl Drop for SlotGuard { } } +struct WantedWaiterGuard { + slots: &'static Slots, + registered: bool, +} + +impl WantedWaiterGuard { + fn new(slots: &'static Slots) -> Self { + Self { slots, registered: false } + } + + fn set(&mut self, active: bool) { + if active && !self.registered { + self.slots.wanted_waiters.fetch_add(1, Ordering::AcqRel); + self.registered = true; + } else if !active && self.registered { + self.slots.wanted_waiters.fetch_sub(1, Ordering::AcqRel); + self.registered = false; + } + } +} + +impl Drop for WantedWaiterGuard { + fn drop(&mut self) { + self.set(false); + } +} + const LARGE_DRIVER_COMPILE: usize = 512 << 10; -static MEDIUM_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Medium }; -static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Big }; +static MEDIUM_COMPILES: Slots = Slots { n: Mutex::new(0), wanted_waiters: AtomicUsize::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Medium }; +static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), wanted_waiters: AtomicUsize::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Big }; /// True giant DXIL shaders (`>= 900 KiB`, e.g. >1 MiB RT/compute shaders that can take >60-140s /// in the driver compiler) get their own dedicated 1-slot lane so they never starve `MEDIUM_COMPILES` /// (`256-512 KiB`) or `BIG_COMPILES` (`512-900 KiB`). const GIANT_DRIVER_COMPILE: usize = 900 << 10; static GIANT_COMPILES: Slots = Slots::fixed(1, 1); +fn is_preload_worker() -> bool { + std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso-pre-")) +} + fn compile_slots(bytes: usize) -> &'static Slots { if bytes >= GIANT_DRIVER_COMPILE { &GIANT_COMPILES @@ -4497,7 +4562,7 @@ fn pso_trace() -> bool { fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Option<(u64, bool)>, build: impl FnOnce() -> R) -> (R, std::time::Duration) { let huge = gate && bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); - let _slot = huge.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + let _slot = huge.then(|| big_compile_turn_with(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted, is_preload_worker())); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; @@ -4549,20 +4614,34 @@ fn gate_compute_driver_compile(has_isa_cached_blob: bool) -> bool { /// `slots.wanted_most()` (default 2 for `>= 256 KB`, 1 for `>= 4 MiB` giant shaders) so a wanted /// build is not stuck behind 1 background build while a burst of lazy binds still cannot spike /// driver compiler commit into OOM. +#[cfg(test)] fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool) -> SlotGuard { + big_compile_turn_with(slots, commit_free, wanted, false) +} + +fn big_compile_turn_with(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool, is_preload: bool) -> SlotGuard { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); + let mut waiter = WantedWaiterGuard::new(slots); let mut n = slots.n.lock().unwrap(); loop { let is_wanted = wanted(); + waiter.set(is_wanted); let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; let ok = if is_wanted { // Always allow the first 2 wanted slots (never deadlock under tight commit); extra // wanted slots on wider tiers (e.g. MEDIUM_COMPILES cap 4) require commit headroom. *n < cap && (*n < 2 || commit_free()) + } else if is_preload { + // Speculative `xcl-pso-pre-*` preload threads (`THREAD_PRIORITY_LOWEST`) may hold at + // most 1 slot in a lane (`*n == 0`) and yield whenever any foreground `wanted` compile + // is waiting or commit headroom is tight — leaving >= 1 tight-commit slot (and all + // extra wanted slots) exclusively for foreground compiles like two-pass MS PSOs. + *n == 0 && slots.wanted_waiters.load(Ordering::Acquire) == 0 && commit_free() } else { - *n < cap && commit_free() + *n < cap && slots.wanted_waiters.load(Ordering::Acquire) == 0 && commit_free() }; if ok { + waiter.set(false); *n += 1; return SlotGuard(slots); } @@ -4707,6 +4786,36 @@ mod big_compile_tests { assert_eq!(parsed.len(), 2); assert!(is_rt_gated_cs(b"HDR\0CS_RaytracingResolve_01\0")); assert!(is_rt_gated_cs(b"HDR\0CS_IrradianceCache_Shade_Low\0")); + assert_eq!(parse_rt_gate_mode(None), RtGateMode::Hold); + assert_eq!(parse_rt_gate_mode(Some("")), RtGateMode::Hold); + assert_eq!(parse_rt_gate_mode(Some("1")), RtGateMode::Hold); + assert_eq!(parse_rt_gate_mode(Some("hold")), RtGateMode::Hold); + assert_eq!(parse_rt_gate_mode(Some("AUTO")), RtGateMode::Auto); + assert_eq!(parse_rt_gate_mode(Some("0")), RtGateMode::Off); + assert_eq!(parse_rt_gate_mode(Some("off")), RtGateMode::Off); + assert_eq!(parse_rt_gate_mode(Some("allow")), RtGateMode::Off); + } + + #[test] + fn preload_never_takes_second_slot_or_starves_wanted_compile() { + static S: Slots = Slots::fixed(3, 4); + let p1 = big_compile_turn_with(&S, || true, || false, true); + assert_eq!(*S.n.lock().unwrap(), 1); + // A second speculative preload compile must wait even though `most == 3`, so preload + // never occupies both tight-commit slots (`*n < 2`) and starves foreground builds. + let p2 = std::thread::spawn(|| { + let _g = big_compile_turn_with(&S, || true, || false, true); + }); + std::thread::sleep(Duration::from_millis(120)); + assert!(!p2.is_finished(), "second preload compile must wait behind the first"); + // A foreground wanted compile enters immediately even when commit headroom is tight! + let t0 = Instant::now(); + let w1 = big_compile_turn_with(&S, || false, || true, false); + assert!(t0.elapsed() < Duration::from_secs(1), "wanted compile must not wait behind preload"); + assert_eq!(*S.n.lock().unwrap(), 2); + drop((w1, p1)); + p2.join().unwrap(); + assert_eq!(*S.n.lock().unwrap(), 0); } #[test] @@ -4840,6 +4949,11 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const if !is_console(cs) { return None; } + // Under `XCL_RT_GATE=hold` (default), RT traversal and RT companion shaders are held back + // without translating or compiling on the driver (belt-and-suspenders guard for direct paths). + if rt_gate_mode() == RtGateMode::Hold && is_rt_gated_cs(cs) { + return Some(Err(())); + } // made when first bound (`pso_async::lazy`): not even translated now if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return Some(Err(())); @@ -6408,9 +6522,79 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const hr } +/// When `XCL_RT_GATE` is in `Hold` mode (default), RT traversal and RT companion compute shaders +/// (`is_rt_gated_cs`) receive a lightweight stand-in pipeline immediately without translating, +/// enqueueing a worker job, or calling `CreateComputePipelineState` on the console shader. +/// Eliminates multi-minute / multi-GB driver compiles (e.g. >1 MiB ray-activation passes) and +/// prevents unguarded `image_bvh*_intersect_ray` dispatches from faulting before null-BVH guards +/// land. `is_translated_compute` stays `false` while `is_console_compute` is `true`, so `Dispatch` +/// and `ExecuteIndirect` skip them cleanly with zero work. +unsafe fn maybe_rt_gated_compute_pso( + this: *mut c_void, + f: PsoFn, + desc: *const c_void, + riid: *const GUID, + ppv: *mut *mut c_void, +) -> Option { + if rt_gate_mode() != RtGateMode::Hold { + return None; + } + if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::()) { + return None; + } + let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + let cs = shader_bytes(&d.CS)?; + if !crate::gpu::recomp::pso::is_console(cs) || !is_rt_gated_cs(cs) { + return None; + } + let key = if super::standin::enabled() && !ppv.is_null() { compute_key(this, desc) } else { None }; + let mut driver = 0usize; + let hr = match key { + Some(key) => { + let made = super::standin::shell(key, || { + let mut out = std::ptr::null_mut(); + let hr = standin_compute(this, f, desc, &pc_iid(Kind::PipelineState), &mut out); + if hr < 0 || out.is_null() { Err(hr) } else { Ok(out as usize) } + }); + match made { + Ok((shell, d)) => { + *ppv = shell; + driver = d; + S_OK + } + Err(hr) => hr, + } + } + None => standin_compute(this, f, desc, riid, ppv), + }; + if hr < 0 || ppv.is_null() || (*ppv).is_null() { + return None; + } + if driver != 0 { + super::pso_async::submit_gated(*ppv as usize, driver); + } + let record = crate::gpu::shader::fnv64(cs); + static GATED_COUNT: AtomicU64 = AtomicU64::new(0); + let n = GATED_COUNT.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: RT-gated compute PSO {record:016x} held back without compiling ({n} so far; XCL_RT_GATE=hold, set XCL_RT_GATE=auto or 0 to enable)" + ); + } + LAST_COMPUTE_TRANSLATED.with(|c| c.set(false)); + LAST_COMPUTE_RS.with(|c| c.set(0)); + note_compute_threads(*ppv as usize, cs); + note_bvh_traversal(*ppv as usize, cs); + note_console_compute(hr, ppv); + Some(hr) +} + unsafe fn create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { super::null::capture_compute_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); + if let Some(hr) = maybe_rt_gated_compute_pso(this, f, desc, riid, ppv) { + return hr; + } let (mut console, missed) = if super::pso_async::enabled() { attempt(|| translated_compute_pso(this, f, desc, riid, ppv)) } else { (translated_compute_pso(this, f, desc, riid, ppv), false) }; if missed { if let Some(hr) = own_compute(desc).and_then(|o| go_background(this, f, desc, riid, ppv, true, o, standin_compute, compute_key, build_compute)) { @@ -6698,7 +6882,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let bytes = stream.shader_bytes() + tp.cs.len(); let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); - let _slot = gate.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + let _slot = gate.then(|| big_compile_turn_with(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted, is_preload_worker())); if gate { crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated, waited {} ms", waited.elapsed().as_millis()); } From 2af01554a392c8c0069ad083f241b32a2d9e5f5e Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:16:14 +0100 Subject: [PATCH 138/258] D3D12.X: back unresolved outside-UMA GPU-writable buffers in sparse VRAM MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Buffers placed at GPU-view or outside-UMA addresses (0xc_..–0x13_..) where resolve_uma_va returns None previously fell back to plain committed resources and skipped gpu_view::base_for on UAVs (read_only=false), writing [0; 4] empty V# descriptors on screen-probe tile-classification UAVs and leaving final gather reading zeros. Add VRAM-only sparse allocation helpers (sparse::alloc_vram_only / free_vram_only with holes=0xFFFF so CPU write-watch never overwrites GPU UAV writes and zero CPU RAM commit is consumed) and a shared OutsideBufferTable in real.rs (XCL_OUTSIDE_BUFFER_MB, default 256 MiB, XCL_OUTSIDE_BUFFERS=0 disables): - place_at_title_address places GPU-writable outside-UMA buffers over shared sparse VRAM backings and registers them in UMA_BUFFERS (refcounted and reclaimed on res_release). - buffer_view and buffer_words_at allocate/pin shared VRAM-only backings for unresolved UAVs instead of returning empty V#s. - resolve_uma_va checks OutsideBufferTable right after UMA containment so subsequent SRVs, UAVs, CBVs, and root descriptors share the exact same GPU-writable sparse backing across sub-ranges. - Includes unit test outside_buffer_table_shares_uav_and_srv_subranges_and_reclaims_on_release. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 295 +++++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/sparse.rs | 38 ++++ 2 files changed, 323 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index c37e3a1acb..80c55a4f15 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1302,11 +1302,185 @@ fn resource_dim_to_view(r: &D3D12_RESOURCE_DESC) -> i32 { static NON_UMA_BUFFER_VIEWS: AtomicU64 = AtomicU64::new(0); static GPU_VIEW_BUFFER_HITS: AtomicU64 = AtomicU64::new(0); +/// Default total VRAM-only sparse backing cap for GPU-writable buffers placed at unresolved +/// addresses outside the UMA windows (`0xc_..–0x13_..` GPU views or outside-window reservations). +/// Override with `XCL_OUTSIDE_BUFFER_MB` (`0` or `XCL_OUTSIDE_BUFFERS=0` disables). +const OUTSIDE_BUFFER_DEFAULT_MB: usize = 256; +const OUTSIDE_BUFFER_MAX_ITEM: usize = 64 << 20; +const OUTSIDE_TILE: usize = 0x1_0000; + +fn outside_buffer_cap_bytes() -> usize { + static CAP: OnceLock = OnceLock::new(); + *CAP.get_or_init(|| { + if std::env::var("XCL_OUTSIDE_BUFFERS").is_ok_and(|v| v.trim() == "0") { + return 0; + } + std::env::var("XCL_OUTSIDE_BUFFER_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(OUTSIDE_BUFFER_DEFAULT_MB) + .saturating_mul(1 << 20) + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct OutsideEntry { + title_base: usize, + title_end: usize, + uma_base: usize, + refs: usize, + pinned_uav: bool, +} + +#[derive(Default)] +struct OutsideBufferTable { + entries: Vec, + total_bytes: usize, +} + +impl OutsideBufferTable { + fn lookup(&self, va: usize, len: usize) -> Option { + let end = va.checked_add(len)?; + self.entries + .iter() + .find(|e| e.title_base <= va && end <= e.title_end) + .map(|e| e.uma_base + (va - e.title_base)) + } + + fn retain_existing(&mut self, va: usize, len: usize, add_ref: bool, pin_uav: bool) -> Option<(usize, usize)> { + let end = va.checked_add(len)?; + let e = self.entries.iter_mut().find(|e| e.title_base <= va && end <= e.title_end)?; + if add_ref { + e.refs = e.refs.saturating_add(1); + } + if pin_uav { + e.pinned_uav = true; + } + Some((e.title_base, e.uma_base + (va - e.title_base))) + } + + fn can_insert(&self, title_base: usize, title_end: usize, cap_bytes: usize) -> bool { + if cap_bytes == 0 || title_end <= title_base { + return false; + } + let span = title_end - title_base; + if span > OUTSIDE_BUFFER_MAX_ITEM || self.total_bytes.saturating_add(span) > cap_bytes { + return false; + } + !self.entries.iter().any(|e| e.title_base < title_end && title_base < e.title_end) + } + + fn insert(&mut self, title_base: usize, title_end: usize, uma_base: usize, add_ref: bool, pin_uav: bool, cap_bytes: usize) -> bool { + if !self.can_insert(title_base, title_end, cap_bytes) { + return false; + } + self.total_bytes = self.total_bytes.saturating_add(title_end - title_base); + self.entries.push(OutsideEntry { + title_base, + title_end, + uma_base, + refs: usize::from(add_ref), + pinned_uav: pin_uav, + }); + true + } + + fn release_ref(&mut self, title_base: usize) -> Option { + let idx = self.entries.iter().position(|e| e.title_base == title_base)?; + let e = &mut self.entries[idx]; + e.refs = e.refs.saturating_sub(1); + if e.refs == 0 && !e.pinned_uav { + let gone = self.entries.swap_remove(idx); + self.total_bytes = self.total_bytes.saturating_sub(gone.title_end - gone.title_base); + Some(gone.uma_base) + } else { + None + } + } +} + +static OUTSIDE_BUFFERS: std::sync::RwLock = std::sync::RwLock::new(OutsideBufferTable { entries: Vec::new(), total_bytes: 0 }); +static OUTSIDE_RES: Mutex>> = Mutex::new(None); +static HAS_OUTSIDE_BUFFERS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn lookup_outside_buffer(va: usize, len: usize) -> Option { + if !HAS_OUTSIDE_BUFFERS.load(Ordering::Acquire) { + return None; + } + OUTSIDE_BUFFERS.read().unwrap().lookup(va, len) +} + +unsafe fn ensure_outside_buffer(va: usize, len: usize, add_ref: bool, pin_uav: bool) -> Option<(usize, usize)> { + let cap = outside_buffer_cap_bytes(); + if cap == 0 || va == 0 || len == 0 || len > OUTSIDE_BUFFER_MAX_ITEM { + return None; + } + if let Some(hit) = OUTSIDE_BUFFERS.write().unwrap().retain_existing(va, len, add_ref, pin_uav) { + return Some(hit); + } + let title_base = va & !(OUTSIDE_TILE - 1); + let title_end = va.checked_add(len)?.checked_next_multiple_of(OUTSIDE_TILE)?; + let span = title_end - title_base; + if !OUTSIDE_BUFFERS.read().unwrap().can_insert(title_base, title_end, cap) { + return None; + } + // Allocate VRAM-only sparse backing OUTSIDE `OUTSIDE_BUFFERS` lock (zero lock-order hazard). + let (uma_base, _) = super::sparse::alloc_vram_only(span, OUTSIDE_TILE)?; + let inserted = { + let mut t = OUTSIDE_BUFFERS.write().unwrap(); + if let Some(hit) = t.retain_existing(va, len, add_ref, pin_uav) { + drop(t); + super::sparse::free_vram_only(uma_base); + return Some(hit); + } + t.insert(title_base, title_end, uma_base, add_ref, pin_uav, cap) + }; + if !inserted { + super::sparse::free_vram_only(uma_base); + return None; + } + HAS_OUTSIDE_BUFFERS.store(true, Ordering::Release); + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: shared GPU-writable backing for outside-UMA buffer {va:#x} ({len} B) -> sparse UMA {:#x} (#{n})", + uma_base + (va - title_base) + ); + } + Some((title_base, uma_base + (va - title_base))) +} + +unsafe fn release_outside_ref(title_base: usize) { + let free_uma = OUTSIDE_BUFFERS.write().unwrap().release_ref(title_base); + if let Some(uma_base) = free_uma { + super::sparse::free_vram_only(uma_base); + } +} + +unsafe fn forget_outside_resource(res: usize) { + if !HAS_OUTSIDE_BUFFERS.load(Ordering::Relaxed) { + return; + } + let title_base = OUTSIDE_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&res)); + if let Some(tb) = title_base { + release_outside_ref(tb); + } +} + +fn is_gpu_writable_placed_buffer(d: &D3D12_RESOURCE_DESC, state: u32) -> bool { + const WRITABLE_STATES: u32 = D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 + | D3D12_RESOURCE_STATE_COPY_DEST.0 as u32 + | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32; + (d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0) || (state & WRITABLE_STATES != 0) +} + /// Resolve a console GPU virtual address range `[va, va + len)` to a shader-readable UMA address. /// Fast path: addresses already inside UMA return as-is. -/// Fallback: consults `kernelx::mirrors::mapped_source` (and paired CPU view `mirrors::source`), -/// verifying every 64 KiB page across `len` maps contiguously into UMA so direct zero-copy -/// SRV/CBV/UAV access never aliases scattered physical pages. +/// Fallback: checks shared GPU-writable outside-UMA backings (`OUTSIDE_BUFFERS`), then consults +/// `kernelx::mirrors::mapped_source` (and paired CPU view `mirrors::source`), verifying every +/// 64 KiB page across `len` maps contiguously into UMA so direct zero-copy SRV/CBV/UAV access +/// never aliases scattered physical pages. pub(super) fn resolve_uma_va(va: u64, len: usize) -> Option { if va == 0 { return None; @@ -1319,6 +1493,9 @@ pub(super) fn resolve_uma_va(va: u64, len: usize) -> Option { } return None; } + if let Some(mapped) = lookup_outside_buffer(start, len) { + return Some(mapped as u64); + } const MAX_CHECK: usize = 256 << 20; if len > MAX_CHECK { return None; @@ -1389,7 +1566,13 @@ fn buffer_view(res: usize, format: windows::Win32::Graphics::Dxgi::Common::DXGI_ let view_bytes = if stride == 0 { records } else { records.saturating_mul(stride as u64) } as usize; let target = (ta as u64).saturating_add(off); let resolved = resolve_uma_va(target, view_bytes) - .or_else(|| read_only.then(|| super::sparse::gpu_view::base_for(target as usize, view_bytes).map(|b| b as u64)).flatten()); + .or_else(|| { + if read_only { + super::sparse::gpu_view::base_for(target as usize, view_bytes).map(|b| b as u64) + } else { + unsafe { ensure_outside_buffer(target as usize, view_bytes, false, true).map(|(_, u)| u as u64) } + } + }); if let Some(base) = resolved { return crate::gpu::desc::buffer_words(base, stride, records as u32, fmt); } @@ -1593,36 +1776,83 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta /// title's allocation stays the title's. pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc: &[u8; 0x38], state: u32, clear: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option { let u = crate::gpu::uma::get()?; - let k = u.window_of(va)?; - let (base, size) = u.window(k); let mut d: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(desc.as_ptr() as *const D3D12_RESOURCE_DESC); let bytes = d.Width as usize; + if bytes == 0 { + return None; + } + let (va, outside_base) = match u.window_of(va) { + Some(_) => (va, None), + None => { + if let Some(resolved) = resolve_uma_va(va as u64, bytes) { + let tb = OUTSIDE_BUFFERS.write().unwrap().retain_existing(va, bytes, true, false).map(|(tb, _)| tb); + (resolved as usize, tb) + } else if u.has_sparse() && is_gpu_writable_placed_buffer(&d, state) { + let (tb, mapped) = ensure_outside_buffer(va, bytes, true, false)?; + (mapped, Some(tb)) + } else { + return None; + } + } + }; + let k = match u.window_of(va) { + Some(k) => k, + None => { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } + return None; + } + }; + let (base, size) = u.window(k); // a placed PC buffer starts at 64 KiB: one at another address starts below it and XCL adds // the difference where PC methods take an offset into it (`buffer_delta`) let start = va & !0xFFFF; let delta = va - start; - if bytes == 0 || va - base + bytes > size { + if va - base + bytes > size { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } return None; } // the title's own memory (a sparse window): a resource over its video-memory tiles if u.is_sparse(va) { - let (hr, delta) = super::sparse::place_buffer(this, va, &d, state, riid, ppv)?; + let Some((hr, delta)) = super::sparse::place_buffer(this, va, &d, state, riid, ppv) else { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } + return None; + }; UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + if let Some(tb) = outside_base { + OUTSIDE_RES.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, tb); + } if delta != 0 { BUFFER_DELTA.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } return Some(hr); } - let heap = (*UMA_HEAPS.lock().unwrap().get(k)?)?; + let Some(heap) = UMA_HEAPS.lock().unwrap().get(k).copied().flatten() else { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } + return None; + }; d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER; d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; d.Alignment = 0; d.Width = (delta + bytes) as u64; let hr = dev_create_placed_resource(this, heap, start - base, &d as *const _ as usize, state as usize, clear as usize, riid, ppv); if hr < 0 || (*ppv).is_null() { + if let Some(tb) = outside_base { + release_outside_ref(tb); + } return None; } UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false)); + if let Some(tb) = outside_base { + OUTSIDE_RES.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, tb); + } if delta != 0 { BUFFER_DELTA.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } @@ -1822,6 +2052,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { super::depth_uav::forget(this as usize); super::format_alias::forget(this as usize); super::ambient::forget_resource(this as usize); + forget_outside_resource(this as usize); let gone = UMA_BUFFERS.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { if u.is_sparse(p) { @@ -2695,7 +2926,13 @@ fn buffer_words_at(va: u64, format: windows::Win32::Graphics::Dxgi::Common::DXGI let target = va.saturating_add(first.saturating_mul(elem as u64)); let len = (n as u64).saturating_mul(elem as u64) as usize; let base = resolve_uma_va(target, len) - .or_else(|| read_only.then(|| super::sparse::gpu_view::base_for(target as usize, len).map(|b| b as u64)).flatten()) + .or_else(|| { + if read_only { + super::sparse::gpu_view::base_for(target as usize, len).map(|b| b as u64) + } else { + unsafe { ensure_outside_buffer(target as usize, len, false, true).map(|(_, u)| u as u64) } + } + }) .unwrap_or(target); crate::gpu::desc::buffer_words(base, stride, records, fmt) } @@ -10954,3 +11191,41 @@ mod pso_release_tests { assert!(!is_translated_compute(this as usize)); } } + +#[cfg(test)] +mod outside_buffer_tests { + use super::*; + + #[test] + fn outside_buffer_table_shares_uav_and_srv_subranges_and_reclaims_on_release() { + let mut t = OutsideBufferTable::default(); + let cap = 1 << 20; // 1 MiB cap + let base = 0x0c00_0000_0000usize; + let uma = 0x0003_1000_0000usize; + + // Disabled cap rejects insertion. + assert!(!t.insert(base, base + 0x4_0000, uma, true, false, 0)); + + // Insert a 256 KiB GPU-writable placed buffer range; sub-range SRV/UAV lookups hit the + // exact same sparse UMA backing at matching byte offsets. + assert!(t.insert(base, base + 0x4_0000, uma, true, false, cap)); + assert_eq!(t.lookup(base, 0x4_0000), Some(uma)); + assert_eq!(t.lookup(base + 0x1_2340, 0x4000), Some(uma + 0x1_2340)); + assert_eq!(t.lookup(base + 0x3_f000, 0x2000), None); // past end + + // Overlapping non-contained insertion is rejected to avoid splitting live tiles. + assert!(!t.insert(base + 0x2_0000, base + 0x6_0000, uma + 0x10_0000, true, false, cap)); + + // Second placed alias retains refcount; releasing first keeps backing alive, releasing second reclaims. + assert_eq!(t.retain_existing(base + 0x1_0000, 0x1_0000, true, false), Some((base, uma + 0x1_0000))); + assert_eq!(t.release_ref(base), None); + assert_eq!(t.release_ref(base), Some(uma)); + assert_eq!(t.total_bytes, 0); + assert_eq!(t.lookup(base, 0x1000), None); + + // UAV-pinned backing created without a placed resource stays resident across release_ref. + assert!(t.insert(base, base + 0x2_0000, uma, false, true, cap)); + assert_eq!(t.release_ref(base), None); + assert_eq!(t.lookup(base + 0x1000, 0x1000), Some(uma + 0x1000)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 4801a3b9b1..11acd4b994 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1271,6 +1271,44 @@ pub unsafe fn free(p: usize) -> bool { u.sparse_release(p).is_some() } +/// Allocate a VRAM-only sparse block (zero CPU commit, `holes = 0xFFFF` so CPU write-watch +/// never overwrites GPU UAV writes) for GPU-writable buffers placed outside the UMA windows. +pub unsafe fn alloc_vram_only(size: usize, align: usize) -> Option<(usize, usize)> { + let u = crate::gpu::uma::get()?; + let (addr, rounded) = u.sparse_alloc(size, align.max(TILE))?; + let ok = { + let mut g = lock_state(); + if let Some(s) = g.as_mut() { + s.ensure_mapped(addr, rounded, |_| 0xFFFF); + let last_tile = (addr + rounded - 1) & !(TILE - 1); + if s.mapped.contains_key(&addr) && s.mapped.contains_key(&last_tile) { + true + } else { + s.decommit_range(addr, rounded); + false + } + } else { + false + } + }; + if !ok { + u.sparse_release(addr); + return None; + } + Some((addr, rounded)) +} + +/// Release a VRAM-only sparse block from `alloc_vram_only` (defers tile unmap behind GPU fences). +pub unsafe fn free_vram_only(p: usize) -> bool { + let Some(u) = crate::gpu::uma::get() else { return false }; + if !u.is_sparse(p) { + return false; + } + let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false }; + decommitted(start, len); + u.sparse_release(p).is_some() +} + /// After `queue.ExecuteCommandLists`: copy GPU-written sparse ranges (e.g. `Write32/64`, /// `FillMemoryWith32BitValueX`, `CopyMemoryToMemoryX`) back to their CPU view so CPU reads /// and spin-waits see the GPU writes without clobbering `sent` hashes. From 1b31962701324b97d3609f7f199a81e40c694889 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:17:46 +0100 Subject: [PATCH 139/258] D3D12.X: pool exclusive ID3D12PipelineLibrary1 read handles to fix concurrent Load* crash Windows D3D12Core.dll mutates internal state during ID3D12PipelineLibrary1::Load* and faults (0xc0000005 at D3D12Core.dll+0x7dfa) when multiple threads invoke LoadComputePipeline/LoadGraphicsPipeline/LoadPipeline concurrently on the same ID3D12PipelineLibrary1 instance, even when no StorePipeline or Serialize runs on that handle. Replace the single shared read_lib handle in MmapPipelineLibrary with a checked-out pool (read_pool, capped at 16 idle handles) backed by the same read-only startup Arc and free-threaded ID3D12Device1: - Each Load* pops an exclusive handle from read_pool (or lazily opens another from the same zero-copy MappedBlob outside the pool mutex) and returns it via ReadHandleGuard::drop, guaranteeing strict single-threaded ownership of every ID3D12PipelineLibrary1 handle while preserving lock-free concurrent Load* throughput (zero lib_lock convoy) and keeping write_lib isolated on xcl-plib-save. - Declare read_pool before read_backing and dev1 so Rust always destroys every pooled library handle before unmapping the backing blob. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/pso_library.rs | 89 ++++++++++++++++++------ 1 file changed, 69 insertions(+), 20 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_library.rs b/crates/xcl/src/hle/d3d12x/pso_library.rs index 9dd5a60d3e..74c900f56c 100644 --- a/crates/xcl/src/hle/d3d12x/pso_library.rs +++ b/crates/xcl/src/hle/d3d12x/pso_library.rs @@ -402,25 +402,61 @@ unsafe fn create_empty_library(dev1: &ID3D12Device1) -> Option { + pool: &'a std::sync::Mutex>, + lib: Option, +} + +impl ReadHandleGuard<'_> { + fn handle(&self) -> &ID3D12PipelineLibrary1 { + self.lib.as_ref().unwrap() + } +} + +impl Drop for ReadHandleGuard<'_> { + fn drop(&mut self) { + if let Some(lib) = self.lib.take() { + let mut pool = self.pool.lock().unwrap(); + if pool.len() < MAX_POOLED_READ_HANDLES { + pool.push(lib); + } + } + } +} + +/// Process-wide D3D12 pipeline library split into: +/// - `read_pool`: checked-out pool of independent read-only `ID3D12PipelineLibrary1` handles +/// opened from the startup `MappedBlob`. Windows `D3D12Core.dll` mutates internal state during +/// `Load*` and crashes (`D3D12Core.dll+0x7dfa`) when two threads call `Load*` concurrently on +/// the same `ID3D12PipelineLibrary1` instance; checking out an exclusive handle per caller keeps +/// every handle strictly single-threaded while preserving lock-free concurrent `Load*` scaling. /// - `write_lib`: owned exclusively by the dedicated `xcl-plib-save` worker thread, fed via an /// `mpsc` channel so `store()` returns in ~1 µs with zero lock contention on compile workers and /// `D3D12Core.dll` never sees concurrent `StorePipeline` + `Load*` or `Serialize` races. pub struct MmapPipelineLibrary { - read_lib: Option, - /// Kept alive for the entire lifetime of `read_lib` because D3D12 requires the initial blob - /// memory to remain valid until the `ID3D12PipelineLibrary` is destroyed. - _read_backing: Option>, + /// Declared BEFORE `read_backing` and `dev1` so Rust drops every pooled handle before + /// unmapping `read_backing` or releasing `dev1`. + read_pool: std::sync::Mutex>, + /// Kept alive for the entire lifetime of `read_pool` handles because D3D12 requires the + /// initial blob memory to remain valid until every `ID3D12PipelineLibrary` is destroyed. + read_backing: Option>, + /// Free-threaded D3D12 device used to lazily open additional read-only handles from + /// `read_backing` when multiple threads call `Load*` concurrently. + dev1: ID3D12Device1, /// Async command channel to the dedicated `xcl-plib-save` thread owning `write_lib`. /// The mutex protects only the ~50 ns `mpsc::Sender::send` (never any D3D12 call). save_tx: Option>>, dirty: Arc, } -// `read_lib` is strictly immutable after creation (`Load*` is free-threaded per D3D12 spec when -// never mutated by `StorePipeline` or `Serialize`); `save_tx` is synchronized by its Mutex. +// Every `ID3D12PipelineLibrary1` in `read_pool` is exclusively owned by one thread at a time via +// `ReadHandleGuard`; `dev1.CreatePipelineLibrary` is free-threaded per D3D12 spec; `read_backing` +// is read-only immutable memory; `save_tx` is synchronized by its Mutex. unsafe impl Sync for MmapPipelineLibrary {} unsafe impl Send for MmapPipelineLibrary {} @@ -433,7 +469,7 @@ impl MmapPipelineLibrary { } let dev1: ID3D12Device1 = device.cast().ok()?; let store = LibraryStore::for_adapter(adapter_name); - let mut read_lib: Option = None; + let mut initial_read_handles: Vec = Vec::new(); let mut backing: Option> = None; if let Some((gen, blob)) = store.open_latest() { @@ -443,7 +479,7 @@ impl MmapPipelineLibrary { "D3D12.X: opened memory-mapped pipeline library gen-{gen:08x} ({:.1} MiB file-backed)", blob.len() as f64 / (1024.0 * 1024.0) ); - read_lib = Some(lib); + initial_read_handles.push(lib); backing = Some(Arc::new(blob)); } Err(e) => { @@ -478,7 +514,7 @@ impl MmapPipelineLibrary { Some(blob) => dev1.CreatePipelineLibrary::(blob.as_slice()).ok(), None => create_empty_library(&dev1), }; - if read_lib.is_none() && write_lib.is_none() { + if initial_read_handles.is_empty() && write_lib.is_none() { return None; } @@ -495,38 +531,51 @@ impl MmapPipelineLibrary { }); Some(Self { - read_lib, - _read_backing: backing, + read_pool: std::sync::Mutex::new(initial_read_handles), + read_backing: backing, + dev1, save_tx, dirty, }) } + /// Check out exclusive ownership of a read-only `ID3D12PipelineLibrary1` handle backed by + /// `read_backing`, lazily opening a new handle from the same mmap when concurrent threads + /// overlap. Never holds `read_pool`'s mutex across any D3D12 driver call. + unsafe fn checkout_read_handle(&self) -> Option> { + let blob = self.read_backing.as_ref()?; + if let Some(lib) = self.read_pool.lock().unwrap().pop() { + return Some(ReadHandleGuard { pool: &self.read_pool, lib: Some(lib) }); + } + let lib = self.dev1.CreatePipelineLibrary::(blob.as_slice()).ok()?; + Some(ReadHandleGuard { pool: &self.read_pool, lib: Some(lib) }) + } + pub unsafe fn load_compute(&self, key: &str, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC) -> Option { if key.is_empty() || desc.pRootSignature.is_none() || desc.CS.pShaderBytecode.is_null() || desc.CS.BytecodeLength == 0 { return None; } - let lib = self.read_lib.as_ref()?; + let guard = self.checkout_read_handle()?; let name = HSTRING::from(key); - lib.LoadComputePipeline(&name, desc).ok() + guard.handle().LoadComputePipeline(&name, desc).ok() } pub unsafe fn load_graphics(&self, key: &str, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> Option { if key.is_empty() || desc.pRootSignature.is_none() { return None; } - let lib = self.read_lib.as_ref()?; + let guard = self.checkout_read_handle()?; let name = HSTRING::from(key); - lib.LoadGraphicsPipeline(&name, desc).ok() + guard.handle().LoadGraphicsPipeline(&name, desc).ok() } pub unsafe fn load_stream(&self, key: &str, desc: &D3D12_PIPELINE_STATE_STREAM_DESC) -> Option { if key.is_empty() || desc.pPipelineStateSubobjectStream.is_null() || desc.SizeInBytes == 0 { return None; } - let lib = self.read_lib.as_ref()?; + let guard = self.checkout_read_handle()?; let name = HSTRING::from(key); - lib.LoadPipeline(&name, desc).ok() + guard.handle().LoadPipeline(&name, desc).ok() } /// Enqueue `(key, pso)` for the dedicated `xcl-plib-save` worker thread. Returns immediately From 60d67a15ad8f81c1be29d96f30a5954ab0b45e73 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:16:06 +0100 Subject: [PATCH 140/258] Shaders: respect XCL_RT_GATE=hold, log slow compiles, and serialize >=900 KiB offline builds Prevent silent multi-minute offline stalls during xcl shaders --precompile --pipelines [--used-only] and align offline prebuilds with runtime RT gating: - Expose real::rt_gated_compute_held(cs) so shaders::precompile skips RT traversal and RT companion compute shaders (e.g. 95cc13288a27a96e) when XCL_RT_GATE is in default hold mode, printing the held-back count in the summary (opt out via XCL_RT_GATE=auto or 0). - Pass the console record hash into Pipelines::make_record and log compile start/finish (record hash, DXIL bytes, elapsed ms, ok/refused) for >=256 KiB DXIL compiles (or >=2 s finishes, or XCL_PSO_TRACE=1) so slow offline driver compiles are immediately visible. - Serialize cold offline compiles >=900 KiB DXIL via Pipelines::giant so multi-threaded XCL_PIPELINE_THREADS runs never stack multiple giant compiles into host OOM. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 7 +++ crates/xcl/src/shaders.rs | 73 ++++++++++++++++++++++++++++--- 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 80c55a4f15..9ce80183a7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2266,6 +2266,13 @@ fn is_rt_gated_cs(cs: &[u8]) -> bool { || crate::gpu::effects::uses_bvh_intersect(cs) } +/// Whether a console compute shader container is currently held back without compiling under +/// `XCL_RT_GATE=hold` (default). Shared by offline `xcl shaders --precompile` so prebuilds skip +/// the exact same RT traversal and RT companion shaders that runtime holds back. +pub(crate) fn rt_gated_compute_held(cs: &[u8]) -> bool { + rt_gate_mode() == RtGateMode::Hold && is_rt_gated_cs(cs) +} + fn note_bvh_traversal(pso: usize, cs: &[u8]) { if pso != 0 && is_rt_gated_cs(cs) { BVH_TRAVERSAL_PSOS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 3bd1d90666..89385152e1 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1219,6 +1219,9 @@ struct Pipelines { /// driver compiles running and the most at once (`XCL_PIPELINE_THREADS`, 4): each of the /// biggest takes ~1.5 GB in the driver – fifteen at once took 24 GB running: (Mutex, std::sync::Condvar), + /// Serializes cold offline compiles `>= OFFLINE_GIANT_DXIL` (900 KiB) to 1-at-a-time so + /// multi-threaded `--pipelines` runs never stack multiple giant driver compiles into OOM. + giant: Mutex<()>, most: usize, /// DXIL bytes a pipeline is still handed to the driver (`XCL_PIPELINE_MAX_KB`, 8 MiB; 0: off) max_dxil: usize, @@ -1226,6 +1229,18 @@ struct Pipelines { cache_dir: Option, } +const OFFLINE_LOG_DXIL: usize = 256 << 10; +const OFFLINE_GIANT_DXIL: usize = 900 << 10; + +fn offline_pso_trace() -> bool { + static V: std::sync::OnceLock = std::sync::OnceLock::new(); + *V.get_or_init(|| std::env::var("XCL_PSO_TRACE").is_ok_and(|v| v.trim() == "1")) +} + +fn should_log_offline_compile_start(dxil_bytes: usize, trace: bool) -> bool { + trace || dxil_bytes >= OFFLINE_LOG_DXIL +} + /// `XCL_PIPELINE_MAX_KB`: the KiB of DXIL `--pipelines` still compiles (default 8 MiB; 0: no /// cap). Above it sit the programs whose driver compile takes tens of minutes and gigabytes — /// the > 8 MB HLSL programs DXC compiles at `-O0` (#1269) — and they hang the pass. @@ -1255,6 +1270,11 @@ mod pipeline_cap_tests { assert!(std_key.starts_with("c-")); assert_eq!(split_key, format!("s{std_key}")); assert_ne!(std_key, split_key); + assert!(!super::should_log_offline_compile_start(super::OFFLINE_LOG_DXIL - 1, false)); + assert!(super::should_log_offline_compile_start(super::OFFLINE_LOG_DXIL, false)); + assert!(super::should_log_offline_compile_start(128, true)); + assert!(crate::hle::d3d12x::real::rt_gated_compute_held(b"HDR\0CS_ScreenProbes_ActivateRays\0")); + assert!(!crate::hle::d3d12x::real::rt_gated_compute_held(b"HDR\0CS_DepthPyramid\0")); } #[test] @@ -1455,6 +1475,7 @@ impl Pipelines { capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), running: (Mutex::new(0), std::sync::Condvar::new()), + giant: Mutex::new(()), most, max_dxil, #[cfg(test)] @@ -1467,11 +1488,21 @@ impl Pipelines { /// into a dispatch chain of at least two pieces, each piece is built and cached under the /// dispatch-chain root signature (`.chain.pso`) as the runtime does (`dispatch_chain::build`), /// instead of the unsplit whole container. + #[cfg(test)] fn make(&self, c: &recomp::pso::Compiled) { - self.make_with_cache_path(c, None); + self.make_with_cache_path_for(c, None, 0); + } + + fn make_record(&self, c: &recomp::pso::Compiled, record: u64) { + self.make_with_cache_path_for(c, None, record); } + #[cfg(test)] fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option) { + self.make_with_cache_path_for(c, path_override, 0); + } + + fn make_with_cache_path_for(&self, c: &recomp::pso::Compiled, path_override: Option, record: u64) { if path_override.is_none() { if let Some(chain) = c.dispatch_chain.as_deref().filter(|chain| chain.pieces.len() >= 2) { self.split_programs.fetch_add(1, Ordering::Relaxed); @@ -1479,7 +1510,7 @@ impl Pipelines { let workers = chain.pieces.len().min(self.most); if workers <= 1 { for piece in &chain.pieces { - self.make_one(piece, &c.samplers, true, None); + self.make_one(piece, &c.samplers, true, None, record); } } else { let next = AtomicUsize::new(0); @@ -1488,7 +1519,7 @@ impl Pipelines { s.spawn(|| loop { let i = next.fetch_add(1, Ordering::Relaxed); let Some(piece) = chain.pieces.get(i) else { break }; - self.make_one(piece, &c.samplers, true, None); + self.make_one(piece, &c.samplers, true, None, record); }); } }); @@ -1496,10 +1527,10 @@ impl Pipelines { return; } } - self.make_one(&c.dxil, &c.samplers, false, path_override); + self.make_one(&c.dxil, &c.samplers, false, path_override, record); } - fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option) { + fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option, record: u64) { use windows::Win32::Graphics::Direct3D12::*; let key: (bool, Vec) = (chained, samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect()); let rs = { @@ -1597,8 +1628,27 @@ impl Pipelines { self.reused.fetch_add(1, Ordering::Relaxed); Ok(pso) } else { + let _giant = (dxil.len() >= OFFLINE_GIANT_DXIL).then(|| self.giant.lock().unwrap()); + let log_start = should_log_offline_compile_start(dxil.len(), offline_pso_trace()); + if log_start { + eprintln!( + " pipeline compile start: record {record:016x} ({} B DXIL{})", + dxil.len(), + if chained { ", split piece" } else { "" } + ); + } + let started = std::time::Instant::now(); desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let pso = unsafe { self.dev.CreateComputePipelineState::(&desc) }; + let took = started.elapsed(); + if log_start || took >= std::time::Duration::from_secs(2) { + eprintln!( + " pipeline compile finish: record {record:016x} ({} B DXIL, {} ms, {})", + dxil.len(), + took.as_millis(), + if pso.is_ok() { "ok" } else { "refused" } + ); + } if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { if let Ok(blob) = unsafe { pso.GetCachedBlob() } { let bytes = unsafe { blob.GetBufferPointer() }.cast::(); @@ -1660,6 +1710,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); let errors: Mutex> = Mutex::new(Vec::new()); let unused = AtomicUsize::new(0); + let rt_gated = AtomicUsize::new(0); if let Some(u) = used { println!("--used-only: {} pipelines earlier runs used (used-pipelines.txt); compute programs of other pipelines are passed over", u.len()); } @@ -1701,10 +1752,16 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on done.fetch_add(1, Ordering::Relaxed); continue; } + if crate::hle::d3d12x::real::rt_gated_compute_held(&blob) { + rt_gated.fetch_add(1, Ordering::Relaxed); + done.fetch_add(1, Ordering::Relaxed); + continue; + } + let record = crate::gpu::shader::fnv64(&blob); match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - p.make(&c); + p.make_record(&c, record); } compiled.fetch_add(1, Ordering::Relaxed) } @@ -1777,6 +1834,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if used.is_some() { println!("compute programs passed over (no earlier run used their pipeline): {}", unused.into_inner()); } + let rt_gated = rt_gated.into_inner(); + if rt_gated != 0 { + println!("compute programs held back by XCL_RT_GATE=hold (set XCL_RT_GATE=auto or 0 to precompile): {rt_gated}"); + } if let Some(p) = pipelines { let saved_plib = p.flush(); println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); From 9d398bf44a4769098b5efe93d5b2b8a6db7ae376 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:43:11 +0100 Subject: [PATCH 141/258] d3d12x,kernelx: lock-free descriptor copies, PSO bind cache, priority opt-out Clean-room Wave 14 runtime FPS & CPU-latency optimizations: 1. console_heap + real: switch HEAPS/GLOBAL/GLOBAL_SAMPLER from Mutex to RwLock with AtomicU32 page slots, drop global locks before D3D12 CopyDescriptorsSimple in publish/publish_range, skip RES lock when XCL_TRACE_FRAME is off, add single-lock copy_words_range(), skip self copies, and replace Vec-allocating dev_copy_descriptors_x with a zero-alloc lockstep range coalescer. 2. list_x + real: track last resolved PC PSO per command list and skip redundant SetPipelineState + DRED markers when (pso, bound) is already active (invalidated on Reset/ClearState/KickoffX/split/depth-bias, XCL_BIND_CACHE=0 opt-out). 3. kernelx: opt out of Windows 11 Efficiency Mode (EXECUTION_SPEED) alongside IGNORE_TIMER_RESOLUTION and lift process priority to ABOVE_NORMAL (XCL_PRIORITY=0 opt-out). 4. bind: raise default per-recording indirect argument scratch cap to 32 MiB (XCL_INDIRECT_SCRATCH_MB, clamped 4..=128 MiB) so dense open-world indirect draw lists do not exhaust scratch mid-recording. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 28 +- crates/xcl/src/hle/d3d12x/console_heap.rs | 300 ++++++++++++++++------ crates/xcl/src/hle/d3d12x/list_x.rs | 79 +++++- crates/xcl/src/hle/d3d12x/real.rs | 58 +++-- crates/xcl/src/hle/kernelx.rs | 42 ++- 5 files changed, 393 insertions(+), 114 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 28d9ca770c..261264b977 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -208,7 +208,21 @@ struct State { /// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its /// two-pass ExecuteIndirects are skipped) const SCRATCH_BLOCK: u64 = 1 << 20; -const SCRATCH_CAP: u64 = 16 << 20; +/// Default per-recording cap on rewritten indirect-argument scratch (MiB). Overridable via +/// `XCL_INDIRECT_SCRATCH_MB` (clamped 4..=128 MiB) so dense open-world indirect draw lists do +/// not exhaust scratch mid-recording and drop trailing draws. +const SCRATCH_CAP: u64 = 32 << 20; + +fn scratch_cap() -> u64 { + static CAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *CAP.get_or_init(|| { + std::env::var("XCL_INDIRECT_SCRATCH_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map(|mb| mb.clamp(4, 128) << 20) + .unwrap_or(SCRATCH_CAP) + }) +} /// Most bytes of buffers kept for reuse (`FREE_RES`) const FREE_RES_CAP: u64 = 256 << 20; /// Size of one pooled VRAM `io` (`u0`) slab (64 KiB = 256 distinct 256-byte `io` slots). @@ -1769,9 +1783,10 @@ unsafe fn alloc_prelude_scratch(this: *mut c_void, dev: &ID3D12Device, bytes: u6 return Ok(r); } let size = bytes.max(SCRATCH_BLOCK); - let remaining = SCRATCH_CAP.saturating_sub(with(this, |s| s.scratch_taken)); + let cap = scratch_cap(); + let remaining = cap.saturating_sub(with(this, |s| s.scratch_taken)); if size > remaining { - return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); + return Err(format!("its rewritten arguments are past {} MiB this recording", cap >> 20)); } let dev_key = dev.as_raw() as usize; let picked = { @@ -2388,9 +2403,10 @@ unsafe fn scratch_args_in(this: *mut c_void, dev: &ID3D12Device, bytes: u64, slo return Ok(r); } let size = bytes.max(SCRATCH_BLOCK); - let remaining = SCRATCH_CAP.saturating_sub(with(this, |s| s.scratch_taken)); + let cap = scratch_cap(); + let remaining = cap.saturating_sub(with(this, |s| s.scratch_taken)); if size > remaining { - return Err(format!("its rewritten arguments are past {} MiB this recording", SCRATCH_CAP >> 20)); + return Err(format!("its rewritten arguments are past {} MiB this recording", cap >> 20)); } let dev_key = dev.as_raw() as usize; let picked = { @@ -2442,7 +2458,7 @@ unsafe fn scratch_args_pingpong(this: *mut c_void, dev: &ID3D12Device, bytes: u6 s.scratch[0].buf.as_ref().is_some_and(|(_, cap, _)| s.scratch[0].used + aligned <= *cap), s.scratch[1].buf.as_ref().is_some_and(|(_, cap, _)| s.scratch[1].used + aligned <= *cap), ]; - let can_alloc = SCRATCH_CAP.saturating_sub(s.scratch_taken) >= size; + let can_alloc = scratch_cap().saturating_sub(s.scratch_taken) >= size; let chosen = pick_pingpong_slot(preferred, fits, can_alloc); s.scratch_next = chosen ^ 1; chosen diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index eb7e75e569..8503cfc3d6 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -26,7 +26,8 @@ //! UAV at 2k + 1. use std::collections::{HashMap, VecDeque}; -use std::sync::Mutex; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Mutex, RwLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -57,7 +58,7 @@ struct Heap { sampler: bool, /// views in the shared heap: the index there of each page's first SRV (`UNMAPPED`: the /// page has no place yet); empty: the heap's views are not in the shared heap - pages: Vec, + pages: Vec, /// shader visible as the title made it visible: bool, memory: Memory, @@ -73,7 +74,7 @@ impl Heap { } } -static HEAPS: Mutex> = Mutex::new(Vec::new()); +static HEAPS: RwLock> = RwLock::new(Vec::new()); /// Released descriptor range in `GLOBAL` or `GLOBAL_SAMPLER` awaiting active GPU queues before /// being returned to `free` (prevents overwriting shader-visible descriptors still read in flight). @@ -162,8 +163,9 @@ struct Global { // D3D12 descriptor heaps and devices are free-threaded unsafe impl Send for Global {} +unsafe impl Sync for Global {} -static GLOBAL: Mutex> = Mutex::new(None); +static GLOBAL: RwLock> = RwLock::new(None); static GLOBAL_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// descriptors of the shared heap at most (the GPU may take more: OPTIONS19) @@ -234,7 +236,10 @@ unsafe fn global_cap(dev: &ID3D12Device) -> u32 { /// made) – view heaps then keep their own. pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { use std::sync::atomic::Ordering::Relaxed; - let mut g = GLOBAL.lock().unwrap(); + if GLOBAL.read().unwrap().is_some() { + return true; + } + let mut g = GLOBAL.write().unwrap(); if g.is_none() { if GLOBAL_FAILED.load(Relaxed) { return false; @@ -327,7 +332,7 @@ unsafe fn set_window_views_checked(dev: &ID3D12Device, windows: &[(usize, usize) let complete = count <= crate::gpu::uma::MAX_WINDOWS || windows.iter().all(|&(raw, bytes)| raw != 0 || bytes == 0); let ok = atomics64 && count <= 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 g = GLOBAL.read().unwrap(); let s = g.as_ref().unwrap(); (s.dev.clone(), s.cpu, s.inc) }; @@ -354,7 +359,7 @@ unsafe fn set_window_views_checked(dev: &ID3D12Device, windows: &[(usize, usize) /// `count` descriptors of the shared heap: the index of the first. None: no shared heap, or /// no room left in it. fn reserve_global(count: u32) -> Option { - let mut g = GLOBAL.lock().unwrap(); + let mut g = GLOBAL.write().unwrap(); let s = g.as_mut()?; unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; let (cap, mut next) = (s.cap, s.next); @@ -372,12 +377,20 @@ fn reserve_global(count: u32) -> Option { /// The place in the shared heap of the page slot `k` of `h` is in – (index of the page's /// first SRV there, the page's first slot) – given now if the page has none yet. None: the /// heap is not in the shared heap, or that is full. -fn page_of(h: &mut Heap, k: u32) -> Option<(u32, u32)> { +fn page_of(h: &Heap, k: u32) -> Option<(u32, u32)> { let p = (k / PAGE_SLOTS) as usize; - let mut first = *h.pages.get(p)?; + let slot_atom = h.pages.get(p)?; + let mut first = slot_atom.load(Ordering::Acquire); if first == UNMAPPED { - first = reserve_global(page_descriptors(h.n, p as u32))?; - h.pages[p] = first; + let count = page_descriptors(h.n, p as u32); + let alloc = reserve_global(count)?; + match slot_atom.compare_exchange(UNMAPPED, alloc, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => first = alloc, + Err(existing) => { + release_global(alloc, count); + first = existing; + } + } } Some((first, p as u32 * PAGE_SLOTS)) } @@ -388,10 +401,10 @@ pub fn release_global(first: u32, count: u32) { if count == 0 { return; } - let dev = GLOBAL.lock().unwrap().as_ref().map(|s| s.dev.clone()); + let dev = GLOBAL.read().unwrap().as_ref().map(|s| s.dev.clone()); let Some(dev) = dev else { return }; let marks = unsafe { signal_live_queues_for(&dev) }; - if let Some(s) = GLOBAL.lock().unwrap().as_mut() { + if let Some(s) = GLOBAL.write().unwrap().as_mut() { if marks.as_ref().is_some_and(Vec::is_empty) { merge_release(&mut s.free, first, count); } else { @@ -418,12 +431,12 @@ fn merge_release(free: &mut Vec<(u32, u32)>, first: u32, count: u32) { /// The shader-visible PC heap lists bind for view descriptors (None: none shared). pub fn global_heap() -> Option { - GLOBAL.lock().unwrap().as_ref().map(|s| s.heap.clone()) + GLOBAL.read().unwrap().as_ref().map(|s| s.heap.clone()) } /// Whether `obj` (a title's view heap) has its descriptors in the shared heap. pub fn in_global(obj: usize) -> bool { - HEAPS.lock().unwrap().iter().any(|h| h.obj == obj && !h.sampler && !h.pages.is_empty()) + HEAPS.read().unwrap().iter().any(|h| h.obj == obj && !h.sampler && !h.pages.is_empty()) } /// Memory for a heap of `bytes` from the title's allocation hook – where the title expects the @@ -482,25 +495,25 @@ pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: ); } } - let pages = if shared && !sampler && GLOBAL.lock().unwrap().is_some() { - vec![UNMAPPED; n.div_ceil(PAGE_SLOTS).max(1) as usize] - } else if shared && sampler && GLOBAL_SAMPLER.lock().unwrap().is_some() { - vec![UNMAPPED; n.div_ceil(SAMPLER_PAGE_SLOTS).max(1) as usize] + let pages = if shared && !sampler && GLOBAL.read().unwrap().is_some() { + (0..n.div_ceil(PAGE_SLOTS).max(1)).map(|_| AtomicU32::new(UNMAPPED)).collect() + } else if shared && sampler && GLOBAL_SAMPLER.read().unwrap().is_some() { + (0..n.div_ceil(SAMPLER_PAGE_SLOTS).max(1)).map(|_| AtomicU32::new(UNMAPPED)).collect() } else { Vec::new() }; - HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); + HEAPS.write().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); true } /// The heap object was released for good: its slots go back to unified memory. pub fn unregister(obj: usize) { let gone = { - let mut heaps = HEAPS.lock().unwrap(); + let mut heaps = HEAPS.write().unwrap(); heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i)) }; if let Some(h) = gone { - for (p, &f) in h.pages.iter().enumerate().filter(|&(_, &f)| f != UNMAPPED) { + for (p, f) in h.pages.iter().enumerate().map(|(p, a)| (p, a.load(Ordering::Relaxed))).filter(|&(_, f)| f != UNMAPPED) { if h.sampler { release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); } else { @@ -523,12 +536,12 @@ pub fn unregister(obj: usize) { /// Whether heap `obj` holds samplers, and the 32-bit console address of its slots. pub fn base(obj: usize) -> Option<(bool, u32)> { - HEAPS.lock().unwrap().iter().find(|h| h.obj == obj).map(|h| (h.sampler, h.shadow as u32)) + HEAPS.read().unwrap().iter().find(|h| h.obj == obj).map(|h| (h.sampler, h.shadow as u32)) } /// Start of the console slots of heap `obj` (CPU handle = GPU handle on the console). pub fn start(obj: usize) -> Option { - HEAPS.lock().unwrap().iter().find(|h| h.obj == obj).map(|h| h.shadow as u64) + HEAPS.read().unwrap().iter().find(|h| h.obj == obj).map(|h| h.shadow as u64) } /// A console slot: where its descriptor goes and its PC descriptors. @@ -552,12 +565,12 @@ pub struct Slot { /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot /// of a heap in the shared heap gets its page's place there now if the page has none yet. pub fn slot(cpu: u64) -> Option { - let mut heaps = HEAPS.lock().unwrap(); - let h = heaps.iter_mut().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; + let heaps = HEAPS.read().unwrap(); + let h = heaps.iter().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32; if h.sampler { let shared = sampler_page_of(h, k).and_then(|(first, k0)| { - let g = GLOBAL_SAMPLER.lock().unwrap(); + let g = GLOBAL_SAMPLER.read().unwrap(); let g = g.as_ref()?; let i = first + (k - k0); Some((i, g.cpu + i as u64 * g.inc as u64)) @@ -570,7 +583,7 @@ pub fn slot(cpu: u64) -> Option { } let uav = ((2 * k + 1) * h.inc) as u64; let shared = page_of(h, k).and_then(|(first, k0)| { - let g = GLOBAL.lock().unwrap(); + let g = GLOBAL.read().unwrap(); let g = g.as_ref()?; let i = first + 2 * (k - k0); Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) @@ -588,8 +601,9 @@ pub unsafe fn publish(s: &Slot, uav: bool) { return; } if s.sampler { - if let Some(g) = GLOBAL_SAMPLER.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple( + let dev = GLOBAL_SAMPLER.read().unwrap().as_ref().map(|g| g.dev.clone()); + if let Some(dev) = dev { + dev.CopyDescriptorsSimple( 1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, @@ -598,9 +612,10 @@ pub unsafe fn publish(s: &Slot, uav: bool) { } return; } - if let Some(g) = GLOBAL.lock().unwrap().as_ref() { - let (dst, src) = if uav { (s.shared_srv + g.inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) }; - g.dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + let target = GLOBAL.read().unwrap().as_ref().map(|g| (g.dev.clone(), g.inc)); + if let Some((dev, inc)) = target { + let (dst, src) = if uav { (s.shared_srv + inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) }; + dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); } } @@ -609,6 +624,12 @@ pub unsafe fn publish(s: &Slot, uav: bool) { pub unsafe fn publish_range(first: &Slot, n: u32) { let page_slots = if first.sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; let step = if first.sampler { SAMPLER_SLOT } else { SLOT }; + let dev = if first.sampler { + GLOBAL_SAMPLER.read().unwrap().as_ref().map(|g| g.dev.clone()) + } else { + GLOBAL.read().unwrap().as_ref().map(|g| g.dev.clone()) + }; + let Some(dev) = dev else { return }; let mut done = 0; while done < n { let s = if done == 0 { Some(*first) } else { slot((first.at + (done * step) as usize) as u64) }; @@ -616,16 +637,19 @@ pub unsafe fn publish_range(first: &Slot, n: u32) { let run = (page_slots - s.k % page_slots).min(n - done); if s.shared_srv != 0 { if s.sampler { - if let Some(g) = GLOBAL_SAMPLER.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple( - run, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - ); - } - } else if let Some(g) = GLOBAL.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple(2 * run, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + dev.CopyDescriptorsSimple( + run, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + ); + } else { + dev.CopyDescriptorsSimple( + 2 * run, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + ); } } done += run; @@ -673,18 +697,97 @@ pub fn copy_words(src: &Slot, dst: &Slot) { } write(dst, &w[..n]); if !src.sampler { - note_resource(dst, resource_at(src.at).unwrap_or(0)); + if super::present::trace_frame() { + note_resource(dst, resource_at(src.at).unwrap_or(0)); + } if w[3] >> 28 >= 8 { super::ambient::copy_descriptor(src.index, dst.index); } } } +/// Copy `n` contiguous console slots from `src` to `dst` under a single shared `HEAPS` read lock, +/// renumbering T#/S# PC heap indices per page run instead of re-acquiring global locks per slot. +pub fn copy_words_range(dst: u64, src: u64, n: u32) -> bool { + if n == 0 { + return true; + } + let heaps = HEAPS.read().unwrap(); + let Some(hd) = heaps.iter().find(|h| dst >= h.shadow as u64 && dst < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64) else { + return false; + }; + let Some(hs) = heaps.iter().find(|h| src >= h.shadow as u64 && src < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64) else { + return false; + }; + if hd.sampler != hs.sampler { + return false; + } + let sampler = hd.sampler; + let step = hd.slot_bytes(); + let kd0 = ((dst - hd.shadow as u64) / step as u64) as u32; + let ks0 = ((src - hs.shadow as u64) / step as u64) as u32; + let count = n.min(hd.n - kd0).min(hs.n - ks0); + let page_slots = if sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; + let words_n = if sampler { 4 } else { 8 }; + let trace = !sampler && super::present::trace_frame(); + let d_hosted = !hd.pages.is_empty(); + let s_hosted = !hs.pages.is_empty(); + + let mut done = 0u32; + while done < count { + let kd = kd0 + done; + let ks = ks0 + done; + let run = (page_slots - kd % page_slots) + .min(page_slots - ks % page_slots) + .min(count - done); + let d_page = if sampler { sampler_page_of(hd, kd) } else { page_of(hd, kd) }; + let s_page = if sampler { sampler_page_of(hs, ks) } else { page_of(hs, ks) }; + for i in 0..run { + let kdi = kd + i; + let ksi = ks + i; + let dst_at = hd.shadow + (kdi * step) as usize; + let src_at = hs.shadow + (ksi * step) as usize; + let dst_idx = match d_page { + Some((first, k0)) => if sampler { first + (kdi - k0) } else { first + 2 * (kdi - k0) }, + None => if sampler { sampler_unmapped_index(d_hosted, kdi) } else { view_unmapped_index(d_hosted, kdi) }, + }; + let mut w = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping(src_at as *const u32, w.as_mut_ptr(), words_n) }; + let is_tex = !sampler && (w[3] >> 28 >= 8); + if sampler { + w[3] = (w[3] & !0xFFF) | (dst_idx & 0xFFF); + } else if is_tex { + w[0] = dst_idx; + } + unsafe { std::ptr::copy_nonoverlapping(w.as_ptr(), dst_at as *mut u32, words_n) }; + if trace { + let res = resource_at(src_at).unwrap_or(0); + let mut g = RES.lock().unwrap(); + let m = g.get_or_insert_with(Default::default); + if res == 0 { + m.remove(&dst_at); + } else { + m.insert(dst_at, res); + } + } + if is_tex { + let src_idx = match s_page { + Some((first, k0)) => first + 2 * (ksi - k0), + None => view_unmapped_index(s_hosted, ksi), + }; + super::ambient::copy_descriptor(src_idx, dst_idx); + } + } + done += run; + } + true +} + /// `XCL_TRACE_FRAME`: what the slots of each shader-visible view heap hold – images whose /// PC index is the slot's own (made or copied through the device) or another (copied by the /// title itself, as memory), buffers, empty. pub fn census() { - let heaps = HEAPS.lock().unwrap(); + let heaps = HEAPS.read().unwrap(); // samplers: S# word 3 [11:0] is the PC index in the sampler heap the slot belongs to for h in heaps.iter().filter(|h| h.sampler) { let (mut empty, mut own, mut other) = (0u32, 0u32, 0u32); @@ -693,7 +796,7 @@ pub fn census() { let w = unsafe { std::slice::from_raw_parts((h.shadow + (k * SAMPLER_SLOT) as usize) as *const u32, 4) }; if w.iter().all(|&x| x == 0) { empty += 1; - } else if w[3] & 0xFFF == sampler_own_index(&h.pages, k) { + } else if w[3] & 0xFFF == sampler_own_index_atomic(&h.pages, k) { own += 1; } else { other += 1; @@ -712,8 +815,8 @@ pub fn census() { for h in heaps.iter().filter(|h| !h.sampler) { let (mut empty, mut own, mut other, mut buffers) = (0u32, 0u32, 0u32, 0u32); let mut examples: Vec<(u32, u32)> = Vec::new(); - let own_index = |k: u32| match h.pages.get((k / PAGE_SLOTS) as usize) { - Some(&f) if f != UNMAPPED => f + 2 * (k % PAGE_SLOTS), + let own_index = |k: u32| match h.pages.get((k / PAGE_SLOTS) as usize).map(|a| a.load(Ordering::Relaxed)) { + Some(f) if f != UNMAPPED => f + 2 * (k % PAGE_SLOTS), _ => 2 * k, }; for k in 0..h.n { @@ -772,6 +875,7 @@ fn sampler_unmapped_index(hosted: bool, k: u32) -> u32 { } /// Expected PC sampler index for slot `k` of a sampler heap with shared-page table `pages`. +#[cfg(test)] fn sampler_own_index(pages: &[u32], k: u32) -> u32 { match pages.get((k / SAMPLER_PAGE_SLOTS) as usize) { Some(&f) if f != UNMAPPED => f + (k % SAMPLER_PAGE_SLOTS), @@ -779,6 +883,13 @@ fn sampler_own_index(pages: &[u32], k: u32) -> u32 { } } +fn sampler_own_index_atomic(pages: &[AtomicU32], k: u32) -> u32 { + match pages.get((k / SAMPLER_PAGE_SLOTS) as usize).map(|a| a.load(Ordering::Relaxed)) { + Some(f) if f != UNMAPPED => f + (k % SAMPLER_PAGE_SLOTS), + _ => sampler_unmapped_index(!pages.is_empty(), k), + } +} + struct GlobalSampler { dev: ID3D12Device, heap: ID3D12DescriptorHeap, @@ -791,8 +902,9 @@ struct GlobalSampler { } unsafe impl Send for GlobalSampler {} +unsafe impl Sync for GlobalSampler {} -static GLOBAL_SAMPLER: Mutex> = Mutex::new(None); +static GLOBAL_SAMPLER: RwLock> = RwLock::new(None); static GLOBAL_SAMPLER_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); fn sampler_page_descriptors(n: u32, p: u32) -> u32 { @@ -805,7 +917,10 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { if std::env::var("XCL_SHARED_SAMPLER_HEAP").is_ok_and(|v| v.trim() == "0") { return false; } - let mut g = GLOBAL_SAMPLER.lock().unwrap(); + if GLOBAL_SAMPLER.read().unwrap().is_some() { + return true; + } + let mut g = GLOBAL_SAMPLER.write().unwrap(); if g.is_none() { if GLOBAL_SAMPLER_FAILED.load(Relaxed) { return false; @@ -858,7 +973,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { } fn reserve_global_sampler(count: u32) -> Option { - let mut g = GLOBAL_SAMPLER.lock().unwrap(); + let mut g = GLOBAL_SAMPLER.write().unwrap(); let s = g.as_mut()?; unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; let (cap, mut next) = (s.cap, s.next); @@ -873,12 +988,20 @@ fn reserve_global_sampler(count: u32) -> Option { r } -fn sampler_page_of(h: &mut Heap, k: u32) -> Option<(u32, u32)> { +fn sampler_page_of(h: &Heap, k: u32) -> Option<(u32, u32)> { let p = (k / SAMPLER_PAGE_SLOTS) as usize; - let mut first = *h.pages.get(p)?; + let slot_atom = h.pages.get(p)?; + let mut first = slot_atom.load(Ordering::Acquire); if first == UNMAPPED { - first = reserve_global_sampler(sampler_page_descriptors(h.n, p as u32))?; - h.pages[p] = first; + let count = sampler_page_descriptors(h.n, p as u32); + let alloc = reserve_global_sampler(count)?; + match slot_atom.compare_exchange(UNMAPPED, alloc, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => first = alloc, + Err(existing) => { + release_global_sampler(alloc, count); + first = existing; + } + } } Some((first, p as u32 * SAMPLER_PAGE_SLOTS)) } @@ -887,10 +1010,10 @@ fn release_global_sampler(first: u32, count: u32) { if count == 0 { return; } - let dev = GLOBAL_SAMPLER.lock().unwrap().as_ref().map(|s| s.dev.clone()); + let dev = GLOBAL_SAMPLER.read().unwrap().as_ref().map(|s| s.dev.clone()); let Some(dev) = dev else { return }; let marks = unsafe { signal_live_queues_for(&dev) }; - if let Some(s) = GLOBAL_SAMPLER.lock().unwrap().as_mut() { + if let Some(s) = GLOBAL_SAMPLER.write().unwrap().as_mut() { if marks.as_ref().is_some_and(Vec::is_empty) { merge_release(&mut s.free, first, count); } else { @@ -902,12 +1025,12 @@ fn release_global_sampler(first: u32, count: u32) { /// The shared shader-visible PC sampler heap lists bind (None: no shared sampler heap). pub fn global_sampler_heap() -> Option { - GLOBAL_SAMPLER.lock().unwrap().as_ref().map(|s| s.heap.clone()) + GLOBAL_SAMPLER.read().unwrap().as_ref().map(|s| s.heap.clone()) } /// Whether `obj` (a title's sampler heap) has its descriptors in the shared sampler heap. pub fn in_global_sampler(obj: usize) -> bool { - HEAPS.lock().unwrap().iter().any(|h| h.obj == obj && h.sampler && !h.pages.is_empty()) + HEAPS.read().unwrap().iter().any(|h| h.obj == obj && h.sampler && !h.pages.is_empty()) } #[cfg(test)] @@ -989,7 +1112,7 @@ mod tests { unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } unsafe extern "system" fn create_uav(_this: *mut c_void, _resource: *mut c_void, _counter: *mut c_void, _desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, _at: D3D12_CPU_DESCRIPTOR_HANDLE) { // The adopted device hook can re-enter descriptor bookkeeping. - UNLOCKED.fetch_and(GLOBAL.try_lock().is_ok(), Ordering::Relaxed); + UNLOCKED.fetch_and(GLOBAL.try_write().is_ok(), Ordering::Relaxed); CALLS.fetch_add(1, Ordering::Relaxed); } let mut vt = [0usize; 20]; @@ -1001,7 +1124,7 @@ mod tests { let mut resource = Object { vt: vt.as_ptr() }; unsafe { let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); - *GLOBAL.lock().unwrap() = Some(Global { + *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, @@ -1025,7 +1148,7 @@ mod tests { assert!(!set_window_views_checked(&dev, &[window], false)); assert_eq!(CALLS.load(Ordering::Relaxed), 0); assert!(UNLOCKED.load(Ordering::Relaxed), "device callback ran while GLOBAL was locked"); - *GLOBAL.lock().unwrap() = None; + *GLOBAL.write().unwrap() = None; } } @@ -1197,7 +1320,7 @@ mod tests { let mut device = Object { vt: vt.as_ptr() }; let mut heap = Object { vt: vt.as_ptr() }; unsafe { - *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { + *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), @@ -1211,11 +1334,11 @@ mod tests { release_global_sampler(5, 4); release_global_sampler(1, 4); release_global_sampler(1, 0); - assert_eq!(GLOBAL_SAMPLER.lock().unwrap().as_ref().unwrap().free, vec![(1, 8)]); + assert_eq!(GLOBAL_SAMPLER.read().unwrap().as_ref().unwrap().free, vec![(1, 8)]); assert_eq!(reserve_global_sampler(8), Some(1)); // Coalesced range ending at cursor straddles cleanly into the never-used tail. { - let mut g = GLOBAL_SAMPLER.lock().unwrap(); + let mut g = GLOBAL_SAMPLER.write().unwrap(); let s = g.as_mut().unwrap(); s.next = 13; s.free.clear(); @@ -1223,12 +1346,12 @@ mod tests { release_global_sampler(9, 2); release_global_sampler(11, 2); assert_eq!(reserve_global_sampler(8), Some(9)); - let g = GLOBAL_SAMPLER.lock().unwrap(); + let g = GLOBAL_SAMPLER.read().unwrap(); let s = g.as_ref().unwrap(); assert_eq!(s.next, 17); assert!(s.free.is_empty()); drop(g); - *GLOBAL_SAMPLER.lock().unwrap() = None; + *GLOBAL_SAMPLER.write().unwrap() = None; } } @@ -1256,12 +1379,12 @@ mod tests { let mut sampler_heap = Object { vt: vt.as_ptr() }; unsafe { let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); - *GLOBAL.lock().unwrap() = Some(Global { + *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), retired: VecDeque::new(), }); - *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { + *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), @@ -1283,18 +1406,18 @@ mod tests { assert_eq!(slot(start(0xC111).unwrap()).unwrap().index, 5); unregister(0xC110); unregister(0xC111); - assert_eq!(GLOBAL_SAMPLER.lock().unwrap().as_ref().unwrap().free, vec![(1, 8)]); + assert_eq!(GLOBAL_SAMPLER.read().unwrap().as_ref().unwrap().free, vec![(1, 8)]); } else { - let mut heaps = HEAPS.lock().unwrap(); - heaps.push(Heap { obj: 0xC100, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); - heaps.push(Heap { obj: 0xC101, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + let mut heaps = HEAPS.write().unwrap(); + heaps.push(Heap { obj: 0xC100, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 16, sampler: true, pages: vec![AtomicU32::new(UNMAPPED), AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xC101, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 32, sampler: false, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); drop(heaps); assert!(!in_global(0xC100) && in_global_sampler(0xC100)); assert!(in_global(0xC101) && !in_global_sampler(0xC101)); - HEAPS.lock().unwrap().clear(); + HEAPS.write().unwrap().clear(); } - *GLOBAL_SAMPLER.lock().unwrap() = None; - *GLOBAL.lock().unwrap() = None; + *GLOBAL_SAMPLER.write().unwrap() = None; + *GLOBAL.write().unwrap() = None; } } @@ -1354,4 +1477,29 @@ mod tests { assert_eq!(free, vec![(64, 32)]); assert_eq!(retired.len(), 1); } + + #[test] + fn copy_words_range_copies_views_and_samplers_with_renumbering() { + let Some(u) = crate::gpu::uma::get() else { return }; + let rel = |p: u64| (p as usize - u.base()) as u32; + assert!(register(0xD100, 6, 0x1000, 0x5000, 32, false, false, true)); + assert!(register(0xD101, 4, 0x9000, 0, 16, true, false, true)); + let (v, sm) = (start(0xD100).unwrap(), start(0xD101).unwrap()); + // Slot 0 = 2D T#, Slot 1 = Buffer V#, Slot 2 = 2D T# + write(&slot(v).unwrap(), &[0, 0x1111_0000, 0, 9 << 28, 0, 0, 0, 0]); + write(&slot(v + SLOT as u64).unwrap(), &[0x5678, 0, 128, 0x3101_6FAC, 0, 0, 0, 0]); + write(&slot(v + 2 * SLOT as u64).unwrap(), &[4, 0x2222_0000, 0, 9 << 28, 0, 0, 0, 0]); + assert!(copy_words_range(v + 3 * SLOT as u64, v, 3)); + assert_eq!(words_at(rel(v + 3 * SLOT as u64)).unwrap()[..4], [6, 0x1111_0000, 0, 9 << 28]); + assert_eq!(words_at(rel(v + 4 * SLOT as u64)).unwrap()[..4], [0x5678, 0, 128, 0x3101_6FAC]); + assert_eq!(words_at(rel(v + 5 * SLOT as u64)).unwrap()[..4], [10, 0x2222_0000, 0, 9 << 28]); + // Samplers: copy slots 0..2 -> 2..4, renumbering word 3 [11:0] + write(&slot(sm).unwrap(), &[1, 2, 3, 0xABC0_0000]); + write(&slot(sm + SAMPLER_SLOT as u64).unwrap(), &[4, 5, 6, 0xDEF0_0001]); + assert!(copy_words_range(sm + 2 * SAMPLER_SLOT as u64, sm, 2)); + assert_eq!(words_at(rel(sm + 2 * SAMPLER_SLOT as u64)).unwrap()[..4], [1, 2, 3, 0xABC0_0002]); + assert_eq!(words_at(rel(sm + 3 * SAMPLER_SLOT as u64)).unwrap()[..4], [4, 5, 6, 0xDEF0_0003]); + unregister(0xD100); + unregister(0xD101); + } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 2d8a67830c..aec209bc0c 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -187,6 +187,9 @@ pub(super) unsafe fn restore_after_internal_pass(list: *mut c_void, clobbered_gf if bound_pso != 0 { let resolved = super::pso_async::resolve_for_bind(bound_pso); pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.last_pc_pso = resolved; + } if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE { if let Some((true, static_bias)) = device_x::base_depth_bias_info(bound_pso) { let target = depth_bias.unwrap_or(static_bias); @@ -903,6 +906,9 @@ struct ListState { last_queue: Option, /// Title's currently bound PSO (before dynamic depth-bias override) bound_pso: usize, + /// Last resolved PC PSO actually emitted via `SetPipelineState` on this PC list + /// (cleared on Reset / ClearState / KickoffX / split so bind dedup is always exact). + last_pc_pso: usize, /// Active `RSSetDepthBiasX` override (None = zero / disabled) depth_bias: Option, /// Last depth bias sent to `ID3D12GraphicsCommandList9::RSSetDepthBias` on this PC list @@ -1170,6 +1176,7 @@ pub(super) fn clear_segment_state(list: usize) { real::dispatch_chain::list_reset(list); super::title_textures::list_reset(list); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { + s.last_pc_pso = 0; s.occlusion = Occlusion::default(); s.written_ranges.clear(); s.written_values.clear(); @@ -1200,14 +1207,40 @@ pub(super) fn on_allocator_release(alloc: usize) { } } -/// Track `SetPipelineState` on a command list (for `RSSetDepthBiasX` and `KickoffX`), -/// syncing `ID3D12GraphicsCommandList9::RSSetDepthBias` when the bound PSO uses native dynamic -/// depth bias. +fn bind_cache_enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_BIND_CACHE").map_or(true, |v| v.trim() != "0")) +} + +/// Whether `SetPipelineState(pso)` resolved to `bound` is already active on `list` (same title +/// PSO and resolved PC PSO, with no pending/active depth-bias patch), allowing the redundant +/// D3D12 call and DRED marker to be skipped. +pub(super) fn skip_redundant_pso_bind(list: *mut c_void, pso: usize, bound: usize) -> bool { + if !bind_cache_enabled() || list.is_null() || pso == 0 || bound == 0 { + return false; + } + LISTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(list as usize))) + .is_some_and(|s| s.bound_pso == pso && s.last_pc_pso == bound && !s.pso_dirty && !s.using_fallback_pso) +} + +/// Track `SetPipelineState` on a command list (for `RSSetDepthBiasX`, `KickoffX`, and redundant +/// bind dedup), syncing `ID3D12GraphicsCommandList9::RSSetDepthBias` when the bound PSO uses +/// native dynamic depth bias. +#[cfg(test)] pub(super) unsafe fn on_set_pipeline_state(list: *mut c_void, pso: usize) { + on_set_pipeline_state_bound(list, pso, pso); +} + +pub(super) unsafe fn on_set_pipeline_state_bound(list: *mut c_void, pso: usize, bound: usize) { let key = list as usize; let sync_target = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(key).or_default(); + s.last_pc_pso = bound; // Keep the title-visible base PSO key when `bind_abi` re-binds its resolved background PSO. if s.bound_pso == 0 || pso == s.bound_pso || super::pso_async::resolve(s.bound_pso) != pso { s.bound_pso = pso; @@ -1261,6 +1294,7 @@ pub(super) unsafe fn on_clear_state(list: *mut c_void, pso: usize) { let mut g = LISTS.lock().unwrap(); if let Some(s) = g.get_or_insert_with(HashMap::new).get_mut(&key) { s.bound_pso = pso; + s.last_pc_pso = 0; s.depth_bias = None; s.native_bias = DepthBias::ZERO; s.pso_dirty = false; @@ -3644,6 +3678,7 @@ pub(super) fn on_pc_reset(list: *mut c_void) { } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { s.bindings.render_targets = None; + s.last_pc_pso = 0; if PREDICATION_USED.load(Ordering::Acquire) { s.predication = None; s.pred_in_state = false; @@ -3917,6 +3952,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { // Reset() cleared the PC list's native RSSetDepthBias state to (0, 0, 0) and bound init_pso. if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(target as usize))) { + s.last_pc_pso = init_pso; s.native_bias = DepthBias::ZERO; s.using_fallback_pso = false; s.pso_dirty = false; @@ -4014,6 +4050,9 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b if let Some(base) = need_restore_base { let resolved = super::pso_async::resolve_for_bind(base); pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.last_pc_pso = resolved; + } } if !need_native_call { return; @@ -4058,6 +4097,9 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b if let Some(base) = restore { let resolved = super::pso_async::resolve_for_bind(base); pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&key)) { + s.last_pc_pso = resolved; + } } } @@ -4099,6 +4141,7 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { let resolved = super::pso_async::resolve_for_bind(target); pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.last_pc_pso = resolved; s.using_fallback_pso = is_fallback; } } @@ -4777,6 +4820,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); s.allocator = alloc; s.bound_pso = pso; + s.last_pc_pso = resolved; s.depth_bias = None; s.native_bias = DepthBias::ZERO; s.pso_dirty = false; @@ -8694,4 +8738,33 @@ mod tests { assert_eq!(free_count, RT_SHADOW_CHUNK_SLOTS as usize, "all shadow slots must recycle on release"); } } + + #[test] + fn redundant_pso_bind_cache_skips_identical_and_invalidates_on_upgrade_or_reset() { + let list = 0x7E57_B1D0usize as *mut c_void; + unsafe { + on_create(list, 0xA110_0001, 0, D3D12_COMMAND_LIST_TYPE_DIRECT); + // First bind is never skipped. + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x2000)); + on_set_pipeline_state_bound(list, 0x1000, 0x2000); + // Exact same (pso, resolved) is skipped. + assert!(skip_redundant_pso_bind(list, 0x1000, 0x2000)); + // Async compile completion: same title PSO resolves to a new real PC PSO -> must bind! + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x3000)); + on_set_pipeline_state_bound(list, 0x1000, 0x3000); + assert!(skip_redundant_pso_bind(list, 0x1000, 0x3000)); + // Different title PSO -> must bind! + assert!(!skip_redundant_pso_bind(list, 0x1001, 0x3001)); + // ClearState / PC Reset / segment clear invalidate the cached PC PSO. + on_clear_state(list, 0x1000); + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x3000)); + on_set_pipeline_state_bound(list, 0x1000, 0x3000); + on_pc_reset(list); + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x3000)); + on_set_pipeline_state_bound(list, 0x1000, 0x3000); + clear_segment_state(list as usize); + assert!(!skip_redundant_pso_bind(list, 0x1000, 0x3000)); + on_release(list as usize); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9ce80183a7..8e7f0c3d16 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2488,21 +2488,19 @@ pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, des /// Copy `n` console slots from `src` to `dst` (both in console heaps of one kind): the PC /// descriptors (2 per view slot) and the slots. False: not two console ranges. unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) -> bool { - use super::console_heap::{copy_words, slot, SAMPLER_SLOT, SLOT}; + use super::console_heap::{copy_words_range, slot}; let (Some(d0), Some(s0)) = (slot(dst), slot(src)) else { return false }; if d0.sampler != s0.sampler { return false; } + if n == 0 || d0.at == s0.at { + return true; + } let ty = pc_heap_type(ty); let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, if d0.sampler { n } else { 2 * n }, d0.pc_srv, s0.pc_srv, ty); super::console_heap::publish_range(&d0, n); - let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64; - for k in 0..n as u64 { - if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) { - copy_words(&s, &d); - } - } + copy_words_range(dst, src, n); true } @@ -2554,20 +2552,37 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst let f: F = std::mem::transmute(orig_fn(this, 23)); return f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); } - // every descriptor as (dst, src) handle, ranges walked in step + // Walk (dst, src) ranges in lockstep with zero heap allocations, batching each maximal + // contiguous overlap into a single `copy_console_slots` call. let step = if ty == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32 { SAMPLER_SLOT } else { SLOT } as u64; - let expand = |starts: *const u64, sizes: *const u32, n: u32| -> Vec { - (0..n as usize).flat_map(|r| { - let (h, len) = (*starts.add(r), if sizes.is_null() { 1 } else { *sizes.add(r) }); - (0..len as u64).map(move |k| h + k * step) - }) - .collect() - }; - let (d, s) = (expand(dsts, dsizes, nd), expand(srcs, ssizes, ns)); - for (a, b) in d.iter().zip(s.iter()) { - if !copy_console_slots(this, 1, *a, *b, ty) { + let (mut di, mut si) = (0usize, 0usize); + let (mut d_rem, mut s_rem) = (0u32, 0u32); + let (mut d_cur, mut s_cur) = (0u64, 0u64); + loop { + while d_rem == 0 { + if di >= nd as usize { + return; + } + d_cur = *dsts.add(di); + d_rem = if dsizes.is_null() { 1 } else { *dsizes.add(di) }; + di += 1; + } + while s_rem == 0 { + if si >= ns as usize { + return; + } + s_cur = *srcs.add(si); + s_rem = if ssizes.is_null() { 1 } else { *ssizes.add(si) }; + si += 1; + } + let run = d_rem.min(s_rem); + if !copy_console_slots(this, run, d_cur, s_cur, ty) { note_mixed_copy(); } + d_cur = d_cur.wrapping_add(run as u64 * step); + s_cur = s_cur.wrapping_add(run as u64 * step); + d_rem -= run; + s_rem -= run; } } @@ -8275,12 +8290,15 @@ pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { } unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_void) { + let bound = super::pso_async::resolve(pso as usize); + if super::list_x::skip_redundant_pso_bind(this, pso as usize, bound) { + return; + } type F = unsafe extern "system" fn(*mut c_void, *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState"))); - let bound = super::pso_async::resolve(pso as usize); f(this, bound as *mut c_void); super::dred::mark_pipeline(this, pso as usize, bound); - super::list_x::on_set_pipeline_state(this, pso as usize); + super::list_x::on_set_pipeline_state_bound(this, pso as usize, bound); } /// The title's markers are counted for `XCL_DRED=1`'s pipeline labels (`dred`). diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 8496a4b175..5f9dfd1e5d 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -2147,33 +2147,57 @@ pub fn host_os_version() -> (u32, u32, u32) { /// The finest timer Windows offers (0.5 ms) for the title: with the default 15.6 ms tick every /// sleep rounds up (a retail game's audio mixer ran at a third of real time). Windows 11 keeps -/// it while the window is hidden only when told to. +/// it while the window is hidden only when told to. Also opt out of Windows 11 Efficiency Mode +/// (`PROCESS_POWER_THROTTLING_EXECUTION_SPEED`) and lift process priority to `ABOVE_NORMAL` so +/// foreground title rendering/streaming threads are not demoted behind background OS work +/// (`XCL_PRIORITY=0` disables priority boost). pub fn fine_timer() { use windows_sys::Win32::System::Threading::{ - GetCurrentProcess, ProcessPowerThrottling, SetProcessInformation, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + GetCurrentProcess, ProcessPowerThrottling, SetPriorityClass, SetProcessInformation, ABOVE_NORMAL_PRIORITY_CLASS, + PROCESS_POWER_THROTTLING_CURRENT_VERSION, PROCESS_POWER_THROTTLING_EXECUTION_SPEED, PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, }; - let state = PROCESS_POWER_THROTTLING_STATE { + let size = std::mem::size_of::() as u32; + let combined = PROCESS_POWER_THROTTLING_STATE { Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, - ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + ControlMask: PROCESS_POWER_THROTTLING_EXECUTION_SPEED | PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, StateMask: 0, }; - let size = std::mem::size_of::() as u32; - let kept = unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &state as *const _ as *const c_void, size) } != 0; + let mut kept = unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &combined as *const _ as *const c_void, size) } != 0; + if !kept { + let timer_only = PROCESS_POWER_THROTTLING_STATE { + Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, + ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + StateMask: 0, + }; + kept = unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &timer_only as *const _ as *const c_void, size) } != 0; + let eco_only = PROCESS_POWER_THROTTLING_STATE { + Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION, + ControlMask: PROCESS_POWER_THROTTLING_EXECUTION_SPEED, + StateMask: 0, + }; + unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &eco_only as *const _ as *const c_void, size) }; + } + let boosted = if std::env::var("XCL_PRIORITY").map_or(true, |v| v.trim() != "0") { + unsafe { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS) != 0 } + } else { + false + }; // in 100 ns units; "finest" is the smallest period the system supports let (mut coarsest, mut finest, mut was) = (0u32, 0u32, 0u32); if unsafe { NtQueryTimerResolution(&mut coarsest, &mut finest, &mut was) } < 0 || finest == 0 { - crate::xlog_warn!("timer: NtQueryTimerResolution failed – Windows' default resolution"); + crate::xlog_warn!("timer: NtQueryTimerResolution failed – Windows' default resolution (above-normal priority: {boosted})"); return; } let mut now = 0u32; let status = unsafe { NtSetTimerResolution(finest, 1, &mut now) }; crate::xlog_info!( - "timer: {} (was {:.2} ms, now {:.2} ms; kept while the window is hidden: {})", + "timer: {} (was {:.2} ms, now {:.2} ms; EcoQoS/timer-throttle off: {}; above-normal priority: {})", if status >= 0 { "finest resolution for the title" } else { "raising the resolution failed" }, was as f64 / 10_000.0, now as f64 / 10_000.0, - if kept { "yes" } else { "no" } + if kept { "yes" } else { "no" }, + if boosted { "yes" } else { "no" } ); } From dece6dd978b4df8c7efa48cd3e6315d6605acbc6 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:43:55 +0100 Subject: [PATCH 142/258] D3D12.X: keep GPU-owned and GPU-aliased VRAM textures fully mapped Fixes two reserved-texture tile-mapping gaps that leave live [type 34] textures with unmapped NULL tiles on AMD RDNA4 (seen faulting cs ef5ece922dc33bfe): 1. vram::place_pages checked has_live_page() to bypass vram_small when a sampled Texture2D aliases a live 64 KiB GPU-owned page (render target, depth buffer, or Hi-Z UAV pyramid), yet still set lazy=true under XCL_TEXTURE_LEVEL_PAGES=1. Because CPU memory at a GPU-owned target VA is zeros, map_levels_with_texels never mapped any tiles on the aliased SRV. Disable lazy levels when aliases_live is true (reusing the existing live pages at zero extra VRAM cost). 2. vram::place (GPU-owned RT | DS | UAV textures) passed follow_key=Some(raw) into Pages::bind, allowing FollowSkip (#1514) to leave uncommitted tiles unmapped when a GPU-written target overlaps GRAPHICS_RESERVATIONS. Gate FollowSkip on !require_aligned (sampled textures only) and preserve follow_backing across remap_if_unmapped. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/vram.rs | 129 +++++++++++++++++++++++++++--- 1 file changed, 118 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index a85889d66e..2db2646061 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -400,6 +400,9 @@ struct Target { used_extra: Vec<(usize, usize)>, /// its owned pages in graphics reservations (`Pages::follow`) follows: Vec, + /// whether uncommitted pages in graphics reservations may be skipped (`FollowSkip`): + /// true for sampled textures (`place_pages`), false for GPU-owned `RT | DS | UAV` targets (`place`) + follow_backing: bool, /// its levels get their pages one by one (`map_levels`); None: all of it has pages levels: Option, recycle: Option, @@ -1251,11 +1254,24 @@ impl Pages { } /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. - /// A page in a graphics reservation the title has no memory at yet is left unmapped (tier 2: - /// reads zero) and mapped when the title puts memory there (`apply_backing`); the texture's - /// followed pages are returned third. + /// When `follow_key` is `Some`, a page in a graphics reservation the title has no memory at + /// yet is left unmapped (tier 2: reads zero) and mapped when the title puts memory there + /// (`apply_backing`); GPU-owned targets (`RT | DS | UAV`) pass `None` so every tile is backed. + unsafe fn bind_with_follow( + &mut self, + dev: &ID3D12Device, + res: &ID3D12Resource, + follow_key: Option, + va: usize, + console_bytes: Option, + total: u32, + ) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { + self.bind_range(dev, res, follow_key, va, console_bytes, total, 0, 0..total as usize) + } + + #[cfg(test)] unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, key: usize, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { - self.bind_range(dev, res, Some(key), va, console_bytes, total, 0, 0..total as usize) + self.bind_with_follow(dev, res, Some(key), va, console_bytes, total) } /// `bind` for the tiles `range` of the resource's `total`, which start at subresource `sub`. @@ -1757,6 +1773,7 @@ unsafe fn place_on_pages( lv } }; + let follow_backing = !require_aligned; let bound = { let timer = step(Step::Lock); let mut g = PAGES.lock().unwrap(); @@ -1766,10 +1783,10 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used: Vec::new(), used_extra: Vec::new(), follows: Vec::new(), levels, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used: Vec::new(), used_extra: Vec::new(), follows: Vec::new(), follow_backing, levels, recycle: recycle_key }); true - } else if let Some((used, used_extra, follows)) = pages.bind(dev, res, raw as usize, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used, used_extra, follows, levels: None, recycle: recycle_key }); + } else if let Some((used, used_extra, follows)) = pages.bind_with_follow(dev, res, follow_backing.then_some(raw as usize), va, console_bytes, total) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used, used_extra, follows, follow_backing, levels: None, recycle: recycle_key }); true } else { false @@ -1847,7 +1864,7 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { let key = res.as_raw() as usize; let mut g = PAGES.lock().unwrap(); let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; - let Some((va, console_bytes, total, mapped)) = pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped)) else { + let Some((va, console_bytes, total, mapped, follow_backing)) = pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped, t.follow_backing)) else { return false; }; if mapped { @@ -1859,7 +1876,7 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.mapping_gen = t.mapping_gen.wrapping_add(1); return true; } - let Some((used, used_extra, follows)) = pages.bind(&dev, res, key, va, console_bytes, total) else { + let Some((used, used_extra, follows)) = pages.bind_with_follow(&dev, res, follow_backing.then_some(key), va, console_bytes, total) else { return false; }; if let Some(t) = pages.targets.get_mut(&key) { @@ -2276,6 +2293,20 @@ fn tier2(dev: &ID3D12Device) -> bool { unsafe { dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut o as *mut _ as *mut c_void, std::mem::size_of_val(&o) as u32).is_ok() && o.ResourceHeapTier.0 >= 2 } } +/// Whether a sampled reserved texture should defer tile mapping per mip level (`level_pages`). +/// Sampled views aliasing an already-live 64 KiB GPU page (`aliases_live`, e.g., an SRV placed +/// over a render target, depth buffer, or Hi-Z UAV pyramid) must map immediately onto those live +/// pages rather than staying lazy: their CPU memory is zeros so upload-driven level mapping +/// would leave every tile unmapped. +fn should_use_lazy_levels(level_pages_on: bool, aliases_live: bool, desc: &D3D12_RESOURCE_DESC) -> bool { + !aliases_live + && level_pages_on + && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && desc.DepthOrArraySize == 1 + && desc.SampleDesc.Count == 1 + && desc.Flags == D3D12_RESOURCE_FLAG_NONE +} + /// A sampled texture of the title at `va` (`desc`: the PC description, `console_bytes` its size on /// the console) backed by shared 4 KiB small-resource heaps (when < 64 KiB and not aliasing an /// existing 64 KiB GPU page) or shared 64 KiB video-memory pages; None when neither applies (the @@ -2298,14 +2329,15 @@ pub unsafe fn place_pages( if console_has_packed_3d_mips(desc) { return None; } - if !(va % PAGE == 0 && has_live_page(dev.as_raw() as usize, canonical_va(va))) { + let aliases_live = va % PAGE == 0 && has_live_page(dev.as_raw() as usize, canonical_va(va)); + if !aliases_live { if let Some(hr) = super::vram_small::place(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); return Some(hr); } } // (one slice: the tiles of an array's packed levels are not asked about here) - let lazy = level_pages() && desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.DepthOrArraySize == 1 && desc.SampleDesc.Count == 1 && desc.Flags == D3D12_RESOURCE_FLAG_NONE; + let lazy = should_use_lazy_levels(level_pages(), aliases_live, desc); place_on_pages(dev, this, va, desc, state, clear, console_bytes, false, lazy, riid, ppv) } @@ -3363,4 +3395,79 @@ mod tests { assert!(!commit_below_floor(None, FLOOR)); assert!(!commit_below_floor(Some(0), 0)); } + + #[test] + fn should_use_lazy_levels_skips_gpu_aliased_sampled_textures() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R16_FLOAT, DXGI_SAMPLE_DESC}; + let tex = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1024, + Height: 1024, + DepthOrArraySize: 1, + MipLevels: 10, + Format: DXGI_FORMAT_R16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + assert!(should_use_lazy_levels(true, false, &tex)); + assert!(!should_use_lazy_levels(true, true, &tex), "sampled view aliasing a live GPU page must map eagerly"); + assert!(!should_use_lazy_levels(false, false, &tex)); + let mut uav = tex; + uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + assert!(!should_use_lazy_levels(true, false, &uav)); + let mut arr = tex; + arr.DepthOrArraySize = 2; + assert!(!should_use_lazy_levels(true, false, &arr)); + } + + #[test] + fn gpu_owned_bind_with_no_follow_maps_uncommitted_graphics_reservation_tiles() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R16_FLOAT, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let Some(mut pages) = Pages::new(&dev) else { + return crate::gpu::recomp::runner::skip_test("tiled tier < 2"); + }; + let span = 4 * PAGE; + let va = VirtualAlloc(std::ptr::null(), span, MEM_RESERVE, PAGE_READWRITE) as usize; + assert!(va != 0 && va % PAGE == 0); + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 256, + Height: 256, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut r: Option = None; + dev.CreateReservedResource(&desc, D3D12_RESOURCE_STATE_COMMON, None, &mut r).unwrap(); + let res = r.unwrap(); + let mut total = 0u32; + dev.GetResourceTiling(&res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); + assert!(total >= 1 && (total as usize) * PAGE <= span); + + let (used, extra, follows) = pages + .bind_with_follow(&dev, &res, None, va, Some(total as u64 * PAGE as u64), total) + .expect("GPU-owned bind must map every tile even when title VA is uncommitted"); + assert_eq!(used.len() + extra.len(), total as usize); + assert!(follows.is_empty(), "GPU-owned target must not register FollowSkip entries"); + assert!(pages.follow.is_empty()); + + pages.unmap(&res, total); + pages.flush_signal(); + let _ = pages.fence.SetEventOnCompletion(pages.value, windows::Win32::Foundation::HANDLE::default()); + drop(res); + VirtualFree(va as *mut c_void, 0, MEM_RELEASE); + } + } } From 95e1602d45525cc9f3f0edec7f5b8ba98b9917d0 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:46:08 +0100 Subject: [PATCH 143/258] D3D12.X: read DRED ObjectNameW/pObject and name VRAM/sparse resources DRED page-fault diagnostics previously queried only ID3D12DeviceRemovedExtendedData::GetPageFaultAllocationOutput and read ObjectNameA, which is NULL whenever ID3D12Object::SetName (UTF-16) is used, leaving faulting resources logged as anonymous [type 34 ]. Prefer ID3D12DeviceRemovedExtendedData1::GetPageFaultAllocationOutput1 (with ObjectNameW -> ObjectNameA fallback and pObject pointer), and when XCL_DRED=1 is enabled name VRAM reserved textures (with title VA, dimensions, mip count, format, flags, lazy bit), VRAM pool/arena heaps, and sparse windows/buffers/staging resources. Zero overhead when XCL_DRED is unset. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 117 ++++++++++++++++++++++++---- crates/xcl/src/hle/d3d12x/sparse.rs | 15 ++++ crates/xcl/src/hle/d3d12x/vram.rs | 19 +++++ 3 files changed, 136 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 8e7f0c3d16..157a03895c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -544,7 +544,7 @@ pub fn init() -> Result { // `XCL_DRED=1`: on a device removal the faulting address and the last GPU operations // (logged by `log_device_removed`); no debug layer needed. Opt-in: with it XDefiant // stalled in its first seconds twice. - if std::env::var_os("XCL_DRED").is_some() { + if dred_on() { match crate::gpu::agility::configuration_interface::( &CLSID_D3D12DeviceRemovedExtendedData, ) { @@ -1630,6 +1630,9 @@ unsafe fn place_console_texture(this: *mut c_void, desc: usize, state: usize, cl return None; } UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, size as usize, true)); + if dred_on() { + name_resource(*ppv, &format!("xcl uma_tex p={p:#x}")); + } Some(hr) } @@ -1686,6 +1689,9 @@ unsafe fn place_console_buffer_sparse(this: *mut c_void, d: &D3D12_RESOURCE_DESC let (p, _) = super::sparse::alloc(bytes, 0x1_0000)?; if let Some((hr, delta)) = super::sparse::place_buffer(this, p, d, state, riid, ppv) { UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + if dred_on() { + name_resource(*ppv, &format!("xcl sparse_buf p={p:#x} sz={bytes:#x}")); + } if delta != 0 { BUFFER_DELTA.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64); } @@ -1752,6 +1758,9 @@ unsafe fn place_console_buffer(this: *mut c_void, props: usize, desc: usize, sta return None; } UMA_BUFFERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true)); + if dred_on() { + name_resource(*ppv, &format!("xcl uma_buf p={p:#x} sz={bytes:#x}")); + } // Map must hand out the same memory the shaders read (checked once) static CHECKED: AtomicU64 = AtomicU64::new(0); if CHECKED.fetch_add(1, Ordering::Relaxed) == 0 { @@ -8757,6 +8766,49 @@ pub fn drain_gpu() { } } +/// Whether DRED diagnostics were requested via `XCL_DRED=1`. +pub(super) fn dred_on() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("XCL_DRED").is_some()) +} + +/// Name an `ID3D12Resource` when `XCL_DRED=1` so DRED page-fault output identifies which internal +/// or placed allocation owns the faulting GPU VA. +pub(super) unsafe fn name_resource(res: *mut c_void, label: &str) { + if !dred_on() || res.is_null() { + return; + } + if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { + let _ = r.SetName(&windows::core::HSTRING::from(label)); + } +} + +/// Name an `ID3D12Heap` when `XCL_DRED=1` so DRED page-fault output identifies backing pool heaps. +pub(super) unsafe fn name_heap(heap: *mut c_void, label: &str) { + if !dred_on() || heap.is_null() { + return; + } + if let Some(h) = ID3D12Heap::from_raw_borrowed(&heap) { + let _ = h.SetName(&windows::core::HSTRING::from(label)); + } +} + +/// Read a DRED allocation node's debug name, preferring `ObjectNameW` (populated by +/// `ID3D12Object::SetName`) and falling back to `ObjectNameA`. +unsafe fn format_dred_allocation_name(name_w: windows::core::PCWSTR, name_a: *const u8) -> String { + if !name_w.is_null() { + if let Ok(s) = name_w.to_string() { + if !s.is_empty() { + return s; + } + } + } + if !name_a.is_null() { + return std::ffi::CStr::from_ptr(name_a as *const std::ffi::c_char).to_string_lossy().into_owned(); + } + String::new() +} + /// DRED gives us a linked list in driver order. Keep the diagnostic bounded even on a /// long chain, with room in the log for work that the GPU had already started. unsafe fn report_dred_lists(head: *const D3D12_AUTO_BREADCRUMB_NODE, mut report: impl FnMut(&D3D12_AUTO_BREADCRUMB_NODE, usize)) { @@ -8800,6 +8852,19 @@ mod dred_tests { assert_eq!((node, done), (std::ptr::from_ref(&nodes[i]), 0)); } } + + #[test] + fn format_dred_allocation_name_prefers_wide_and_falls_back_to_ansi() { + let wide: Vec = "wide_name".encode_utf16().chain([0]).collect(); + let empty_wide: [u16; 1] = [0]; + let ansi = b"ansi_name\0"; + unsafe { + assert_eq!(format_dred_allocation_name(windows::core::PCWSTR(wide.as_ptr()), ansi.as_ptr()), "wide_name"); + assert_eq!(format_dred_allocation_name(windows::core::PCWSTR::null(), ansi.as_ptr()), "ansi_name"); + assert_eq!(format_dred_allocation_name(windows::core::PCWSTR(empty_wide.as_ptr()), ansi.as_ptr()), "ansi_name"); + assert_eq!(format_dred_allocation_name(windows::core::PCWSTR::null(), std::ptr::null()), ""); + } + } } /// If the device was removed: the reason, DRED's page fault (address, the allocations around @@ -8814,21 +8879,43 @@ pub fn log_device_removed() { } crate::xlog_error!("D3D12 device removed: {:#x} {}", e.code().0 as u32, e.message()); unsafe { + let mut pf_logged = false; + if let Ok(dred1) = dev.cast::() { + if let Ok(pf) = dred1.GetPageFaultAllocationOutput1() { + let names = |mut n: *const D3D12_DRED_ALLOCATION_NODE1| { + let mut v = Vec::new(); + while !n.is_null() && v.len() < 8 { + let a = &*n; + let name = format_dred_allocation_name(a.ObjectNameW, a.ObjectNameA); + let ptr = (&*a.pObject).as_ref().map(|obj| format!(" ptr={:#x}", obj.as_raw() as usize)).unwrap_or_default(); + v.push(format!("type {} {}{}", a.AllocationType.0, name, ptr)); + n = a.pNext; + } + v.join(", ") + }; + let va = pf.PageFaultVA; + let window = uma_window_vas().iter().position(|&w| va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); + crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); + pf_logged = true; + } + } let Ok(dred) = dev.cast::() else { return }; - if let Ok(pf) = dred.GetPageFaultAllocationOutput() { - let names = |mut n: *const D3D12_DRED_ALLOCATION_NODE| { - let mut v = Vec::new(); - while !n.is_null() && v.len() < 8 { - let a = &*n; - let name = if a.ObjectNameA.is_null() { String::new() } else { std::ffi::CStr::from_ptr(a.ObjectNameA as *const std::ffi::c_char).to_string_lossy().into_owned() }; - v.push(format!("type {} {}", a.AllocationType.0, name)); - n = a.pNext; - } - v.join(", ") - }; - let va = pf.PageFaultVA; - let window = uma_window_vas().iter().position(|&w| va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); - crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); + if !pf_logged { + if let Ok(pf) = dred.GetPageFaultAllocationOutput() { + let names = |mut n: *const D3D12_DRED_ALLOCATION_NODE| { + let mut v = Vec::new(); + while !n.is_null() && v.len() < 8 { + let a = &*n; + let name = format_dred_allocation_name(a.ObjectNameW, a.ObjectNameA); + v.push(format!("type {} {}", a.AllocationType.0, name)); + n = a.pNext; + } + v.join(", ") + }; + let va = pf.PageFaultVA; + let window = uma_window_vas().iter().position(|&w| va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default(); + crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode)); + } } if let Ok(bc) = dred.GetAutoBreadcrumbsOutput() { report_dred_lists(bc.pHeadAutoBreadcrumbNode, |node, done| { diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 11acd4b994..2b41a276bb 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -534,6 +534,9 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { return Vec::new(); } let Some(r) = r else { return Vec::new() }; + if super::real::dred_on() { + super::real::name_resource(r.as_raw(), &format!("xcl sparse window {k}")); + } out.push((k, r.clone().into_raw() as usize, r.GetGPUVirtualAddress())); windows.push((base, r)); } @@ -932,6 +935,9 @@ impl State { ) .ok()?; let r = r?; + if super::real::dred_on() { + super::real::name_resource(r.as_raw(), "xcl sparse staging"); + } let mut p = std::ptr::null_mut(); r.Map(0, None, Some(&mut p)).ok()?; self.staging = Some((r, p as *mut u8)); @@ -959,6 +965,9 @@ impl State { return false; } let Some(r) = r else { return false }; + if super::real::dred_on() { + super::real::name_resource(r.as_raw(), "xcl sparse zero"); + } let mut p = std::ptr::null_mut(); if r.Map(0, None, Some(&mut p)).is_err() { return false; @@ -986,6 +995,9 @@ impl State { ) .ok()?; let r = r?; + if super::real::dred_on() { + super::real::name_resource(r.as_raw(), "xcl sparse readback"); + } let mut p = std::ptr::null_mut(); r.Map(0, None, Some(&mut p)).ok()?; self.readback = Some((r, p as *mut u8)); @@ -1854,6 +1866,9 @@ pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_D s.ensure_mapped(start, delta + bytes, |t| query_tile_holes(t)); let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); let raw = *ppv; + if super::real::dred_on() { + super::real::name_resource(raw, &format!("xcl sparse_buf va={va:#x} sz={bytes:#x}")); + } let res = ID3D12Resource::from_raw_borrowed(&raw)?.clone(); s.map_tiles(&res, start, &tiles); for &(_, tile) in &tiles { diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 2db2646061..5eb6b8e5f1 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -331,6 +331,11 @@ unsafe fn arena_heap(dev: &ID3D12Device, va: usize, size: usize, align: usize) - if n < 16 || n.is_power_of_two() { crate::xlog_info!("D3D12.X: video-memory arena #{n} for title addresses {va:#x}..{:#x} ({made} bytes of arenas made so far)", va + size); } + if super::real::dred_on() { + if let Some(ref h) = heap { + super::real::name_heap(h.as_raw(), &format!("xcl vram arena va={va:#x}")); + } + } heap } @@ -798,6 +803,11 @@ unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { crate::xlog_warn!("D3D12.X: no video memory for more pages of title textures ({e})"); return None; } + if super::real::dred_on() { + if let Some(ref h) = heap { + super::real::name_heap(h.as_raw(), "xcl vram tile_pool"); + } + } heap } @@ -1747,6 +1757,15 @@ unsafe fn place_on_pages( hr }; let raw = *ppv; + if super::real::dred_on() { + super::real::name_resource( + raw, + &format!( + "xcl vram tex va={va:#x} {}x{}x{} m={} fmt={} fl={:#x} lazy={}", + desc.Width, desc.Height, desc.DepthOrArraySize, desc.MipLevels, desc.Format.0, desc.Flags.0, lazy + ), + ); + } let res = ID3D12Resource::from_raw_borrowed(&raw)?; let mut total = 0u32; let levels = match cached_tiling { From 993b74965dd31c0c187d16790338118d597cd5bd Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:49:04 +0100 Subject: [PATCH 144/258] d3d12x: inline indirect-guard batching, RT bind dedup, root VA cache, water state Clean-room Wave 14 Part 2 runtime GPU/CPU optimizations: 1. Inline 256-slot indirect-dispatch guard batching (bind.rs, list_x.rs; XCL_INLINE_GUARD_BATCH=0 opt-out): when prelude hoisting is blocked after a GPU write, emit one PRELUDE_GUARD_* Dispatch(4,1,1) + barrier pair on the first single indirect dispatch and append up to 255 consecutive indirect dispatches into its coherent UMA job table with zero extra barriers or PSO switches (invalidated on any ResourceBarrier, direct Dispatch, GPU write, scaled mesh args, Reset, or split). 2. State-aware water readback barriers (list_x.rs): pass each water texture's actual state to maybe_enqueue_water_readback, skip barriers when already in COPY_SOURCE, and trigger readback on UAV/RT -> read ResourceBarrier transitions as well as CopyResource / CopyTextureRegion. 3. Semantic OMSetRenderTargets dedup (list_x.rs, real.rs; XCL_BIND_CACHE=0 opt-out): skip identical OMSetRenderTargets binds when RT_DESC_GEN (bumped on CreateRenderTargetView, CreateDepthStencilView, CopyDescriptors*(RTV|DSV)) is unchanged and targets remain live on the PC list. 4. Per-list outside-UMA root descriptor VA cache (bind.rs): 16-entry MRU cache + coherent-UMA fast path in set_{graphics,compute}_root_descriptor so repeatedly bound frame/pass/material CBVs skip global map locks. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 171 +++++++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 108 +++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 11 ++ 3 files changed, 281 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 261264b977..dc537cb3fd 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -201,10 +201,39 @@ struct State { io_cache_cs: Option<(u64, Option, u64)>, io_cache_tp_cs: Option<(u64, u64)>, io_cache_tp_ms: Option<(u64, u64)>, + /// Active inline 256-slot indirect-dispatch guard batch: one inline `PRELUDE_GUARD_*` + /// `Dispatch(4, 1, 1)` + barrier pair already emitted on this list, with subsequent + /// consecutive single indirect dispatches (up to 256, invalidated on any GPU write/barrier) + /// appending their 32-byte clamp jobs into its coherent UMA job table with zero extra barriers. + inline_guard: Option, + /// Per-list 16-entry MRU cache of resolved outside-UMA root descriptor VAs (`raw -> resolved`) + /// so repeatedly binding the same frame/pass/material CBV skips global `resolve_uma_va` and + /// `sparse::gpu_view` lock lookups. + root_va_cache: [(u64, u64); 16], + root_va_next: usize, /// L1 VRAM `io` (`u0`) slabs populated during this recording and copied in `prelude_list_for` io_blocks: Vec, } +/// Active inline 256-slot indirect-dispatch guard batch recorded directly on a command list. +struct InlineGuardBatch { + /// Host pointer to `[count, 0, 0, 0]` + 256 × 32-byte `PreludeGuardJob` records in coherent UMA. + jobs_cpu: usize, + /// Committed scratch buffer holding 256 × 256-byte guarded argument outputs (`GUARDED_ARGS_STATE`). + dst: ID3D12Resource, + dst_base_off: u64, + count: u32, +} + +const INLINE_GUARD_BATCH_MAX: u32 = 256; +const INLINE_GUARD_JOBS_BYTES: usize = 16 + INLINE_GUARD_BATCH_MAX as usize * 32; +const INLINE_GUARD_DST_BYTES: u64 = INLINE_GUARD_BATCH_MAX as u64 * 256; + +fn inline_guard_batch_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INLINE_GUARD_BATCH").map_or(true, |v| v.trim() != "0")) +} + /// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its /// two-pass ExecuteIndirects are skipped) const SCRATCH_BLOCK: u64 = 1 << 20; @@ -446,14 +475,24 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { /// Note that the active recording segment issued a GPU buffer write or cross-queue fence wait: /// subsequent indirect argument clamps must execute inline instead of hoisting into the prelude, +/// any open inline indirect-guard batch is closed so later dispatches observe the new writes, /// and indirect argument ordering is no longer clean. pub(super) fn note_gpu_write(list: *mut c_void) { with(list, |s| { s.prelude_blocked = true; + s.inline_guard = None; s.arg_order_clean = false; }); } +/// Close any open inline indirect-guard batch on `list` (called on `ResourceBarrier` / direct +/// `Dispatch` so subsequent indirect dispatches see post-barrier argument bytes). +pub(super) fn invalidate_inline_guard(list: *mut c_void) { + with(list, |s| { + s.inline_guard = None; + }); +} + /// Allow indirect-argument prelude hoisting on a freshly split continuation segment whose /// predecessor finished on the same queue with no cross-queue head fence wait. pub(super) fn unblock_prelude(list: *mut c_void) { @@ -500,6 +539,9 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.prelude_scales.clear(); let prelude = s.prelude_owned.take(); s.prelude_built = None; + s.inline_guard = None; + s.root_va_cache = [(0, 0); 16]; + s.root_va_next = 0; s.arg_order_clean = false; s.uma_windows = None; s.dummy_res_va = 0; @@ -568,6 +610,7 @@ pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { s.prelude_scales.clear(); let prelude = s.prelude_owned.take(); s.prelude_built = None; + s.inline_guard = None; s.dummy_res_va = 0; s.io_cache_gfx = None; s.io_cache_cs = None; @@ -618,6 +661,9 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.prelude_scales.clear(); let prelude = s.prelude_owned.take(); s.prelude_built = None; + s.inline_guard = None; + s.root_va_cache = [(0, 0); 16]; + s.root_va_next = 0; s.arg_order_clean = false; s.uma_windows = None; s.dummy_res_va = 0; @@ -781,10 +827,31 @@ pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_vo /// #40 / #42) pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_void, i: u32, va: u64) { note_address(va); - let va = readable_root(va); + let va = resolve_root_for_list(this, va); put_in(this, true, i, 0, &va.to_le_bytes()); } +/// Resolve a root descriptor VA for `list`, short-circuiting coherent-UMA addresses and caching +/// outside-UMA resolutions per recording (`root_va_cache`) to avoid repeated global map lookups +/// when the title rebinds the same frame/pass/material CBVs across consecutive draws. +fn resolve_root_for_list(list: *mut c_void, va: u64) -> u64 { + if va == 0 || crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)) { + return va; + } + if let Some(hit) = with(list, |s| { + s.root_va_cache.iter().find(|&&(raw, _)| raw == va).map(|&(_, resolved)| resolved) + }) { + return hit; + } + let resolved = readable_root(va); + with(list, |s| { + let idx = s.root_va_next & 15; + s.root_va_cache[idx] = (va, resolved); + s.root_va_next = s.root_va_next.wrapping_add(1); + }); + resolved +} + /// The address a root descriptor at `va` gets: first try resolving a GPU-view VA directly to /// contiguous UMA backing (`real::resolve_uma_va`, zero-copy for both reads and root UAV writes), /// then fall back to the read-only `sparse::gpu_view` mirror for scattered mappings. @@ -2195,6 +2262,100 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis } } } + // Inline 256-slot offset-table batching (`XCL_INLINE_GUARD_BATCH=0` opt-out): when prelude + // hoisting is blocked (after a compute/UAV write), emit ONE `PRELUDE_GUARD_*` `Dispatch(4,1,1)` + // + barrier pair on the first indirect dispatch and append up to 255 subsequent consecutive + // indirect dispatches into its coherent UMA job table with zero extra barriers or PSO switches. + if inline_guard_batch_on() { + if let (Some((src_win, src_off)), Some((lim_win, lim_off))) = ( + uma_win_off(u, src, 12), + uma_win_off(u, dispatch_io_host + crate::gpu::recomp::IO_GROUP_LIMIT * 4, 4), + ) { + let most = most_groups(); + let appended = with(this, |s| { + let b = s.inline_guard.as_mut()?; + if b.count >= INLINE_GUARD_BATCH_MAX { + return None; + } + let idx = b.count; + let rec = [src_win, src_off, most, idx * 256, lim_win, lim_off, 0u32, 0u32]; + let slot_ptr = (b.jobs_cpu + 16 + idx as usize * 32) as *mut u32; + std::ptr::copy_nonoverlapping(rec.as_ptr(), slot_ptr, rec.len()); + (*(b.jobs_cpu as *const std::sync::atomic::AtomicU32)).store(idx + 1, Ordering::Release); + b.count = idx + 1; + Some((b.dst.clone(), b.dst_base_off + idx as u64 * 256)) + }); + if let Some(res) = appended { + return Ok(res); + } + let use_heap = super::console_heap::window_views_ready(); + let win_ok = use_heap || (src_win < 4 && lim_win < 4); + if win_ok { + let win_vas = if use_heap { + Some([0u64; 4]) + } else { + with(this, |s| { + if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { + s.uma_windows = Some(super::real::uma_window_vas()); + } + let w = s.uma_windows.as_deref()?; + let first = *w.first().filter(|&&v| v != 0)?; + Some([ + first, + w.get(1).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(2).copied().filter(|&v| v != 0).unwrap_or(first), + w.get(3).copied().filter(|&v| v != 0).unwrap_or(first), + ]) + }) + }; + if let Some(win_vas) = win_vas { + let jobs_p = with(this, |s| s.arena.take(u, INLINE_GUARD_JOBS_BYTES, 256, &mut s.uma)); + if let Some(jobs_p) = jobs_p { + if let Some(jobs_va) = super::real::uma_va_of(jobs_p as usize) { + with(this, |s| s.inline_guard = None); + let (dst, dst_base_off, slot, prev_state) = scratch_args_pingpong(this, &dev, INLINE_GUARD_DST_BYTES)?; + let dst_va = dst.GetGPUVirtualAddress() + dst_base_off; + let hdr = [1u32, 0, 0, 0]; + let rec0 = [src_win, src_off, most, 0u32, lim_win, lim_off, 0u32, 0u32]; + std::ptr::copy_nonoverlapping(hdr.as_ptr(), jobs_p as *mut u32, hdr.len()); + std::ptr::copy_nonoverlapping(rec0.as_ptr(), (jobs_p as usize + 16) as *mut u32, rec0.len()); + let (rs, pso) = if use_heap { + super::list_x::ensure_view_heap(this); + prelude_guard_heap_pipeline(&dev)? + } else { + prelude_guard_pipeline(&dev)? + }; + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + if !use_heap { + for (k, &va) in win_vas.iter().enumerate() { + list.SetComputeRootUnorderedAccessView((2 + k) as u32, va); + } + } + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.Dispatch(INLINE_GUARD_BATCH_MAX / 64, 1, 1); + emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); + with(this, |s| { + s.scratch[slot].state = GUARDED_ARGS_STATE; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + s.inline_guard = Some(InlineGuardBatch { + jobs_cpu: jobs_p as usize, + dst: dst.clone(), + dst_base_off, + count: 1, + }); + }); + return Ok((dst, dst_base_off)); + } + } + } + } + } + } + with(this, |s| s.inline_guard = None); let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, 256)?; let lim_off = (crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32; let dst_va = dst.GetGPUVirtualAddress() + dst_off; @@ -2518,6 +2679,7 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman } } } + with(this, |s| s.inline_guard = None); let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, commands.saturating_mul(2))?; let dst_va = dst.GetGPUVirtualAddress() + dst_off; if super::console_heap::window_views_ready() { @@ -3596,7 +3758,7 @@ pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_voi /// #39 / #41): the 64-bit GPU address pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) { note_address(va); - let va = readable_root(va); + let va = resolve_root_for_list(this, va); put(this, i, 0, &va.to_le_bytes()); } @@ -3608,7 +3770,10 @@ pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { - let pso = with(this, |s| s.pso); + let pso = with(this, |s| { + s.inline_guard = None; + s.pso + }); if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) { return super::pso_async::need_by_submit(pso); } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index aec209bc0c..b097a914c5 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -483,6 +483,15 @@ unsafe fn alloc_rt_shadow_slot(dev: &ID3D12Device) -> Option> Some(Arc::new(RtShadowSlot { dev_key, entry })) } +/// Monotonic generation bumped whenever any CPU RTV or DSV descriptor slot is created or +/// overwritten (`CreateRenderTargetView`, `CreateDepthStencilView`, `CopyDescriptors*(RTV|DSV)`). +/// Semantic `OMSetRenderTargets` dedup skips a rebind only when this generation is unchanged. +static RT_DESC_GEN: AtomicU64 = AtomicU64::new(1); + +pub(super) fn bump_rt_desc_gen() { + RT_DESC_GEN.fetch_add(1, Ordering::Release); +} + /// Recorded `OMSetRenderTargets` state for `KickoffX` / split restoration and `XCL_TRACE_FRAME`. #[derive(Clone, Debug, PartialEq, Eq)] struct RenderTargets { @@ -498,6 +507,10 @@ struct RenderTargets { shadow: Option>, shadow_has_rtvs: bool, shadow_has_dsv: bool, + /// `RT_DESC_GEN` observed when these targets were bound on this list. + desc_gen: u64, + /// True when these exact targets are currently active on the PC command list. + live_on_pc: bool, } /// What console code set on a list that a PC Reset clears: `KickoffX` closes, submits and @@ -744,8 +757,43 @@ pub(super) unsafe extern "system" fn om_set_stencil_ref_x(this: *mut c_void, r: pc::(this, PC_OM_SET_STENCIL_REF)(this, r) } +/// Whether `OMSetRenderTargets(n, rtvs, single, dsv)` is semantically identical to what is +/// already active on `this` (same handles/counts/single/DSV and no RTV/DSV CPU descriptor slot +/// was created or copied since that bind). Opt-out via `XCL_BIND_CACHE=0`. +pub(super) unsafe fn skip_redundant_render_targets( + this: *mut c_void, + n: u32, + rtvs: *const usize, + single: i32, + dsv: *const usize, +) -> bool { + if !bind_cache_enabled() || super::present::trace_frame() || this.is_null() { + return false; + } + let num_targets = if rtvs.is_null() { 0 } else { n.min(D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) }; + let read_count = if single != 0 { num_targets.min(1) } else { num_targets } as usize; + let slice: &[usize] = if read_count == 0 { &[] } else { std::slice::from_raw_parts(rtvs, read_count) }; + let d = dsv.as_ref().copied(); + let cur_gen = RT_DESC_GEN.load(Ordering::Acquire); + LISTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(this as usize))) + .and_then(|s| s.bindings.render_targets.as_ref()) + .is_some_and(|rt| { + rt.live_on_pc + && rt.desc_gen == cur_gen + && rt.num_targets == num_targets + && rt.single == single + && rt.dsv == d + && rt.handles.as_slice() == slice + }) +} + /// OMSetRenderTargets as the PC list got it (`real::cl_om_set_render_targets`) pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { + let desc_gen = RT_DESC_GEN.load(Ordering::Acquire); let num_targets = if rtvs.is_null() { 0 } else { n.min(D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) }; let read_count = if single != 0 { num_targets.min(1) } else { num_targets } as usize; // SAFETY: `rtvs` is non-null whenever `read_count > 0`, and D3D12 requires at least 1 @@ -841,6 +889,8 @@ pub(super) unsafe fn note_render_targets(this: *mut c_void, n: u32, rtvs: *const shadow, shadow_has_rtvs, shadow_has_dsv, + desc_gen, + live_on_pc: true, }); }); } @@ -4968,7 +5018,22 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 super::title_textures::note_transitions(this as usize, &t); } if !out.is_empty() { + super::bind::invalidate_inline_guard(this); pc::(this, PC_RESOURCE_BARRIER)(this, out.len() as u32, out.as_ptr()); + if super::cpu_writes::has_water_readback() { + const WRITE_STATES: u32 = UNORDERED_ACCESS | 0x4; // UNORDERED_ACCESS | RENDER_TARGET + for b in &out { + if b[0] == 0 + && b[1] == 0 + && (b[4] == 0 || b[4] == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) + && (b[5] & WRITE_STATES) != 0 + && (b[6] & WRITE_STATES) == 0 + { + let res = (b[2] as u64 | (b[3] as u64) << 32) as usize; + maybe_enqueue_water_readback(this, res, D3D12_RESOURCE_STATES(b[6] as i32)); + } + } + } } if !depth_syncs.is_empty() { super::depth_uav::execute_syncs(this, &depth_syncs); @@ -5157,7 +5222,7 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds pc::(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx); } if water_dst != 0 { - maybe_enqueue_water_readback(this, water_dst); + maybe_enqueue_water_readback(this, water_dst, D3D12_RESOURCE_STATE_COPY_DEST); } std::mem::forget((d, s)); // borrowed resource pointers } @@ -5292,9 +5357,10 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v /// If `dst` is a tracked placed ocean height/displacement/buoyancy texture (`256×256` /// `R32_FLOAT`/`R32G32_FLOAT`, `64×64` `R32G32_FLOAT`, or `128×128` `R16G16_UINT`), copy -/// subresource 0 into a pooled `READBACK` buffer and queue asynchronous XOR-swizzled writeback +/// subresource 0 into a pooled `READBACK` buffer using its actual current `cur_state` (skipping +/// redundant barriers if already in `COPY_SOURCE`) and queue asynchronous XOR-swizzled writeback /// into console memory on `xcl-cpu-writes` after this submission's GPU fence completes. -unsafe fn maybe_enqueue_water_readback(this: *mut c_void, dst: usize) { +unsafe fn maybe_enqueue_water_readback(this: *mut c_void, dst: usize, cur_state: D3D12_RESOURCE_STATES) { let Some(target) = super::cpu_writes::water_readback_target(dst) else { return }; if list_type(this) == D3D12_COMMAND_LIST_TYPE_BUNDLE { return; @@ -5324,12 +5390,17 @@ unsafe fn maybe_enqueue_water_readback(this: *mut c_void, dst: usize) { }, }, }; - transition(this, dst, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + let need_barrier = (cur_state.0 & D3D12_RESOURCE_STATE_COPY_SOURCE.0) == 0; + if need_barrier { + transition(this, dst, cur_state, D3D12_RESOURCE_STATE_COPY_SOURCE); + } pc::( this, PC_COPY_TEXTURE_REGION, )(this, &dst_loc, 0, 0, 0, &src_loc, std::ptr::null()); - transition(this, dst, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST); + if need_barrier { + transition(this, dst, D3D12_RESOURCE_STATE_COPY_SOURCE, cur_state); + } std::mem::forget((src_loc, dst_loc)); // borrowed resource pointers let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); @@ -5355,7 +5426,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi if !super::format_alias::try_copy_resource(this, dst, src) { pc::(this, PC_COPY_RESOURCE)(this, dst, src); } - maybe_enqueue_water_readback(this, dst); + maybe_enqueue_water_readback(this, dst, D3D12_RESOURCE_STATE_COPY_DEST); return; } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); @@ -8767,4 +8838,29 @@ mod tests { on_release(list as usize); } } + + #[test] + fn redundant_render_targets_dedup_invalidates_on_descriptor_mutation_or_reset() { + let list = 0x7E57_B1D1usize as *mut c_void; + let rtvs = [0x4000usize, 0x4020]; + let dsv = 0x5000usize; + unsafe { + assert!(!skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + note_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv); + // Identical bind with unchanged RTV/DSV descriptor generation is skipped. + assert!(skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + // Different DSV or count -> not skipped. + assert!(!skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, std::ptr::null())); + assert!(!skip_redundant_render_targets(list, 1, rtvs.as_ptr(), 0, &dsv)); + // Overwriting any RTV/DSV CPU slot bumps RT_DESC_GEN -> must rebind! + bump_rt_desc_gen(); + assert!(!skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + note_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv); + assert!(skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + // ClearState / PC Reset invalidate live render targets. + on_pc_reset(list); + assert!(!skip_redundant_render_targets(list, 2, rtvs.as_ptr(), 0, &dsv)); + on_release(list as usize); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 157a03895c..25260974fa 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2534,6 +2534,9 @@ fn note_mixed_copy() { unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) { let ty = pc_heap_type(ty); note_copy_call("CopyDescriptorsSimple", n, dst, src); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32 || ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { + super::list_x::bump_rt_desc_gen(); + } if copy_console_slots(this, n, dst, src, ty) { return; } @@ -2550,6 +2553,9 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32, ty: u32) { let ty = pc_heap_type(ty); note_copy_call("CopyDescriptors", nd, if dsts.is_null() { 0 } else { *dsts }, if srcs.is_null() { 0 } else { *srcs }); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_RTV.0 as u32 || ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 { + super::list_x::bump_rt_desc_gen(); + } use super::console_heap::{slot, SAMPLER_SLOT, SLOT}; let console = !dsts.is_null() && !srcs.is_null() && nd > 0 && slot(*dsts).is_some(); if !console { @@ -2703,6 +2709,7 @@ unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, } let dsv_flags = copy.as_ref().map_or(0, |c| c.Flags.0 as u32); f(this, res, copy.as_ref().map_or(desc, |c| c as *const _), cpu); + super::list_x::bump_rt_desc_gen(); super::depth_uav::note_dsv(cpu as usize, res as usize, dsv_flags); } @@ -8238,6 +8245,7 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de } let desc = copy.as_ref().map_or(desc, |c| c as *const _ as *const c_void); f(this, res, desc, handle); + super::list_x::bump_rt_desc_gen(); super::present::note_rtv(handle, res); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); @@ -8268,6 +8276,9 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt if !dsv.is_null() { super::depth_uav::before_bind_dsv(this, *dsv); } + if super::list_x::skip_redundant_render_targets(this, n, rtvs, single, dsv) { + return; + } type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "OMSetRenderTargets"))); f(this, n, rtvs, single, dsv); From aa5dbf76ddc7bda7bef02cad196b036d91dec736 Mon Sep 17 00:00:00 2001 From: grahamster2 <128315603+grahamster2@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:10:08 -0500 Subject: [PATCH 145/258] D3D12.X: a dispatch put off to the submit waits there until it is built With XCL_PSO_WAIT_MS set, a Dispatch or dispatching ExecuteIndirect put off to the submit (#2118) was recorded through resolve_wait, with the same budget a bind has as the title records. A pipeline a bind had already found late got the stand-in at once, one still building got it after the budget, and the dispatch was counted as skipped and left out. Its segment lies between the list's other work, so the list's Write64 labels, EOP writes and fence signals still fired: the title saw the work as done while its UAV outputs, counters and indirect argument buffers were never written. record_deferred now waits for the segment's compute pipeline (pso_async::wait_for_submit) before it records the call, whether a bind found it late or not. Without the budget this is the wait the submit already made. With it, the submit leaves the build to the workers for the budget first, as a bind does, so big compiles keep their turns on the workers; one no worker has started by then is built on the submitting thread, so a submit never waits for a free worker. One a worker builds is waited for at most 30 s (SUBMIT_WAIT_MOST, the time a retail title's watchdog lets its main thread stand still, #891): title_held stops kernelx::Sleep and the GPU-wait watchdog, not every clock a title reads. Past that the call goes on with the stand-in as before, with a WARN ("deferred dispatch skipped after waiting 30 s for its pipeline") and a count of its own. A worker's build that panics now ends as a failed build (catch_unwind around the job), so whoever waits for it goes on instead of waiting for a done flag nobody sets. Tests: a put-off dispatch of a translated console program whose build ends 400 ms into the submit, with a 50 ms budget and the pipeline already late, has its store and the Write64 after it in the list reach memory (without the change the label is written and the store is not); a submit's wait for a late pipeline no worker can start builds it itself; a submit waits for a worker's build no longer than its bound and counts it; a panicking build ends as failed. --- crates/xcl/src/hle/d3d12x/bind.rs | 15 ++ crates/xcl/src/hle/d3d12x/list_x.rs | 147 +++++++++++++++++- crates/xcl/src/hle/d3d12x/pso_async.rs | 200 ++++++++++++++++++++++++- 3 files changed, 359 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index dc537cb3fd..af35428d50 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -689,6 +689,12 @@ pub(super) fn want_bound(this: *mut c_void) { super::pso_async::want(with(this, |s| s.pso)); } +/// A submit records a put-off call of `this`: it waits until the pipeline `this` has bound is +/// built (`pso_async::wait_for_submit`). +pub(super) fn wait_for_bound(this: *mut c_void) { + super::pso_async::wait_for_submit(with(this, |s| s.pso)); +} + /// A put-off dispatch that could not be recorded. pub(super) fn dispatch_dropped() { count(DISPATCHES_SKIPPED); @@ -4100,6 +4106,15 @@ pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { DRAW_ARGS.with(|d| d.get()) } +/// `list`'s compute arguments without a title root signature: `args` is the whole argument table. +#[cfg(test)] +pub(super) fn set_args_for_test(list: *mut c_void, args: Vec) { + with(list, |s| { + s.layout = None; + s.args = args; + }); +} + #[cfg(test)] pub(super) fn counts_snapshot() -> [u64; 5] { std::array::from_fn(|k| COUNTS[k].load(Ordering::Relaxed)) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index b097a914c5..02ea23fdc2 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3120,7 +3120,8 @@ pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { /// Builds of a submit's put-off calls that go on without the commit headroom, as a title thread's own do: about what the title's threads had in the driver at once before. const WANTED_AT_ONCE: usize = 4; -/// Records the deferred dispatches of `wrapper`'s recording, waiting for their pipelines as a bind did. +/// Records the deferred dispatches of `wrapper`'s recording, each once its pipeline is built +/// (`pso_async::wait_for_submit`: not bounded by `XCL_PSO_WAIT_MS`). pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { let mut segs = Vec::new(); super::title_list::raw_segments(wrapper, &mut segs); @@ -3164,6 +3165,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { super::bind::pass_arena(last, seg); real::dispatch_chain::list_follows(last as usize, seg as usize); } + super::bind::wait_for_bound(seg); match what { Deferred::Dispatch(x, y, z) => super::bind::dispatch(seg, x, y, z), Deferred::Indirect(sig, max, args, args_off, count_buf, count_off) => super::bind::execute_indirect(seg, sig, max, args, args_off, count_buf, count_off), @@ -8134,6 +8136,149 @@ mod tests { } } + /// With `XCL_PSO_WAIT_MS`, a dispatch put off to the submit whose pipeline is built after the + /// budget (and that a bind already found `late`) is recorded with the built pipeline: its + /// output is written, as is the `Write64` after it in the list. Before, the submit's bind gave + /// up after the budget and left the dispatch out while the label still fired. + #[test] + fn a_put_off_dispatch_runs_at_the_submit_when_its_build_outlasts_the_wait_budget() { + use super::super::{bind, pso_async, title_list}; + use crate::gpu::recomp::runner; + use crate::gpu::xbox::tests::{fssm, sample}; + use std::time::{Duration, Instant}; + + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + if super::super::backend() != super::super::Backend::Real { + return runner::skip_test("no GPU"); + } + if runner::wave64_programs_supported() != Ok(true) { + return runner::skip_test("no wave64"); + } + if real::uma_window_vas().is_empty() { + return runner::skip_test("no unified memory on the GPU"); + } + const MARK: u32 = 0x600D_F00D; + const LABEL: u64 = 0x1AB_E15E_7000_0001; + unsafe { + let raw = real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw).unwrap().clone(); + // s[0:1]: the argument table; its first 8 bytes say where the program stores MARK + let code: Vec = [ + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 4), ("SBASE", 0), ("OFFSET", 0), ("SOFFSET", 0x7D)][..], None), + ("S_WAITCNT", "ENC_SOPP", &[("SIMM16", 0)][..], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 4)][..], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 5)][..], None), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 255)][..], Some(MARK)), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 2), ("DATA", 1), ("SADDR", 0x7D)][..], None), + ("S_ENDPGM", "ENC_SOPP", &[][..], None), + ] + .iter() + .flat_map(|(n, e, f, l)| crate::gpu::rdna2::encode(n, e, f, *l).unwrap_or_else(|x| panic!("{n}: {x}"))) + .collect(); + let mut f = fssm(&code, &[(6, 1)]); + // COMPUTE_PGM_RSRC2 (2 user SGPRs) and numthreads + for (k, x) in [2u32 << 1, 64, 1, 1].into_iter().enumerate() { + f[0x138 + 4 * k..0x13C + 4 * k].copy_from_slice(&x.to_le_bytes()); + } + let blob = sample(5, &[f]); + let game_rs: ID3D12RootSignature = { + let mut ser = None; + D3D12SerializeRootSignature(&D3D12_ROOT_SIGNATURE_DESC::default(), D3D_ROOT_SIGNATURE_VERSION_1, &mut ser, None).unwrap(); + let ser = ser.unwrap(); + dev.CreateRootSignature(0, std::slice::from_raw_parts(ser.GetBufferPointer() as *const u8, ser.GetBufferSize())).unwrap() + }; + let mut desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(game_rs)), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: blob.as_ptr() as _, BytecodeLength: blob.len() }, + ..Default::default() + }; + let made: windows::core::Result = dev.CreateComputePipelineState(&desc); + std::mem::ManuallyDrop::drop(&mut desc.pRootSignature); + let made = made.expect("CreateComputePipelineState through the backend hook"); + let built = pso_async::resolve_wait(made.as_raw() as usize); + assert!(real::is_translated_compute(built), "not translated: {:?}", real::stats().translation_errors); + + // the title's pipeline: a stand-in whose build ends once the submit has begun + let standin = 0x7E57_D0F1usize; + static BUILD: AtomicBool = AtomicBool::new(false); + BUILD.store(false, Ordering::Release); + pso_async::submit( + standin, + true, + Box::new(move || { + let t = Instant::now(); + while !BUILD.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + ID3D12PipelineState::from_raw_borrowed(&(built as *mut c_void)).unwrap().clone().into_raw() as usize + }), + ); + pso_async::set_wait_budget_for_test(Some(Duration::from_millis(50))); + assert_eq!(pso_async::resolve_wait(standin), standin, "a bind as the title records: past the budget, late"); + + let u = crate::gpu::uma::get().unwrap(); + let out = u.alloc(256, 256).unwrap(); + std::ptr::write_bytes(out, 0, 256); + let label = out.add(64) as *mut u64; + + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let a = alloc.as_raw() as usize; + let pc0 = real::create_raw_pc_command_list(raw, ty, a, 0).expect("a PC command list"); + on_create(pc0, a, 0, ty); + bind::reset(pc0, a, standin); + let wrap = title_list::wrap(pc0); + bind::set_args_for_test(pc0, (out as u64).to_le_bytes().to_vec()); + + bind::dispatch(pc0, 1, 1, 1); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 3, "the dispatch was not put off"); + write64_bottom_x(*segs.last().unwrap(), label as u64, LABEL, 0, 0); + let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); + assert_eq!(close_fn(wrap), 0); + + let build = std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(400)); + BUILD.store(true, Ordering::Release); + }); + let t = Instant::now(); + record_deferred(wrap); + let took = t.elapsed(); + pso_async::set_wait_budget_for_test(None); + build.join().unwrap(); + + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + segs.clear(); + assert!(title_list::push_segments(wrap, &mut segs)); + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let q = queue.as_raw(); + let exec: ExecFn = if real::is_adopted(q) { + std::mem::transmute(real::orig_fn(q, PC_QUEUE_EXECUTE_COMMAND_LISTS)) + } else { + std::mem::transmute(*(*(q as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)) + }; + exec(q, segs.len() as u32, segs.as_ptr()); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 5000).expect("the list runs"); + let (mark, labelled) = (std::ptr::read_volatile(out as *const u32), std::ptr::read_volatile(label)); + let removed = dev.GetDeviceRemovedReason(); + + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + rel_fn(wrap); + pso_async::release(pso_async::released(standin)); + drop(made); + + assert!(removed.is_ok()); + assert_eq!(labelled, LABEL, "the Write64 after the dispatch"); + assert_eq!(mark, MARK, "the put-off dispatch was left out (the submit waited {took:?})"); + assert!(took >= Duration::from_millis(300), "the submit did not wait for the build ({took:?})"); + } + } + /// Reproduces the exact intra-list fork-join pattern seen on retail compute queues: /// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame) /// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index f564adf5fd..ce8250be4a 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -84,7 +84,8 @@ fn build(p: &Arc, job: Job, preload: bool) { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } - complete(p, job()); + // (a panic in a build ends it as a failed one: whoever waits for it is not left waiting) + complete(p, std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)).unwrap_or(0)); if preload { // (under the lock: `want` does not raise this thread after it) let mut d = p.demand.lock().unwrap(); @@ -1119,6 +1120,112 @@ mod used_tests { calls.end(5, 9, t_stale); } + /// With `XCL_PSO_WAIT_MS`, a submit's wait for a late pipeline that no worker can start (all + /// are busy) neither ends with the stand-in nor waits for a free worker: after the budget it + /// builds the pipeline itself. + #[test] + fn a_submit_builds_a_late_pipeline_no_worker_has_started() { + let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use std::time::{Duration, Instant}; + let n = crate::gpu::recomp::dxc::compile_threads(); + let (started_tx, started_rx) = mpsc::channel(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let mut blockers = Vec::with_capacity(n); + for k in 0..n { + let standin = 0x7E57_A500usize + k; + let (tx, g) = (started_tx.clone(), gate.clone()); + submit(standin, false, Box::new(move || { + let _ = tx.send(()); + let mut open = g.0.lock().unwrap(); + while !*open { + open = g.1.wait(open).unwrap(); + } + 0xA500 + k + })); + blockers.push(standin); + } + for _ in 0..n { + started_rx.recv_timeout(Duration::from_secs(10)).expect("workers saturated"); + } + let target = 0x7E57_A5FFusize; + submit(target, true, Box::new(|| 0xA5FF)); + set_wait_budget_for_test(Some(Duration::from_millis(30))); + assert_eq!(resolve_wait(target), target, "a bind as the title records: past the budget, late"); + let t = Instant::now(); + wait_for_submit(target); + let took = t.elapsed(); + set_wait_budget_for_test(None); + let built = resolve(target); + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + for standin in blockers { + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + let _ = released(standin); + } + let _ = released(target); + assert_eq!(built, 0xA5FF, "the submit's wait ended without the pipeline"); + assert!(took < Duration::from_secs(5), "the submit waited for a free worker ({took:?})"); + } + + /// With `XCL_PSO_WAIT_MS`, a submit waits for a pipeline a worker is building at most + /// `SUBMIT_WAIT_MOST`, then goes on (with the stand-in) and counts it. + #[test] + fn a_submit_waits_for_a_build_on_a_worker_no_longer_than_its_bound() { + let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use std::time::{Duration, Instant}; + let standin = 0x7E57_A600usize; + let (started_tx, started_rx) = mpsc::channel(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let g = gate.clone(); + submit(standin, true, Box::new(move || { + let _ = started_tx.send(()); + let mut open = g.0.lock().unwrap(); + while !*open { + open = g.1.wait(open).unwrap(); + } + 0xA600 + })); + started_rx.recv_timeout(Duration::from_secs(10)).expect("a worker builds it"); + set_wait_budget_for_test(Some(Duration::from_millis(20))); + set_submit_wait_for_test(Some(Duration::from_millis(300))); + let gave_up = SUBMIT_GAVE_UP.load(Ordering::Relaxed); + let t = Instant::now(); + wait_for_submit(standin); + let took = t.elapsed(); + let pending = is_pending(standin); + let counted = SUBMIT_GAVE_UP.load(Ordering::Relaxed) > gave_up; + set_wait_budget_for_test(None); + set_submit_wait_for_test(None); + *gate.0.lock().unwrap() = true; + gate.1.notify_all(); + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + let _ = released(standin); + assert!(pending, "the build ended before the bound"); + assert!(took >= Duration::from_millis(300) && took < Duration::from_secs(5), "the submit waited {took:?}"); + assert!(counted, "the submit that went on without its pipeline was not counted"); + } + + /// A build that panics on a worker ends as a failed one: binds and submits waiting for it go on. + #[test] + fn a_build_that_panics_on_a_worker_ends_as_failed() { + use std::time::{Duration, Instant}; + let standin = 0x7E57_A700usize; + submit(standin, true, Box::new(|| panic!("a build that panics (test)"))); + let start = Instant::now(); + while is_pending(standin) && start.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(2)); + } + let pending = is_pending(standin); + let _ = released(standin); + assert!(!pending, "the panicked build never ended"); + } + #[test] fn released_queued_pipeline_drops_job_immediately_before_workers_drain() { let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); @@ -1305,6 +1412,78 @@ pub fn resolve_wait(pso: usize) -> usize { resolve_wait_for(pso, wait_budget()) } +/// A call put off to the submit is recorded now: wait for its compute pipeline to be built, +/// whether a bind already found it `late` or not. Its segment lies between the list's other work, +/// whose labels and fence signals the title reads as "done": recorded with the stand-in, the +/// dispatch is left out while they still fire. The submitting thread is held for that time +/// (`title_held`), as a bind's wait holds it. A build that fails still gives the stand-in, and a +/// program binds do not wait for (`image_only`) is not waited for. +/// +/// Unset `XCL_PSO_WAIT_MS`: until the pipeline is built, as a bind waits. Set: the build is left +/// to the workers for that long first, as a bind leaves it (their turns for big compiles); one no +/// worker has started by then is built here. One a worker builds is waited for at most +/// `SUBMIT_WAIT_MOST`, and the call then goes on with the stand-in (logged and counted): +/// `title_held` stops only `kernelx::Sleep` and the GPU-wait watchdog, not every clock a title +/// reads. +pub fn wait_for_submit(pso: usize) { + let Some(budget) = wait_budget() else { + let _ = resolve_wait_for(pso, None); + return; + }; + let Some(p) = entry(pso) else { return }; + if !p.compute || p.spared.load(Ordering::Acquire) || *p.done.lock().unwrap() { + return; + } + p.note_use(); + let _held = Held::new(); + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); + } + p.want(); + let built = |p: &Pending, most: std::time::Duration| *p.cv.wait_timeout_while(p.done.lock().unwrap(), most, |d| !*d).unwrap().0; + if built(&p, budget) { + return; + } + // no worker has started it: built here, as without the budget + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + return complete(&p, job()); + } + let most = submit_wait_most(); + if !built(&p, most) { + let n = SUBMIT_GAVE_UP.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 16 || n.is_power_of_two() { + crate::xlog_warn!("D3D12.X: deferred dispatch skipped after waiting {} s for its pipeline ({n} so far)", most.as_secs_f32()); + } + } +} + +/// put-off calls that went on with the stand-in after `SUBMIT_WAIT_MOST` +static SUBMIT_GAVE_UP: AtomicUsize = AtomicUsize::new(0); + +/// How long a submit waits for a pipeline a worker builds, with `XCL_PSO_WAIT_MS` set: as long as +/// a retail title's watchdog lets its main thread stand still (30 s, #891). +const SUBMIT_WAIT_MOST: std::time::Duration = std::time::Duration::from_secs(30); + +fn submit_wait_most() -> std::time::Duration { + #[cfg(test)] + if let Some(b) = SUBMIT_WAIT_FOR_TEST.with(|b| b.get()) { + return b; + } + SUBMIT_WAIT_MOST +} + +#[cfg(test)] +thread_local! { + /// `SUBMIT_WAIT_MOST` for the submits of this test thread + static SUBMIT_WAIT_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(test)] +fn set_submit_wait_for_test(most: Option) { + SUBMIT_WAIT_FOR_TEST.with(|b| b.set(most)); +} + /// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). fn resolve_wait_for(pso: usize, budget: Option) -> usize { let Some(p) = entry(pso) else { return pso }; @@ -1345,12 +1524,29 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { /// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until /// it is built). A retail game builds compute programs on its own threads: the driver takes up to /// 30 s for the biggest translated ones, and the title's watchdog ends it when its main thread -/// has been held 30 s. +/// has been held 30 s. It bounds binds as the title records; a call put off to the submit waits +/// there until its pipeline is built (`wait_for_submit`). fn wait_budget() -> Option { + #[cfg(test)] + if let Some(b) = BUDGET_FOR_TEST.with(|b| b.get()) { + return Some(b); + } static B: OnceLock> = OnceLock::new(); *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis)) } +#[cfg(test)] +thread_local! { + /// `XCL_PSO_WAIT_MS` for the binds of this test thread + static BUDGET_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Binds on this thread wait at most `budget` (None: as `XCL_PSO_WAIT_MS` says). +#[cfg(test)] +pub(super) fn set_wait_budget_for_test(budget: Option) { + BUDGET_FOR_TEST.with(|b| b.set(budget)); +} + /// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a /// pipeline not built by then is `late` – it and later binds of it get the stand-in (their /// dispatches are skipped) until a worker has built it. From 04e0b956104e1d9b9c3443dfb4dee72df1a2f55d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:49:41 +0100 Subject: [PATCH 146/258] KernelX / D3D12.X: fix VirtualFree AWAY/home-reuse bugs and post-upload VRAM fence wait Two memory/GPU ordering fixes: 1. kernelx.rs: Clean up AWAY/title/lazy entries before sparse and plain MEM_DECOMMIT/MEM_RELEASE VirtualFree (preventing dangling AWAY mappings and stale physical_page_at results on address reuse), handle self-home mapping (at == home) without overlapping copy_nonoverlapping UB or spurious give_back_homes decommit, and remove reused home addresses from away.gone during scatter remaps. 2. title_textures.rs: Re-run vram::before_execute(queue) after upload_all(todo) when textures were uploaded so the submitting queue is always GPU-fence-ordered behind any vram::map_levels tile mappings issued inside upload_all, even if an upload batch fails or exits early before fence::wait. (Audit confirms texture::upload_batch already CPU-waits on its upload fence before q_execute_command_lists submits title work.) Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/title_textures.rs | 8 + crates/xcl/src/hle/kernelx.rs | 176 +++++++++++++++++++- 2 files changed, 183 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6b2b0e477c..d12271daa9 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -998,7 +998,15 @@ unsafe fn refresh_once(queue: *mut c_void) { .collect() }); seed_stream_recheck(&todo, &ranges, recheck_frame); + let uploaded = !todo.is_empty(); upload_all(todo); + // Ensure the submitting queue waits for any `vram::map_levels` tile mappings queued inside + // `upload_all`, even if an upload batch failed or exited early before its upload-queue wait. + if uploaded { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { + super::vram::before_execute(q); + } + } } struct PageHashes { diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 5f9dfd1e5d..4b2514f6ce 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -655,6 +655,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 } }; if n > 0 { + unmap_away_range(a, n); // sparse first: under its lock, so no copy of CPU writes to video memory reads the // pages while they go (the submit thread's copy faulted on them) crate::hle::d3d12x::sparse::decommitted(a, n); @@ -684,6 +685,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 size }; let notify = gone > 0 && (overlaps_graphics_reservation(addr as usize, gone) || !mirrors::gpu_views_of(addr as usize).is_empty()); + unmap_away_for_plain_free(addr as usize, size, t); let ok = mem::VirtualFree(addr, size, t); if ok != 0 && notify { crate::hle::d3d12x::vram::title_memory_changed(addr as usize, gone); @@ -1486,6 +1488,87 @@ unsafe fn release_at(at: usize) { mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT); } +/// Unmap every away-mapped physical page overlapping `[start, start + len)` (clearing `title` +/// and `lazy` records so freed/decommitted pages never leave dangling `AWAY` entries). +unsafe fn unmap_away_in(away: &mut Away, start: usize, len: usize) { + if len == 0 || away.at.is_empty() { + return; + } + let lo = start & !(PHYS_PAGE - 1); + let hi = start.saturating_add(len); + let addrs: Vec = away.at.range(lo..hi).map(|(&at, _)| at).collect(); + for at in addrs { + away.title.remove(&at); + unmap_away(away, at, &(0..0)); + note_mapping_at(at); + } +} + +unsafe fn unmap_away_range(start: usize, len: usize) { + if len > 0 { + if let Some(away) = AWAY.lock().unwrap().as_mut() { + unmap_away_in(away, start, len); + } + } +} + +/// Validate a plain `MEM_PRIVATE` `VirtualFree` call and return the byte range it will free/decommit. +unsafe fn plain_free_range(addr: usize, size: usize, t: u32) -> Option<(usize, usize)> { + let mut m: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if mem::VirtualQuery(addr as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 + || m.State == mem::MEM_FREE + || m.Type != mem::MEM_PRIVATE + || m.RegionSize == 0 + { + return None; + } + let alloc_base = m.AllocationBase as usize; + let query_same = |at: usize| -> Option { + let mut next: mem::MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + (mem::VirtualQuery(at as *const c_void, &mut next, std::mem::size_of_val(&next)) != 0 + && next.State != mem::MEM_FREE + && next.Type == mem::MEM_PRIVATE + && next.AllocationBase as usize == alloc_base + && next.RegionSize > 0) + .then_some(next.RegionSize) + }; + if t == mem::MEM_RELEASE || size == 0 { + if addr != alloc_base { + return None; + } + let mut end = (m.BaseAddress as usize).checked_add(m.RegionSize)?; + while let Some(step) = query_same(end) { + end = end.checked_add(step)?; + } + return Some((alloc_base, end - alloc_base)); + } + let (start, req_end) = (m.BaseAddress as usize, addr.checked_add(size)?); + let mut end = start.checked_add(m.RegionSize)?; + while end < req_end { + end = end.checked_add(query_same(end)?)?; + } + Some((start, req_end - start)) +} + +unsafe fn unmap_away_for_plain_free(addr: usize, size: usize, t: u32) { + if addr == 0 || !((t == mem::MEM_RELEASE && size == 0) || t == mem::MEM_DECOMMIT) { + return; + } + let mut g = AWAY.lock().unwrap(); + let Some(away) = g.as_mut().filter(|a| !a.at.is_empty()) else { return }; + let lo = addr & !(PHYS_PAGE - 1); + let has_cand = if t == mem::MEM_RELEASE || size == 0 { + away.at.range(lo..).next().is_some() + } else { + addr.checked_add(size).is_some_and(|hi| away.at.range(lo..hi).next().is_some()) + }; + if has_cand { + if let Some((start, len)) = plain_free_range(addr, size, t) { + unmap_away_in(away, start, len); + } + } +} + /// Coalesces contiguous 64 KiB sparse-window commits inside `map_pages` / scatter calls so a /// multi-gigabyte `XMemMapPhysicalPages` issues one `sparse::committed(start, len)` per run /// instead of one `UpdateTileMappings` + `Signal` per page. @@ -1800,11 +1883,30 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize, if p == 0 { continue; } + let Some(home) = page_home(p) else { + fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER); + return std::ptr::null_mut(); + }; + if at == home { + if !commit_homes(home, 1) { + fnd::SetLastError(fnd::ERROR_NOT_ENOUGH_MEMORY); + return std::ptr::null_mut(); + } + away.gone.retain(|&h| h != home); + if let Some(&old) = away.page.get(&p) { + sparse_batch.flush_if_contains(old); + unmap_away(away, old, &(home..home + PHYS_PAGE)); + } + away.title.insert(home, p); + (at_run, home_run) = Default::default(); + continue; + } if let Some(&old) = away.page.get(&p) { // (a move commits `at` and decommits `old`, which may lie in a run already answered: // both runs go – #556) match move_away_batched(away, old, at, p, in_uma(at), Some(sparse_batch)) { Ok(true) => { + away.gone.retain(|&h| h != at); (at_run, home_run) = Default::default(); away.title.insert(at, p); continue; @@ -1818,11 +1920,11 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize, } } let fresh = !in_uma(at) && !committed_page_in(at, &mut at_run); - let home = page_home(p).unwrap(); // a page never used (its home not committed) at the title's own reserved address space: // committed on first use (`lazy`) – GPU-owned targets placed there are never touched let plain = crate::gpu::uma::get().is_none_or(|u| !u.contains(at)); if fresh && plain && !committed_page_in(home, &mut home_run) { + away.gone.retain(|&h| h != at); lazy::mark(at); away.at.insert(at, p); away.page.insert(p, at); @@ -1833,6 +1935,7 @@ unsafe fn map_pages(away: &mut Away, va: *mut c_void, n: usize, arr: *mut usize, fnd::SetLastError(fnd::ERROR_INVALID_ADDRESS); return std::ptr::null_mut(); } + away.gone.retain(|&h| h != at); if committed_page(home) { std::ptr::copy_nonoverlapping(home as *const u8, at as *mut u8, PHYS_PAGE); if move_home_away(away, home) { @@ -3870,4 +3973,75 @@ mod tests { assert!(u.free(home)); } } + + #[test] + fn map_pages_preserves_self_home_and_reused_home_in_scatter() { + unsafe { + let _ = crate::gpu::uma::get().expect("UMA must initialize"); + let (mut n, mut pages) = (3usize, [0usize; 3]); + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let [p0, p1, p2] = pages; + let h0 = MapTitlePhysicalPages(std::ptr::null_mut(), 3, 0, 4, pages.as_mut_ptr()) as usize; + assert_ne!(h0, 0); + *(h0 as *mut u32) = 0x1111_0001; + *((h0 + PHYS_PAGE) as *mut u32) = 0x2222_0002; + *((h0 + 2 * PHYS_PAGE) as *mut u32) = 0x3333_0003; + + let dst = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(dst, 0); + let (dst0, dst1) = (dst, dst + PHYS_PAGE); + // Step 0 moves p0 off h0 (away.gone); step 1 maps p1 from its home onto h0. + let addrs = [dst0 as *mut c_void, h0 as *mut c_void]; + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), 2, [p0 as u64, p1 as u64].as_mut_ptr()), 1); + assert!(committed_page(h0), "reused home (from home) must stay committed"); + assert_eq!((*(dst0 as *const u32), *(h0 as *const u32)), (0x1111_0001, 0x2222_0002)); + // Same scatter with p2 arriving via move_away from dst1 onto h0. + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), 3, 0, 4, pages.as_mut_ptr()) as usize, h0); + assert_eq!(MapTitlePhysicalPages(dst1 as *mut c_void, 1, 0, 4, [p2].as_mut_ptr()) as usize, dst1); + *(dst1 as *mut u32) = 0x4444_0004; + assert_eq!(XMemMapPhysicalPagesScatter(addrs.as_ptr(), 2, [p0 as u64, p2 as u64].as_mut_ptr()), 1); + assert!(committed_page(h0) && !committed_page(dst1), "reused home (via move_away) must stay committed"); + assert_eq!((*(dst0 as *const u32), *(h0 as *const u32)), (0x1111_0001, 0x4444_0004)); + + assert_eq!(MapTitlePhysicalPages(std::ptr::null_mut(), 3, 0, 4, pages.as_mut_ptr()) as usize, h0); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()), 1); + assert_eq!(mem::VirtualFree(dst as *mut c_void, 0, mem::MEM_RELEASE), 1); + } + } + + #[test] + fn virtual_free_unmaps_away_pages_in_plain_and_sparse_reservations() { + unsafe { + let u = crate::gpu::uma::get().expect("UMA must initialize"); + let (mut n, mut pages) = (3usize, [0usize; 3]); + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let [p0, p1, p2] = pages; + let r = mem::VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE, mem::PAGE_READWRITE) as usize; + assert_ne!(r, 0); + assert_eq!(MapTitlePhysicalPages(r as *mut c_void, 2, 0, 4, [p0, p1].as_mut_ptr()) as usize, r); + *(r as *mut u32) = 0x5555_0001; + // Invalid VirtualFree calls must fail without touching AWAY. + assert_eq!(VirtualFree(r as *mut c_void, PHYS_PAGE, mem::MEM_RELEASE), 0); + assert_eq!(VirtualFree((r + PHYS_PAGE) as *mut c_void, 0, mem::MEM_RELEASE), 0); + assert_eq!(VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE | mem::MEM_DECOMMIT), 0); + assert_eq!(VirtualFree(r as *mut c_void, 3 * PHYS_PAGE, mem::MEM_DECOMMIT), 0); + assert!(physical_page_at(r) && physical_page_at(r + PHYS_PAGE) && *(r as *const u32) == 0x5555_0001); + // Partial MEM_DECOMMIT unmaps p0 (saving bytes home); MEM_RELEASE clears lazy p1. + assert_eq!(VirtualFree(r as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT), 1); + assert!(!physical_page_at(r) && physical_page_at(r + PHYS_PAGE)); + assert_eq!(VirtualFree(r as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!(!physical_page_at(r + PHYS_PAGE) && !lazy::unmark(r + PHYS_PAGE)); + // Sparse UMA reservation: partial MEM_DECOMMIT + full MEM_RELEASE across committed p0 & lazy p2. + let sp = VirtualAlloc(std::ptr::null(), 2 * PHYS_PAGE, mem::MEM_RESERVE | MEM_GRAPHICS, mem::PAGE_READWRITE) as usize; + assert!(sp != 0 && u.is_sparse(sp)); + assert_eq!(MapTitlePhysicalPages(sp as *mut c_void, 2, 0, 4, [p0, p2].as_mut_ptr()) as usize, sp); + assert_eq!(*(sp as *const u32), 0x5555_0001); + *(sp as *mut u32) = 0x6666_0001; + assert_eq!(VirtualFree(sp as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT), 1); + assert!(!physical_page_at(sp) && physical_page_at(sp + PHYS_PAGE)); + assert_eq!(VirtualFree(sp as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!(!physical_page_at(sp + PHYS_PAGE) && !lazy::unmark(sp + PHYS_PAGE)); + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()), 1); + } + } } From ecf25c0464f033a4279afef0582432aa8851e137 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:59:29 +0100 Subject: [PATCH 147/258] D3D12.X: use RwLock for recording-thread PSO/layout/texture lookups Convert read-heavy command-list recording lookup tables from Mutex to std::sync::RwLock so concurrent recording threads do not serialize on SetPipelineState, dispatch user-SGPR/thread-group lookups, root-layout lookups, DRED label lookups, or placed-texture checks: - console_list.rs: LAYOUTS - dred.rs: LABELS, plus reuse a static UTF-16 marker buffer and fold the double MARKS lock in mark_pipeline into a single acquisition - real.rs: TRANSLATED_COMPUTE, PSO_COMPUTE_THREADS, BVH_TRAVERSAL_PSOS, PSO_USER_SGPRS - vram.rs: PLACED_TEXTURES Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/console_list.rs | 6 ++-- crates/xcl/src/hle/d3d12x/dred.rs | 40 ++++++++++++++++++----- crates/xcl/src/hle/d3d12x/real.rs | 40 +++++++++++------------ crates/xcl/src/hle/d3d12x/vram.rs | 12 +++---- 4 files changed, 60 insertions(+), 38 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index b8f7efaa91..bc50666e32 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -224,17 +224,17 @@ fn sgprs(first: usize, inline: u32, args: &[u8], table_at: u64) -> Vec { s } -static LAYOUTS: Mutex>>> = Mutex::new(None); +static LAYOUTS: std::sync::RwLock>>> = std::sync::RwLock::new(None); /// A root signature was created from `blob`: remember its argument layout. pub fn note_root_signature(rs: usize, blob: &[u8]) { if let Some(l) = layout_from_blob(blob) { - LAYOUTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(rs, Arc::new(l)); + LAYOUTS.write().unwrap().get_or_insert_with(HashMap::new).insert(rs, Arc::new(l)); } } pub(super) fn layout_of(rs: usize) -> Option> { - LAYOUTS.lock().unwrap().as_ref()?.get(&rs).cloned() + LAYOUTS.read().unwrap().as_ref()?.get(&rs).cloned() } /// Both are the layout of the same root signature object (not merely of one at the same diff --git a/crates/xcl/src/hle/d3d12x/dred.rs b/crates/xcl/src/hle/d3d12x/dred.rs index 84150a4e81..404eb53939 100644 --- a/crates/xcl/src/hle/d3d12x/dred.rs +++ b/crates/xcl/src/hle/d3d12x/dred.rs @@ -18,11 +18,19 @@ use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::{ID3D12GraphicsCommandList, D3D12_AUTO_BREADCRUMB_OP_SETMARKER}; /// translated pipeline → its label -static LABELS: Mutex>> = Mutex::new(None); +static LABELS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// PC command list → its last `RECORDINGS` recordings, oldest first: the label of each marker /// (`None`: the title's own) static MARKS: Mutex>>>>> = Mutex::new(None); +/// Null-terminated UTF-16 marker text (`"xcl pipeline\0"`) reused across `mark_pipeline` calls +/// without per-PSO heap allocations. +const PIPELINE_MARKER_W: &[u16] = &[ + b'x' as u16, b'c' as u16, b'l' as u16, b' ' as u16, + b'p' as u16, b'i' as u16, b'p' as u16, b'e' as u16, + b'l' as u16, b'i' as u16, b'n' as u16, b'e' as u16, 0, +]; + /// Recordings kept per list: a list can be Reset and recorded again while an earlier /// submission of it still runs, and that one can be the one that faults. const RECORDINGS: usize = 4; @@ -43,18 +51,18 @@ pub fn label(pso: usize, shaders: &[(&str, Option<&[u8]>)]) { return; } let text = shaders.iter().filter_map(|(k, b)| b.map(|b| format!("{k} {:016x}", crate::gpu::shader::fnv64(b)))).collect::>().join(" "); - LABELS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, text); + LABELS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, text); } /// `label` with a text of XCL's own: a piece of a split program, a pass of two. pub fn label_text(pso: usize, text: impl FnOnce() -> String) { if on() && pso != 0 { - LABELS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, text()); + LABELS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, text()); } } fn label_of(pso: usize) -> Option { - LABELS.lock().unwrap().as_ref()?.get(&pso).cloned() + LABELS.read().unwrap().as_ref()?.get(&pso).cloned() } /// After `SetPipelineState(pso)` on `list`: a marker, and the label of what is bound now. @@ -65,16 +73,24 @@ pub unsafe fn mark_pipeline(list: *mut c_void, pso: usize, bound: usize) { } // nothing labelled: a stand-in still building, or a pipeline of PC shaders let text = label_of(bound).unwrap_or_else(|| format!("pipeline {pso:#x} (a stand-in, or not translated)")); - let first = !MARKS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).and_then(|r| r.last()).is_some_and(|v| v.iter().any(Option::is_some)); - push(list as usize, Some(text)); + let first = { + let mut g = MARKS.lock().unwrap(); + let recordings = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); + if recordings.is_empty() { + recordings.push(Vec::new()); + } + let cur = recordings.last_mut().unwrap(); + let first = !cur.iter().any(Option::is_some); + cur.push(Some(text)); + first + }; if let Some(l) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) { // DRED's node may give the list's name and not its pointer (NVIDIA, Windows 26300) if first { let _ = l.SetName(&windows::core::HSTRING::from(format!("xcl list {:#x}", list as usize))); } - let w: Vec = "xcl pipeline".encode_utf16().chain([0]).collect(); OWN_MARKER.with(|f| f.set(true)); - l.SetMarker(0, Some(w.as_ptr() as *const c_void), (w.len() * 2) as u32); + l.SetMarker(0, Some(PIPELINE_MARKER_W.as_ptr() as *const c_void), std::mem::size_of_val(PIPELINE_MARKER_W) as u32); OWN_MARKER.with(|f| f.set(false)); } } @@ -119,7 +135,7 @@ pub fn forget_list(list: *mut c_void) { /// A pipeline was released: its address may be another pipeline's next. pub fn forget_pso(pso: usize) { if on() { - if let Some(m) = LABELS.lock().unwrap().as_mut() { + if let Some(m) = LABELS.write().unwrap().as_mut() { m.remove(&pso); } } @@ -217,4 +233,10 @@ mod tests { assert_eq!(bound_after(list, &h, 6), Vec::::new()); MARKS.lock().unwrap().as_mut().unwrap().remove(&list); } + + #[test] + fn pipeline_marker_constant_matches_nul_terminated_utf16() { + let expected: Vec = "xcl pipeline\0".encode_utf16().collect(); + assert_eq!(PIPELINE_MARKER_W, expected.as_slice()); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 25260974fa..594a1a8cdc 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2107,7 +2107,7 @@ unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 { /// A pipeline state is gone: drop what XCL keeps by its address (a later pipeline may get the /// same address and must not inherit its root signature or compute pass). /// compute pipelines that run a translated console shader -static TRANSLATED_COMPUTE: Mutex>> = Mutex::new(None); +static TRANSLATED_COMPUTE: std::sync::RwLock>> = std::sync::RwLock::new(None); /// graphics pipelines built from translated console shaders static TRANSLATED_GRAPHICS: std::sync::RwLock>> = std::sync::RwLock::new(None); @@ -2151,9 +2151,9 @@ fn note_rect_list_gs(pso: usize, copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect /// Thread-group dimensions `[x, y, z]` of console compute PSOs (stand-in and real) for /// `DispatchX` with `USE_THREAD_DIMENSIONS` (`0x20`). -static PSO_COMPUTE_THREADS: Mutex>> = Mutex::new(None); +static PSO_COMPUTE_THREADS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// Compute PSOs (stand-in and real) that issue `image_bvh*_intersect_ray`. -static BVH_TRAVERSAL_PSOS: Mutex>> = Mutex::new(None); +static BVH_TRAVERSAL_PSOS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// At least one `DispatchX(..., 0x20)` BVH builder pass succeeded with no failed builder PSOs. static BVH_BUILD_READY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// At least one `DispatchX(..., 0x20)` BVH builder PSO failed or stayed pending: gate stays closed. @@ -2224,13 +2224,13 @@ pub(super) fn pso_compute_threads(pso: usize) -> Option<[u32; 3]> { if pso == 0 { return None; } - PSO_COMPUTE_THREADS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_COMPUTE_THREADS.read().unwrap().as_ref()?.get(&pso).copied() } fn note_compute_threads(pso: usize, cs: &[u8]) { if pso != 0 { if let Some(t) = crate::gpu::recomp::pso::compute_threads(cs) { - PSO_COMPUTE_THREADS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, t); + PSO_COMPUTE_THREADS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, t); } } } @@ -2284,17 +2284,17 @@ pub(crate) fn rt_gated_compute_held(cs: &[u8]) -> bool { fn note_bvh_traversal(pso: usize, cs: &[u8]) { if pso != 0 && is_rt_gated_cs(cs) { - BVH_TRAVERSAL_PSOS.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + BVH_TRAVERSAL_PSOS.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } fn is_bvh_traversal_pso(pso: usize) -> bool { - pso != 0 && BVH_TRAVERSAL_PSOS.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && BVH_TRAVERSAL_PSOS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } /// Raw check without BVH traversal hold-back (used by `DispatchX` builder passes). pub(super) fn is_translated_compute_raw(pso: usize) -> bool { - pso != 0 && TRANSLATED_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) + pso != 0 && TRANSLATED_COMPUTE.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } /// Whether `pso` runs a translated console compute shader (holding back BVH traversal shaders @@ -2339,7 +2339,7 @@ pub(super) fn register_console_compute_for_test(pso: usize) { #[cfg(test)] pub(super) fn register_translated_compute_for_test(pso: usize) { if pso != 0 { - TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(pso); + TRANSLATED_COMPUTE.write().unwrap().get_or_insert_with(HashSet::new).insert(pso); } } @@ -2365,7 +2365,7 @@ pub(super) fn forget_pso_for_test(pso: usize) { fn forget_pso(pso: usize) { dispatch_chain::forget(pso); super::dred::forget_pso(pso); - if let Some(s) = TRANSLATED_COMPUTE.lock().unwrap().as_mut() { + if let Some(s) = TRANSLATED_COMPUTE.write().unwrap().as_mut() { s.remove(&pso); } if let Some(s) = CONSOLE_COMPUTE.write().unwrap().as_mut() { @@ -2380,13 +2380,13 @@ fn forget_pso(pso: usize) { if let Some(m) = PSO_RS.write().unwrap().as_mut() { m.remove(&pso); } - if let Some(m) = PSO_USER_SGPRS.lock().unwrap().as_mut() { + if let Some(m) = PSO_USER_SGPRS.write().unwrap().as_mut() { m.remove(&pso); } - if let Some(m) = PSO_COMPUTE_THREADS.lock().unwrap().as_mut() { + if let Some(m) = PSO_COMPUTE_THREADS.write().unwrap().as_mut() { m.remove(&pso); } - if let Some(s) = BVH_TRAVERSAL_PSOS.lock().unwrap().as_mut() { + if let Some(s) = BVH_TRAVERSAL_PSOS.write().unwrap().as_mut() { s.remove(&pso); } super::device_x::forget_base(pso); @@ -4563,13 +4563,13 @@ fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { } /// user SGPRs of the console CS of a translated compute pipeline -static PSO_USER_SGPRS: Mutex>> = Mutex::new(None); +static PSO_USER_SGPRS: std::sync::RwLock>> = std::sync::RwLock::new(None); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). pub fn pso_user_sgprs(pso: usize) -> Option { let pso = super::pso_async::resolve(pso); - PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_USER_SGPRS.read().unwrap().as_ref()?.get(&pso).copied() } /// The root signature a translated pipeline state was created with. @@ -5255,7 +5255,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const note_pso_rs(*ppv, rs as *mut c_void); super::dred::label_text(*ppv as usize, || format!("cs {record:016x} piece 0")); if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + PSO_USER_SGPRS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } note_compute_threads(*ppv as usize, cs); note_bvh_traversal(*ppv as usize, cs); @@ -5277,7 +5277,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + PSO_USER_SGPRS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } note_compute_threads(*ppv as usize, cs); note_bvh_traversal(*ppv as usize, cs); @@ -5309,7 +5309,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + PSO_USER_SGPRS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); } note_compute_threads(*ppv as usize, cs); note_bvh_traversal(*ppv as usize, cs); @@ -6693,7 +6693,7 @@ unsafe fn go_background( } } if bvh_trav { - BVH_TRAVERSAL_PSOS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + BVH_TRAVERSAL_PSOS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } } let job: super::pso_async::Job = Box::new(move || { @@ -6785,7 +6785,7 @@ unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID unsafe fn note_translated_compute(hr: HRESULT, ppv: *mut *mut c_void) { if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + TRANSLATED_COMPUTE.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 5eb6b8e5f1..9429ed0e01 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -124,11 +124,11 @@ static MADE_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsi pub fn arena_bytes() -> (usize, usize) { (ARENAS.lock().unwrap().bytes(), MADE_BYTES.load(std::sync::atomic::Ordering::Relaxed)) } -static PLACED_TEXTURES: Mutex>> = Mutex::new(None); +static PLACED_TEXTURES: std::sync::RwLock>> = std::sync::RwLock::new(None); /// A texture backed by one of the aliasable D3D12 heaps. pub(super) fn is_placed_texture(resource: usize) -> bool { - PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) + PLACED_TEXTURES.read().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } /// Maximum idle reserved sampled textures kept per device for reuse (#1268). @@ -252,7 +252,7 @@ unsafe fn release_raw_com(raw: usize) { } pub(super) fn forget_for_recycle(resource: usize, held: bool) -> Option { - let placed = PLACED_TEXTURES.lock().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); + let placed = PLACED_TEXTURES.write().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); if !placed { return None; } @@ -1819,7 +1819,7 @@ unsafe fn place_on_pages( *ppv = std::ptr::null_mut(); return None; } - PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); + PLACED_TEXTURES.write().unwrap().get_or_insert_with(HashSet::new).insert(raw as usize); Some(hr) } @@ -2351,7 +2351,7 @@ pub unsafe fn place_pages( let aliases_live = va % PAGE == 0 && has_live_page(dev.as_raw() as usize, canonical_va(va)); if !aliases_live { if let Some(hr) = super::vram_small::place(dev, this, va, desc, state, clear, console_bytes, riid, ppv) { - PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + PLACED_TEXTURES.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); return Some(hr); } } @@ -2476,7 +2476,7 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st ARENAS.lock().unwrap().release(id, now); return None; } - PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + PLACED_TEXTURES.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); ARENA_OF.lock().unwrap().get_or_insert_with(std::collections::HashMap::new).insert(*ppv as usize, id); Some(hr) } From 8549b14de7907d622697fbc67825be20931dcae7 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:00:13 +0100 Subject: [PATCH 148/258] d3d12x: unlock sparse Map readback waits and adapt #2548/#2549/#2550 Eliminate the global sparse STATE lock convoy across synchronous GPU fence waits in sparse::readback_now (triggered on ID3D12Resource::Map readbacks) by pooling per-Map ReadbackJob objects (COPY command allocator + list + persistently-mapped READBACK staging buffer + OS fence event) outside STATE. STATE is now only held briefly to flush pending zero/dirty pages and snapshot mapped spans, to submit/signal on the copy queue, and to copy still-committed non-hole bytes back into host memory after the fence wait completes unlocked. Also adapt three upstream fixes cleanly atop our runtime branch: - #2548: use pso_async::resolve (non-blocking) instead of resolve_for_bind in device_x::create_list, list_x::kickoff_x, and list_x::reset_pc so list creation/reset with a compiling compute PSO never stalls the title thread. - #2549: preserve own_alloc when split() reuses a spare segment whose previous recording held deferred dispatches' allocator. - #2550: add pso_async::is_stand_in and bind::note_skipped_indirect to call list_x::note_dropped_draw on skipped graphics ExecuteIndirect paths (including stand-in / two-pass PSOs) so dropped draws stay tracked consistently. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 19 +- crates/xcl/src/hle/d3d12x/device_x.rs | 2 +- crates/xcl/src/hle/d3d12x/list_x.rs | 10 +- crates/xcl/src/hle/d3d12x/pso_async.rs | 5 + crates/xcl/src/hle/d3d12x/sparse.rs | 236 +++++++++++++++++++++---- 5 files changed, 236 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index af35428d50..968ca2c73b 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -2834,6 +2834,14 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: pc_dm(this, x, y, z); } +/// An ExecuteIndirect that could have drawn is skipped: mark any active occlusion query visible +/// so the title does not treat skipped geometry as occluded (Dispatch signatures make no samples). +fn note_skipped_indirect(this: *mut c_void, sig: usize) { + if !signature_dispatches(sig) { + super::list_x::note_dropped_draw(this); + } +} + /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a /// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root /// arguments themselves cannot be – skipped, logged) @@ -2938,6 +2946,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // doesn't match the currently set Pipeline State Object"; a retail title's world then // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. if super::pso_async::is_pending(raw_pso) { + note_skipped_indirect(this, sig); count(DRAWS_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -2950,6 +2959,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // with the title's graphics root signature (e.g. a non-DispatchMesh indirect draw or a // root-changing signature) invalidates the command list (Close → E_INVALIDARG). if let Some(tp) = super::real::two_pass_of(pso) { + note_skipped_indirect(this, sig); count(DRAWS_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -2983,6 +2993,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); } if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { + if gfx { + note_skipped_indirect(this, sig); + } static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: ExecuteIndirect that changes root arguments with a translated pipeline skipped"); @@ -3130,6 +3143,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } Err(e) => { + if gfx { + note_skipped_indirect(this, sig); + } if guarded.is_some() { if let Some(real) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { list.SetPipelineState(real); @@ -3451,6 +3467,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option // DrawInstanced / DrawIndexedInstanced against a mesh PSO invalidates the command list // (Close → E_INVALIDARG). if let Some(tp) = super::real::two_pass_of(real) { + super::list_x::note_dropped_draw(this); count(DRAWS_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -3480,7 +3497,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option // a PC pipeline (also a stand-in or fallback: made with the title's root signature): // the title's root signature, which nothing else binds on the PC list – a draw without // one is invalid (the debug layer reports it on every GPU; WARP faults on it) - if super::pso_async::is_pending(pso) { + if super::pso_async::is_stand_in(pso) { super::list_x::note_dropped_draw(this); } let rs = with(this, |s| s.rs_gfx) as *mut c_void; diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 4ab93e9a44..39744893e0 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -96,7 +96,7 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: let hr = if super::console_list::enabled() { real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) } else { - let resolved_pso = super::pso_async::resolve_for_bind(pso); + let resolved_pso = super::pso_async::resolve(pso); let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::list_x::on_create(*ppv, alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 02ea23fdc2..587cbb1315 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3302,7 +3302,10 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ let old_next = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); - let old = m.remove(&(next_pc as usize)); + let mut old = m.remove(&(next_pc as usize)); + // A spare that was previously a first segment holds the allocator its deferred segments + // recorded on: keep it alive while those dispatches may still execute on the GPU (#2549). + let own_alloc = old.as_mut().and_then(|o| o.own_alloc.take()); if let Some(ref o) = old { if !o.pending_waits.is_empty() { PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); @@ -3333,6 +3336,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ pred_in_state: false, predication, bindings: bindings.clone(), + own_alloc, ..Default::default() }, ); @@ -3979,7 +3983,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { }; let ext_closed = *(target as *const usize); - let init_pso = super::pso_async::resolve_for_bind(bound_pso); + let init_pso = super::pso_async::resolve(bound_pso); let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| { pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso) }); @@ -4848,7 +4852,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 // A failed native Reset leaves the old recording alive. Do not discard its tracked state or // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); - let resolved = super::pso_async::resolve_for_bind(pso); + let resolved = super::pso_async::resolve(pso); // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index ce8250be4a..039f698c17 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1762,6 +1762,11 @@ pub fn is_pending(pso: usize) -> bool { entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) } +/// `pso` is a stand-in with no real pipeline yet (still building or build failed: draws nothing). +pub fn is_stand_in(pso: usize) -> bool { + entry(pso).is_some_and(|p| p.real.load(Ordering::Acquire) == 0) +} + /// One of the title's threads is about to wait for `pso`. pub fn want(pso: usize) { if let Some(p) = entry(pso) { diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 2b41a276bb..820f820b8b 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1361,50 +1361,224 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz s.readback_ranges(&merged); } +/// Pooled per-`Map` synchronous readback resources so concurrent `ID3D12Resource::Map` readbacks +/// record, submit, and GPU-wait OUTSIDE the global `STATE` lock (avoiding `STATE` convoy stalls). +struct ReadbackJob { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + buf: ID3D12Resource, + event: HANDLE, + mapped: usize, + cap: usize, + dev_key: usize, +} + +unsafe impl Send for ReadbackJob {} + +impl Drop for ReadbackJob { + fn drop(&mut self) { + if !self.event.is_invalid() { + unsafe { let _ = windows::Win32::Foundation::CloseHandle(self.event); } + } + } +} + +const MAX_RB_JOBS: usize = 16; +const MIN_RB_JOB_BYTES: usize = 256 << 10; +static FREE_RB_JOBS: Mutex> = Mutex::new(Vec::new()); + +unsafe fn take_readback_job(dev: &ID3D12Device, need: usize) -> Option { + let dev_key = dev.as_raw() as usize; + let want = need.max(MIN_RB_JOB_BYTES).min(READBACK_STAGING); + { + let mut free = FREE_RB_JOBS.lock().unwrap(); + if let Some(i) = free.iter().position(|j| j.dev_key == dev_key && j.cap >= want) { + return Some(free.swap_remove(i)); + } + } + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY).ok()?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &alloc, None).ok()?; + let _ = list.Close(); + let mut d = buffer_desc(want as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + let mut r: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &d, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut r, + ) + .ok()?; + let buf = r?; + let mut p = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + if p.is_null() { + return None; + } + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).ok()?; + Some(ReadbackJob { alloc, list, buf, event, mapped: p as usize, cap: want, dev_key }) +} + +fn return_readback_job(job: ReadbackJob) { + let mut free = FREE_RB_JOBS.lock().unwrap(); + if free.len() < MAX_RB_JOBS { + free.push(job); + } +} + /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with /// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending /// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then -/// copies the range back from VRAM into CPU memory. +/// copies the range back from VRAM into CPU memory using a per-call pooled `ReadbackJob` whose +/// GPU fence wait runs OUTSIDE the global `STATE` lock. pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; } - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; - if s.window_index(va).is_none() { + // 1. Flush pending clears & dirty CPU chunks under `STATE`, collect mapped spans, then release + // `STATE` before recording/waiting so other `Map` threads and `before_execute` never stall. + let (dev, spans): (ID3D12Device, Vec<(usize, ID3D12Resource, u64, usize)>) = { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return }; + if s.window_index(va).is_none() { + return; + } + let zeroed = std::mem::take(&mut s.to_zero); + if !zeroed.is_empty() { + for &(a, n) in &zeroed { + s.clear_sent_range(a, n); + } + s.upload_zeros(&zeroed); + } + // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` + let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); + let mut pg = va & !(PAGE - 1); + let end = va + len; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = s.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + let idx = (p - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); + scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); + } + p += PAGE; + } + } + pg = tile_end; + } + if !dirty_runs.is_empty() { + s.upload_dirty(&dirty_runs); + } + let mut spans = Vec::new(); + let mut done = 0usize; + while done < len { + let cur = va + done; + let tile = cur & !(TILE - 1); + let Some(wi) = s.window_index(cur) else { break }; + let b = s.windows[wi].0; + let to_tile_end = (tile + TILE) - cur; + if !s.mapped.contains_key(&tile) { + done += (len - done).min(to_tile_end); + continue; + } + let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; + let chunk = (len - done).min(to_tile_end).min(to_win_end); + spans.push((cur, s.windows[wi].1.clone(), (cur - b) as u64, chunk)); + done += chunk; + } + if spans.is_empty() { + return; + } + (s.dev.clone(), spans) + }; + + let total_need: usize = spans.iter().map(|s| s.3).sum(); + let Some(job) = take_readback_job(&dev, total_need) else { + let mut g = lock_state(); + if let Some(s) = g.as_mut() { + s.readback_ranges(&[(va, len)]); + } return; - } - let zeroed = std::mem::take(&mut s.to_zero); - if !zeroed.is_empty() { - for &(a, n) in &zeroed { - s.clear_sent_range(a, n); + }; + + let mut idx = 0usize; + let mut sub_off = 0usize; + let mut pending: Vec<(usize, usize, usize)> = Vec::new(); + while idx < spans.len() { + let mut used = 0usize; + pending.clear(); + if job.alloc.Reset().is_err() || job.list.Reset(&job.alloc, None).is_err() { + break; } - s.upload_zeros(&zeroed); - } - // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` - let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); - let mut pg = va & !(PAGE - 1); - let end = va + len; - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = (t + TILE).min(end); - if let Some(entry) = s.mapped.get_mut(&t) { - let mut p = pg; - while p < tile_end { - let idx = (p - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); - scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); + while idx < spans.len() && used < job.cap { + let (dst, ref win_buf, src_base, span_len) = spans[idx]; + let rem = span_len - sub_off; + let take = rem.min(job.cap - used); + job.list.CopyBufferRegion(&job.buf, used as u64, win_buf, src_base + sub_off as u64, take as u64); + pending.push((dst + sub_off, used, take)); + used += take; + sub_off += take; + if sub_off >= span_len { + idx += 1; + sub_off = 0; + } + } + if pending.is_empty() || job.list.Close().is_err() { + break; + } + let Ok(cmd_list) = job.list.cast::() else { break }; + // 2. Submit & signal atomically under `STATE` (strictly ordered after our uploads on `s.queue`), + // then release `STATE` BEFORE waiting on the GPU fence. + let wait_target = { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { break }; + super::title_textures::own_work(|| { + s.queue.ExecuteCommandLists(&[Some(cmd_list)]); + }); + s.signal(); + (s.fence.clone(), s.value) + }; + if wait_target.1 > 0 && wait_target.0.GetCompletedValue() < wait_target.1 { + let _ = wait_target.0.SetEventOnCompletion(wait_target.1, job.event); + windows::Win32::System::Threading::WaitForSingleObject(job.event, 5000); + if wait_target.0.GetCompletedValue() < wait_target.1 { + crate::xlog_warn!( + "sparse: readback_now queue has not reached fence value {} after 5 s (at {})", + wait_target.1, + wait_target.0.GetCompletedValue() + ); + } + } + // 3. Copy only still-committed non-hole bytes into host memory and sync `sent` hashes. + let mut g = lock_state(); + let Some(s) = g.as_mut() else { break }; + let p = job.mapped as *const u8; + for &(dst, off, chunk) in &pending { + let mut at = dst; + let mut src_off = off; + let end = dst + chunk; + while at < end { + let pg = at & !(PAGE - 1); + let t = pg & !(TILE - 1); + let page_idx = (pg - t) / PAGE; + let step = (pg + PAGE).min(end) - at; + if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << page_idx) == 0) { + std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); } - p += PAGE; + at += step; + src_off += step; } + s.sync_sent_range(dst, chunk); } - pg = tile_end; - } - if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); + s.reclaim_ring(); } - s.readback_ranges(&[(va, len)]); + return_readback_job(job); } /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that From ce9049095458efc446a340bb4559339e5edf806e Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:10:23 +0100 Subject: [PATCH 149/258] D3D12.X: submit title texture uploads asynchronously on direct title queues Port upstream #2558 adapted to amd-dev's staging pool and low-commit guards so streaming texture uploads no longer stall ExecuteCommandLists on synchronous CPU fence waits: - gpu/texture.rs: extract plan_batch and add submit_batch returning an InFlight guard that reuses STAGING_POOLS for <=8 MiB batches (returned on GPU completion) and frees oversized staging buffers immediately - title_textures.rs: submit batches inline on matching DIRECT title queues after vram::before_execute(queue), track per-queue in-flight batches bounded by 512 MiB (64 MiB under low Windows commit), and non-blockingly reclaim completed batches on quiet refresh_once ticks - vram.rs: add test helpers (note_mapping_for_test, waited_for_test) for the #2558 title-queue upload and tile-mapping wait regression tests Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/texture.rs | 113 ++++++- crates/xcl/src/hle/d3d12x/title_textures.rs | 337 +++++++++++++++++--- crates/xcl/src/hle/d3d12x/vram.rs | 20 ++ 3 files changed, 414 insertions(+), 56 deletions(-) diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index 34fcf6989a..a8963663f2 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -507,19 +507,7 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items None => Uploader::new(dev)?, }; // where each texture's texels go in the upload buffer - let mut failed = Vec::new(); - let mut planned = Vec::with_capacity(items.len()); - let mut total = 0u64; - for (k, (res, subs, states)) in items.iter().enumerate() { - match layout(dev, res, subs, states, states) { - Ok(l) => { - let base = total.div_ceil(PLACEMENT) * PLACEMENT; - total = base + l.total; - planned.push((k, l, base)); - } - Err(e) => failed.push((k, e)), - } - } + let (failed, planned, total) = plan_batch(dev, items); if planned.is_empty() { put_back(key, up); return Ok(failed); @@ -550,6 +538,105 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items Ok(failed) } +unsafe fn plan_batch(dev: &ID3D12Device, items: &[(ID3D12Resource, Vec, Vec)]) -> (Vec<(usize, String)>, Vec<(usize, Layout, u64)>, u64) { + let mut failed = Vec::new(); + let mut planned = Vec::with_capacity(items.len()); + let mut total = 0u64; + for (k, (res, subs, states)) in items.iter().enumerate() { + match layout(dev, res, subs, states, states) { + Ok(l) => { + let base = total.div_ceil(PLACEMENT) * PLACEMENT; + total = base + l.total; + planned.push((k, l, base)); + } + Err(e) => failed.push((k, e)), + } + } + (failed, planned, total) +} + +struct StagingSlot { + dev_key: usize, + cap: u64, + pooled: Option, + _unpooled: Option, +} + +impl Drop for StagingSlot { + fn drop(&mut self) { + if let Some(ms) = self.pooled.take() { + if self.cap <= STAGING_POOL_MAX_ITEM && staging_pool_cap_bytes() > 0 { + let now_ms = monotonic_ms(); + let frame = CURRENT_FRAME.load(std::sync::atomic::Ordering::Relaxed); + let mut pools = STAGING_POOLS.lock().unwrap(); + let pool = pools + .get_or_insert_with(Default::default) + .entry(self.dev_key) + .or_insert_with(|| StagingPool::new(staging_pool_cap_bytes())); + let _ = pool.release(self.cap, ms, now_ms, frame); + } + } + } +} + +/// GPU-side upload resources kept alive until `queue`'s fence passes the submitted batch. +/// Dropping an `InFlight` returns pooled `<= 8 MiB` staging buffers to `STAGING_POOLS` and frees +/// oversized staging buffers immediately. +pub struct InFlight { + _alloc: ID3D12CommandAllocator, + _list: ID3D12GraphicsCommandList, + _staging: StagingSlot, + pub bytes: u64, +} + +/// Record and execute a batch of texture uploads directly on `queue` without waiting on the CPU. +/// The returned `InFlight` must stay alive until `queue` completes this submission. +pub unsafe fn submit_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result<(Vec<(usize, String)>, Option), String> { + let (failed, planned, bytes) = plan_batch(dev, items); + if planned.is_empty() { + return Ok((failed, None)); + } + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; + let dev_key = windows::core::Interface::as_raw(dev) as usize; + let slot = if let Some(bucket) = (staging_pool_cap_bytes() > 0).then(|| staging_pool_bucket(bytes)).flatten() { + let cached = STAGING_POOLS + .lock() + .unwrap() + .as_mut() + .and_then(|m| m.get_mut(&dev_key)) + .and_then(|pool| pool.acquire(bucket)); + let (cap, ms) = match cached { + Some(hit) => hit, + None => { + let b = buffer(dev, bucket)?; + let mut mapped = std::ptr::null_mut(); + b.Map(0, None, Some(&mut mapped)).map_err(err)?; + (bucket, MappedStaging(b, mapped as *mut u8)) + } + }; + for (k, layout, base) in &planned { + let (res, subs, states) = &items[*k]; + record_into(&list, res, subs, layout, states, states, &ms.0, ms.1, *base); + } + StagingSlot { dev_key, cap, pooled: Some(ms), _unpooled: None } + } else { + let staging = buffer(dev, bytes)?; + let mut mapped = std::ptr::null_mut(); + staging.Map(0, None, Some(&mut mapped)).map_err(err)?; + for (k, layout, base) in &planned { + let (res, subs, states) = &items[*k]; + record_into(&list, res, subs, layout, states, states, &staging, mapped as *mut u8, *base); + } + staging.Unmap(0, None); + StagingSlot { dev_key, cap: bytes, pooled: None, _unpooled: Some(staging) } + }; + list.Close().map_err(err)?; + queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); + let tracked = slot.cap; + Ok((failed, Some(InFlight { _alloc: alloc, _list: list, _staging: slot, bytes: tracked }))) +} + fn put_back(key: usize, up: Uploader) { UPLOADERS.lock().unwrap().get_or_insert_with(Default::default).insert(key, up); } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d12271daa9..d3197f4058 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -883,6 +883,7 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: } unsafe fn refresh_once(queue: *mut c_void) { + reclaim_completed_on_queue(queue as usize); let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); if !sparse && TEXTURES_LEN.load(Ordering::Relaxed) == 0 { @@ -999,9 +1000,9 @@ unsafe fn refresh_once(queue: *mut c_void) { }); seed_stream_recheck(&todo, &ranges, recheck_frame); let uploaded = !todo.is_empty(); - upload_all(todo); + upload_all(todo, ID3D12CommandQueue::from_raw_borrowed(&queue)); // Ensure the submitting queue waits for any `vram::map_levels` tile mappings queued inside - // `upload_all`, even if an upload batch failed or exited early before its upload-queue wait. + // `upload_all`, even if an upload batch fell back to the upload queue or exited early. if uploaded { if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { super::vram::before_execute(q); @@ -1380,9 +1381,107 @@ fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_d batch_fits_limit(picked_count, picked_bytes, batch_dev, next_dev, next_bytes, BATCH_BYTES) } +struct QueueUploads { + fence: ID3D12Fence, + value: u64, + in_flight: std::collections::VecDeque<(u64, texture::InFlight)>, + bytes: u64, +} + +unsafe impl Send for QueueUploads {} + +static ON_QUEUE: Mutex> = Mutex::new(BTreeMap::new()); + +const IN_FLIGHT_BYTES: u64 = 512 << 20; +const IN_FLIGHT_BYTES_LOW_COMMIT: u64 = 64 << 20; + +fn in_flight_cap_bytes(low_commit: bool) -> u64 { + if low_commit { IN_FLIGHT_BYTES_LOW_COMMIT } else { IN_FLIGHT_BYTES } +} + +unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue>) -> Option { + let q = title?; + if q.GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT { + return None; + } + let mut qd: Option = None; + q.GetDevice(&mut qd).ok()?; + (qd?.as_raw() == dev.as_raw()).then(|| q.clone()) +} + +/// Non-blockingly release completed in-flight upload batches for `queue_key` so staging buffers do +/// not stay pinned during quiet frames with no new texture uploads. +unsafe fn reclaim_completed_on_queue(queue_key: usize) { + if queue_key == 0 { + return; + } + let mut g = ON_QUEUE.lock().unwrap(); + let Some(q) = g.get_mut(&queue_key) else { return }; + if q.in_flight.is_empty() { + return; + } + let done = q.fence.GetCompletedValue(); + while q.in_flight.front().is_some_and(|&(v, _)| v <= done) { + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes = q.bytes.saturating_sub(f.bytes); + } +} + +unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u32) { + let done = q.fence.GetCompletedValue(); + while q.in_flight.front().is_some_and(|&(v, _)| v <= done) { + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes = q.bytes.saturating_sub(f.bytes); + } + while q.bytes > cap { + let Some(&(v, _)) = q.in_flight.front() else { break }; + if crate::gpu::fence::wait(&q.fence, v, dev, None, wait_ms).is_err() { + break; + } + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes = q.bytes.saturating_sub(f.bytes); + } +} + +unsafe fn submit_on_title_queue(dev: &ID3D12Device, queue: &ID3D12CommandQueue, batch: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + // Wait for any tile mappings queued since `queue` last waited (from another thread or from + // `map_levels_with_texels` above) so copy-engine writes never hit unmapped tiles. + super::vram::before_execute(queue); + let (failed, f) = texture::submit_batch(dev, queue, batch)?; + let Some(f) = f else { return Ok(failed) }; + let mut g = ON_QUEUE.lock().unwrap(); + let key = queue.as_raw() as usize; + if !g.contains_key(&key) { + match dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + Ok(fence) => { + g.insert(key, QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); + } + Err(e) => { + texture::wait(dev, queue)?; + drop(f); + return Err(e.to_string()); + } + } + } + let q = g.get_mut(&key).unwrap(); + q.value += 1; + if let Err(e) = queue.Signal(&q.fence, q.value) { + q.value -= 1; + texture::wait(dev, queue)?; + drop(f); + return Err(e.to_string()); + } + q.bytes = q.bytes.saturating_add(f.bytes); + let v = q.value; + q.in_flight.push_back((v, f)); + reclaim(dev, q, in_flight_cap_bytes(super::vram::commit_low()), 10_000); + Ok(failed) +} + /// The uploads `todo`, in batches of up to `BATCH_BYTES` (or `BATCH_BYTES_LOW_COMMIT` when Windows -/// commit is below reserve) and `BATCH_ITEMS` (one list and one wait each). -unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { +/// commit is below reserve) and `BATCH_ITEMS`. Direct title queues execute uploads inline with a +/// bounded in-flight staging ring (no CPU fence stall); other queues fall back to the upload queue. +unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12CommandQueue>) { static N: AtomicU64 = AtomicU64::new(0); let warn = |e: &str| { if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1441,6 +1540,18 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; + if let Some(tq) = title_queue_for(dev, title) { + match own_work(|| submit_on_title_queue(dev, &tq, &batch)) { + Ok(failed) => { + for (_, e) in failed { + warn(&e); + } + UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); + } + Err(e) => warn(&e), + } + continue; + } let queue = match upload_queue(dev, device) { Ok(q) => q, Err(e) => { @@ -2155,6 +2266,185 @@ mod tests { forget(res); } + #[test] + fn in_flight_cap_shrinks_under_low_commit() { + assert_eq!(in_flight_cap_bytes(false), IN_FLIGHT_BYTES); + assert_eq!(in_flight_cap_bytes(true), IN_FLIGHT_BYTES_LOW_COMMIT); + assert!(in_flight_cap_bytes(true) < in_flight_cap_bytes(false)); + } + + unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec { + own_work(|| { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + dev.GetCopyableFootprints(&texture.GetDesc(), 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); + let mut readback = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback, + ).unwrap(); + let readback: ID3D12Resource = readback.unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let barrier = |before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(texture), Subresource: 0, StateBefore: before, StateAfter: after }) }, + ..Default::default() + }; + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, dev, None, 5_000).unwrap(); + let mut data = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut data)).unwrap(); + let mut out = Vec::with_capacity(64 * 64); + for y in 0..64 { + out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), 64)); + } + readback.Unmap(0, None); + out + }) + } + + #[test] + fn gpu_uploads_on_the_title_queue_run_before_its_later_work_and_are_released() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let compute: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + assert!(title_queue_for(dev, Some(&queue)).is_some()); + assert!(title_queue_for(dev, Some(&compute)).is_none()); + assert!(title_queue_for(dev, None).is_none()); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let key = queue.as_raw() as usize; + let upload = |value: u8| { + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![value; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + }; + for value in [0x21, 0xC4] { + upload(value); + assert_eq!(read_r8(dev, &queue, &texture), vec![value; 64 * 64], "the title queue's next work sees the upload"); + } + upload(0x5E); + { + let mut g = ON_QUEUE.lock().unwrap(); + let q = g.get_mut(&key).unwrap(); + assert_eq!(q.value, 3); + reclaim(dev, q, 0, 10_000); + assert!(q.in_flight.is_empty() && q.bytes == 0, "over the cap the oldest uploads are waited for and released"); + assert!(q.fence.GetCompletedValue() >= 3); + } + assert_eq!(read_r8(dev, &queue, &texture), vec![0x5E; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + + #[test] + fn gpu_a_title_queue_upload_waits_for_the_page_mappings_before_it() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let Some(mapped) = super::super::vram::note_mapping_for_test(dev) else { + crate::gpu::recomp::runner::skip_test("no texture pages on this device"); + return; + }; + let key = queue.as_raw() as usize; + assert!(super::super::vram::waited_for_test(raw_device as usize, key) < mapped); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x3C; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + assert_eq!( + super::super::vram::waited_for_test(raw_device as usize, key), + mapped, + "the title queue's upload must wait for the page mappings made before it" + ); + assert_eq!(read_r8(dev, &queue, &texture), vec![0x3C; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + + #[test] + fn gpu_an_upload_still_running_is_kept_when_its_wait_times_out() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let key = queue.as_raw() as usize; + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x77; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])])).unwrap(); + { + let mut g = ON_QUEUE.lock().unwrap(); + let q = g.get_mut(&key).unwrap(); + reclaim(dev, q, 0, 50); + assert_eq!(q.in_flight.len(), 1, "a batch the GPU has not run stays in flight when its wait times out"); + assert!(q.bytes > 0); + } + gate.Signal(1).unwrap(); + { + let mut g = ON_QUEUE.lock().unwrap(); + let q = g.get_mut(&key).unwrap(); + reclaim(dev, q, 0, 10_000); + assert!(q.in_flight.is_empty() && q.bytes == 0); + } + assert_eq!(read_r8(dev, &queue, &texture), vec![0x77; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + /// Real uploads, dirty-page detection and a source changing after registration: /// bookkeeping alone cannot show that the bytes the GPU sees follow the mirror. #[test] @@ -2203,45 +2493,6 @@ mod tests { assert!(kernelx::in_graphics_reservation(at), "fallback must be write-watched"); reservation } - unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec { - own_work(|| { - let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); - let mut total = 0; - dev.GetCopyableFootprints(&texture.GetDesc(), 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); - let mut readback = None; - dev.CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, - &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, - D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback, - ).unwrap(); - let readback: ID3D12Resource = readback.unwrap(); - let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); - let barrier = |before, after| D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, - Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(texture), Subresource: 0, StateBefore: before, StateAfter: after }) }, - ..Default::default() - }; - list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; - let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); - list.Close().unwrap(); - queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); - queue.Signal(&fence, 1).unwrap(); - crate::gpu::fence::wait(&fence, 1, dev, None, 5_000).unwrap(); - let mut data = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut data)).unwrap(); - let mut out = Vec::with_capacity(64 * 64); - for y in 0..64 { - out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), 64)); - } - readback.Unmap(0, None); - out - }) - } unsafe { let raw_device = super::super::real::device_raw(); let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 9429ed0e01..04cc55ef7d 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2219,6 +2219,26 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { #[cfg(test)] pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); +/// A tile mapping on `dev`'s page queue, as `map` leaves it (the fence advanced and signalled +/// there): the value a queue must wait for before work that uses the pages. None: no pages on +/// this device (no tiled resources). +#[cfg(test)] +pub(super) unsafe fn note_mapping_for_test(dev: &ID3D12Device) -> Option { + let mut g = PAGES.lock().unwrap(); + let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; + pages.value += 1; + pages.queue.Signal(&pages.fence, pages.value).ok()?; + pages.dirty_signal = false; + Some(pages.value) +} + +/// The page mapping value `queue` was last made to wait for on `dev` (`before_execute`). +#[cfg(test)] +pub(super) fn waited_for_test(dev: usize, queue: usize) -> u64 { + let g = PAGES.lock().unwrap(); + g.get(&dev).and_then(|p| p.as_ref()).and_then(|p| p.waited.get(&queue).copied()).unwrap_or(0) +} + /// Whether `va` already has a live (or still within `IDLE`) 64 KiB page on `device` (e.g., an /// existing GPU-owned render target that a sampled view at the same 64 KiB-aligned address should /// alias). From 9f02a3b28633e1725c38b236724c09fa6f32d244 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:35:26 +0100 Subject: [PATCH 150/258] DXIL: guard null/out-of-window BVH nodes and all-zero Box32 children Unmapped or null BVH node addresses (or 112-byte Box32 nodes straddling a window boundary) previously let image_bvh*_intersect_ray read zeroes and loop indefinitely during traversal. Guard multi-window BVH traversal on hi != 0, window < mems.len(), full >= 0x10000, and end-of-node hi_end == hi, defaulting inactive/invalid lanes to all-miss (u32::MAX), and reject all-zero child/box entries as miss (u32::MAX) inside bvh_intersect while preserving synthetic tests that use child == 0 with non-zero bounding boxes. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/lower_image.rs | 49 ++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_image.rs b/crates/xcl/src/gpu/dxil/lower_image.rs index c366666fd9..293add2d85 100644 --- a/crates/xcl/src/gpu/dxil/lower_image.rs +++ b/crates/xcl/src/gpu/dxil/lower_image.rs @@ -146,7 +146,26 @@ impl Lw { let b = lw.fmin(hi[0], hi[1]); let b = lw.fmin(b, hi[2]); let cv = lw.cmpc(Pred::Ne, child[k], u32::MAX); - let mut all = cv; + // Reject all-zero unmapped-page / Box32 page-straddle entries where + // `child == 0` AND all box bounds are 0 (prevents infinite BVH traversal + // loops on unmapped sparse tiles while preserving synthetic tests that use + // child index 0 with real non-zero box bounds). + let nonzero = if box32 { + let b = 4 + 6 * k; + let mut m = child[k]; + for j in 0..6 { + m = lw.or(m, words[b + j]); + } + lw.nz(m) + } else { + let b = 4 + 3 * k; + let mut m = child[k]; + for j in 0..3 { + m = lw.or(m, words[b + j]); + } + lw.nz(m) + }; + let mut all = lw.land(cv, nonzero); for c in 0..3 { let le = lw.fcmp(Pred::FOLe, mn[c], mx[c]); all = lw.land(all, le); @@ -918,7 +937,11 @@ impl Lw { let base_lo = self.shlc(d0, 8); let off_lo = self.shlc(nlo, 3); let a = self.add(base_lo, off_lo); - // the window: bits 32.. of the 64-bit address + // the window: bits 32.. of the 64-bit address; also verify the node is non-null + // (`full >= 0x10000`, `hi != 0`) and that both the start and end of a 128 B Box32 + // node (`full + 111`) fall within valid UMA windows so out-of-window / null BVH + // roots never read `[0; 28]` or straddle into an unmapped window. + let mut bvh_valid = self.b(true); if self.mems.len() > 1 { let d1lo = self.andc(d1, 0xFF); let b64 = self.pack64(d0, d1lo); @@ -939,6 +962,19 @@ impl Lw { let full = self.add(b64, off); let (_, hi) = self.unpack64(full); self.window_hi(hi, false); + let hi_nz = self.nz(hi); + let w = self.rd(super::lower::VAR_WIN); + let w_ok = self.cmpc(Pred::ULt, w, self.mems.len() as u32); + // Check end of 112-byte Box32 node (`full + 111`) stays in-window as well. + let k111 = self.c64(111); + let full_end = self.add(full, k111); + let (_, hi_end) = self.unpack64(full_end); + let same_hi = self.cmp(Pred::Eq, hi_end, hi); + let k64k = self.c64(0x1_0000); + let non_null = self.cmp(Pred::UGe, full, k64k); + let ok1 = self.land(hi_nz, w_ok); + let ok2 = self.land(same_hi, non_null); + bvh_valid = self.land(ok1, ok2); } let ty = self.andc(node, 7); let sort = { @@ -946,8 +982,15 @@ impl Lw { self.nz(s) }; let act = self.act(); + let guard = self.land(act, bvh_valid); let out = [self.tmp_var(), self.tmp_var(), self.tmp_var(), self.tmp_var()]; - self.guarded(act, &mut |lw| { + // Default to all-miss (`u32::MAX`) for active lanes whose BVH node address was + // null/out-of-window so traversal exits immediately instead of looping on zeroes. + let ones = self.c(u32::MAX); + for (c, _) in out.iter().enumerate() { + self.write32(&super::lower::Dst::V(vdata + c as u64), ones); + } + self.guarded(guard, &mut |lw| { lw.bvh_intersect(ty, a, extent, origin, dir, inv, sort, out)?; for (c, &t) in out.iter().enumerate() { let v = lw.rd(t); From 46aecbf702b1747e1c8e0990a890c1a88fce2989 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:35:27 +0100 Subject: [PATCH 151/258] DXIL: shrink emitted shaders 4.5x-5.4x via abbrevs, compact micro-blocks, and IR opts Large console compute shaders previously exceeded 1 MB of DXIL bitcode (>136k instructions, 15k interned table constants, 84 switches) and stalled or OOM-spiked amdxc64 during pipeline creation on AMD RDNA4. - Bitcode encoding (bitstream.rs, module.rs, bitreader_tests.rs): emit LLVM DEFINE_ABBREV records for hot instruction/constant opcodes, emit compact lookup tables via CST_CODE_DATA (ConstDef::DataI32), and prune dead constants in write_bitcode (~6.88 -> 4.31 B/inst). - Compact form (compact.rs, lower.rs, kernel.rs): isolate repeated heavy memory ops (ENC_MUBUF/MTBUF/SMEM/MIMG/FLAT) into standalone micro-blocks, run backward SGPR+SCC liveness to strip dead far-jump veneers and dead SCC/SGPR slot stores, strip pure no-ops and bypass empty non-header jump blocks while preserving fallthroughs, add TargetPool successor encoding, and support single-literal / S_GETPC_B64 parameterization on large shaders. - IR optimization (opt.rs, lanes.rs, prelude.rs, lower_valu.rs, pso.rs): multi-iteration fixed-point optimize() with intra-block scalar alloca store->load forwarding + DSE, entry hoisting of repeated ReadNone system intrinsics (keeping createHandleFromHeap unshared and annotateHandle / getDimensions block-local for AMD RDNA4 amdxc64 stability), dominator branch-fact propagation, adjacent redundant barrier elimination, chained select collapse, constant EXEC lanebit folding, single-instruction f32 IEEE-754 fcmp predicates, XCL_RDNA_FLOAT native op::FRC + mul/fma_legacy constant fast-paths, and XCL_HEAP_WINDOWS default ON. Verified: 201/201 gpu::dxil + gpu_bvh unit/validator/GPU tests pass with 0 dxcompiler 1.8.2502.11 errors; 95cc13288a27a96e shrinks from 1,238 KB (1,036.8 KB w/ heap windows) -> 230.8 KB (236,320 B DXBC, 37.6s amdxc64 compile) and 958400d2caf07244 -> 139.4 KB (142,740 B DXBC, 9.86s compile). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/bitreader_tests.rs | 75 +- crates/xcl/src/gpu/dxil/bitstream.rs | 141 ++- crates/xcl/src/gpu/dxil/compact.rs | 732 +++++++++++-- crates/xcl/src/gpu/dxil/compact_tests.rs | 2 +- crates/xcl/src/gpu/dxil/core_tests.rs | 3 +- crates/xcl/src/gpu/dxil/kernel.rs | 2 + crates/xcl/src/gpu/dxil/lanes.rs | 21 + crates/xcl/src/gpu/dxil/lower.rs | 28 +- crates/xcl/src/gpu/dxil/lower_valu.rs | 25 +- crates/xcl/src/gpu/dxil/module.rs | 250 ++++- crates/xcl/src/gpu/dxil/module/opt.rs | 961 ++++++++++++++---- crates/xcl/src/gpu/dxil/module/split.rs | 2 + crates/xcl/src/gpu/dxil/prelude.rs | 32 + .../xcl/src/gpu/recomp/heap_window_tests.rs | 2 +- crates/xcl/src/gpu/recomp/pso.rs | 8 +- 15 files changed, 1934 insertions(+), 350 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/bitreader_tests.rs b/crates/xcl/src/gpu/dxil/bitreader_tests.rs index b3a7b3dd41..3393060ba4 100644 --- a/crates/xcl/src/gpu/dxil/bitreader_tests.rs +++ b/crates/xcl/src/gpu/dxil/bitreader_tests.rs @@ -1,7 +1,7 @@ //! A test-only reader for the bitstream [`super::bitstream::BitWriter`] -//! produces (unabbreviated records only), used to check record layouts -//! that the validator and disassembler do not distinguish (e.g. atomic -//! ordering codes the LLVM reader maps leniently). +//! produces (both unabbreviated records and `DEFINE_ABBREV` abbreviated records), +//! used to check record layouts that the validator and disassembler do not +//! distinguish (e.g. atomic ordering codes the LLVM reader maps leniently). use super::module::{BinOp, Module, RmwOp}; @@ -12,6 +12,15 @@ pub(super) struct Block { pub blocks: Vec, } +#[derive(Clone, Debug)] +enum AbOp { + Literal(u64), + Fixed(u32), + Vbr(u32), + ArrayFixed(u32), + ArrayVbr(u32), +} + impl Block { /// Depth-first search for the first block with `id`. pub fn find(&self, id: u32) -> Option<&Block> { @@ -57,6 +66,7 @@ impl Reader<'_> { } fn block(&mut self, id: u32, width: u32, end_bit: Option) -> Block { let mut blk = Block { id, ..Default::default() }; + let mut abbrevs: Vec> = Vec::new(); loop { if end_bit.is_none() && self.pos + width as usize > self.b.len() * 8 { return blk; @@ -77,13 +87,70 @@ impl Reader<'_> { let end = self.pos + words * 32; blk.blocks.push(self.block(sub, w, Some(end))); } + 2 => { + let n = self.vbr(5); + let mut ops = Vec::new(); + let mut i = 0; + while i < n { + if self.fixed(1) == 1 { + ops.push(AbOp::Literal(self.vbr(8))); + i += 1; + } else { + match self.fixed(3) { + 1 => { + ops.push(AbOp::Fixed(self.vbr(5) as u32)); + i += 1; + } + 2 => { + ops.push(AbOp::Vbr(self.vbr(5) as u32)); + i += 1; + } + 3 => { + assert_eq!(self.fixed(1), 0, "array element must be encoded"); + match self.fixed(3) { + 1 => ops.push(AbOp::ArrayFixed(self.vbr(5) as u32)), + 2 => ops.push(AbOp::ArrayVbr(self.vbr(5) as u32)), + e => panic!("unsupported array elem encoding {e}"), + } + i += 2; + } + e => panic!("unsupported abbrev encoding {e}"), + } + } + } + abbrevs.push(ops); + } 3 => { let code = self.vbr(6) as u32; let n = self.vbr(6); let ops = (0..n).map(|_| self.vbr(6)).collect(); blk.records.push((code, ops)); } - a => panic!("unexpected abbreviation id {a}"), + a => { + let ab = abbrevs.get((a - 4) as usize).unwrap_or_else(|| panic!("unknown abbreviation id {a}")); + let mut vals = Vec::new(); + for op in ab { + match *op { + AbOp::Literal(v) => vals.push(v), + AbOp::Fixed(w) => vals.push(self.fixed(w)), + AbOp::Vbr(w) => vals.push(self.vbr(w)), + AbOp::ArrayFixed(w) => { + let len = self.vbr(6); + for _ in 0..len { + vals.push(self.fixed(w)); + } + } + AbOp::ArrayVbr(w) => { + let len = self.vbr(6); + for _ in 0..len { + vals.push(self.vbr(w)); + } + } + } + } + let code = vals[0] as u32; + blk.records.push((code, vals[1..].to_vec())); + } } } } diff --git a/crates/xcl/src/gpu/dxil/bitstream.rs b/crates/xcl/src/gpu/dxil/bitstream.rs index 70757093f1..6b23eedd51 100644 --- a/crates/xcl/src/gpu/dxil/bitstream.rs +++ b/crates/xcl/src/gpu/dxil/bitstream.rs @@ -1,21 +1,30 @@ //! LLVM bitstream writer: fixed and VBR fields, nested blocks with -//! back-patched lengths, and unabbreviated records. -//! -//! DXIL accepts the plain bitstream container without any abbreviations, -//! which keeps the writer small; size is not a concern for shader modules -//! (the driver re-encodes them anyway). +//! back-patched lengths, unabbreviated records, and LLVM `DEFINE_ABBREV` +//! abbreviations for compact DXIL encoding. /// Bit-level writer, little-endian within 32-bit words as LLVM defines. pub struct BitWriter { out: Vec, acc: u64, nbits: u32, - /// Open blocks: (byte offset of the length word, outer abbreviation width). - blocks: Vec<(usize, u32)>, + /// Open blocks: (byte offset of the length word, outer abbreviation width, next abbrev id). + blocks: Vec<(usize, u32, u32)>, width: u32, } -/// Abbreviation width used for every block we open (IDs 0..3 need 2 bits). +/// Abbreviation operand encoding for LLVM `DEFINE_ABBREV` records. +#[derive(Clone, Copy, Debug)] +pub enum AbbrevOp { + Literal(u64), + Fixed(u32), + Vbr(u32), + /// Trailing array of fixed-width operands (LLVM `Array` + `Fixed(w)` pair). + ArrayFixed(u32), + /// Trailing array of VBR-encoded operands (LLVM `Array` + `VBR(w)` pair). + ArrayVbr(u32), +} + +/// Abbreviation width used for every block opened via [`BitWriter::enter_block`] (IDs 0..7). pub const ABBREV_WIDTH: u32 = 3; impl Default for BitWriter { @@ -31,7 +40,7 @@ impl BitWriter { pub fn emit(&mut self, value: u64, width: u32) { debug_assert!(width <= 32); - debug_assert!(width == 64 || value >> width == 0, "value {value:#x} does not fit {width} bits"); + debug_assert!(width == 64 || width == 32 || value >> width == 0, "value {value:#x} does not fit {width} bits"); self.acc |= value << self.nbits; self.nbits += width; while self.nbits >= 8 { @@ -60,25 +69,114 @@ impl BitWriter { } pub fn enter_block(&mut self, id: u32) { + self.enter_block_with_width(id, ABBREV_WIDTH); + } + + pub fn enter_block_with_width(&mut self, id: u32, abbrev_width: u32) { self.emit(1, self.width); // ENTER_SUBBLOCK self.vbr(id as u64, 8); - self.vbr(ABBREV_WIDTH as u64, 4); + self.vbr(abbrev_width as u64, 4); self.align32(); let at = self.out.len(); self.out.extend_from_slice(&[0; 4]); - self.blocks.push((at, self.width)); - self.width = ABBREV_WIDTH; + self.blocks.push((at, self.width, 4)); + self.width = abbrev_width; } pub fn end_block(&mut self) { self.emit(0, self.width); // END_BLOCK self.align32(); - let (at, outer) = self.blocks.pop().expect("end_block without enter_block"); + let (at, outer, _) = self.blocks.pop().expect("end_block without enter_block"); let words = ((self.out.len() - at - 4) / 4) as u32; self.out[at..at + 4].copy_from_slice(&words.to_le_bytes()); self.width = outer; } + /// Define a block-local abbreviation (`DEFINE_ABBREV = 2`) and return its ID (`>= 4`). + pub fn define_abbrev(&mut self, ops: &[AbbrevOp]) -> u32 { + let id = { + let top = self.blocks.last_mut().expect("define_abbrev outside block"); + let id = top.2; + top.2 += 1; + id + }; + debug_assert!((id as u64) < (1u64 << self.width), "abbrev id {id} exceeds width {}", self.width); + let num_ops: u64 = ops.iter().map(|o| if matches!(o, AbbrevOp::ArrayFixed(_) | AbbrevOp::ArrayVbr(_)) { 2 } else { 1 }).sum(); + self.emit(2, self.width); // DEFINE_ABBREV + self.vbr(num_ops, 5); + for &op in ops { + match op { + AbbrevOp::Literal(v) => { + self.emit(1, 1); + self.vbr(v, 8); + } + AbbrevOp::Fixed(w) => { + self.emit(0, 1); + self.emit(1, 3); + self.vbr(w as u64, 5); + } + AbbrevOp::Vbr(w) => { + self.emit(0, 1); + self.emit(2, 3); + self.vbr(w as u64, 5); + } + AbbrevOp::ArrayFixed(w) => { + self.emit(0, 1); + self.emit(3, 3); // Array + self.emit(0, 1); + self.emit(1, 3); // Fixed element + self.vbr(w as u64, 5); + } + AbbrevOp::ArrayVbr(w) => { + self.emit(0, 1); + self.emit(3, 3); // Array + self.emit(0, 1); + self.emit(2, 3); // VBR element + self.vbr(w as u64, 5); + } + } + } + id + } + + /// Emit an abbreviated record defined by [`Self::define_abbrev`]. `values` supplies only the + /// non-literal operands in order; if `ops` ends with `ArrayFixed`/`ArrayVbr`, remaining items + /// in `values` form the array payload. + pub fn emit_abbrev(&mut self, id: u32, ops: &[AbbrevOp], values: &[u64]) { + self.emit(id as u64, self.width); + let mut idx = 0usize; + for &op in ops { + match op { + AbbrevOp::Literal(_) => {} + AbbrevOp::Fixed(w) => { + self.emit(values[idx], w); + idx += 1; + } + AbbrevOp::Vbr(w) => { + self.vbr(values[idx], w); + idx += 1; + } + AbbrevOp::ArrayFixed(w) => { + let rest = &values[idx..]; + self.vbr(rest.len() as u64, 6); + for &v in rest { + self.emit(v, w); + } + idx = values.len(); + } + AbbrevOp::ArrayVbr(w) => { + let rest = &values[idx..]; + self.vbr(rest.len() as u64, 6); + for &v in rest { + self.vbr(v, w); + } + idx = values.len(); + } + } + } + debug_assert_eq!(idx, values.len()); + } + /// An unabbreviated record. pub fn record(&mut self, code: u32, ops: &[u64]) { self.emit(3, self.width); // UNABBREV_RECORD @@ -152,4 +250,21 @@ mod tests { assert_eq!(signed(-3), 7); assert_eq!(signed(i64::MIN), 1); } + + #[test] + fn define_abbrev_round_trips_fixed_vbr_and_arrays() { + const AB: &[AbbrevOp] = &[AbbrevOp::Literal(22), AbbrevOp::ArrayFixed(32)]; + let mut w = BitWriter::new(); + for b in [b'B', b'C', 0xC0, 0xDE] { + w.emit(b as u64, 8); + } + w.enter_block_with_width(11, 3); + let id = w.define_abbrev(AB); + assert_eq!(id, 4); + w.emit_abbrev(id, AB, &[0x1234_5678, 0xDEAD_BEEF]); + w.end_block(); + let bc = w.finish(); + assert_eq!(&bc[..4], b"BC\xC0\xDE"); + assert_eq!(bc.len() % 4, 0); + } } diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index f8dfe6a544..91f8ebbd28 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -1,14 +1,192 @@ //! The compact form: each distinct block of a program lowered once, in a loop over a table. use super::cfg::{Cfg, Term}; -use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET}; +use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET, VAR_SCC}; use super::lower_mem::VAR_TMP; use super::module::{Block, Pred, Value}; use std::collections::{BTreeSet, HashMap}; +const ALL_SGPRS_MASK: u128 = (1u128 << 106) - 1; +const SCC_LIVE_BIT: u128 = 1u128 << VAR_SCC; + +fn is_pure_nop(name: &str) -> bool { + matches!( + name, + "S_NOP" + | "V_NOP" + | "S_WAITCNT" + | "S_WAITCNT_VSCNT" + | "S_WAITCNT_VMCNT" + | "S_WAITCNT_LGKMCNT" + | "S_WAITCNT_EXPCNT" + | "S_WAITCNT_DEPCTR" + | "S_INST_PREFETCH" + | "S_CLAUSE" + ) +} + +/// Conservative `(use_mask, def_mask)` over `s0..s105` (bits `0..106`) and `SCC` (bit `VAR_SCC`). +/// Any register not provably unconditionally overwritten is omitted from `def_mask`; any unknown +/// or indexed SGPR read sets all bits in `use_mask`. +fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded) -> (u128, u128) { + use crate::gpu::rdna2::{field_value, register_scale, Variant}; + if d.inst.name.starts_with("S_MOVREL") { + return (ALL_SGPRS_MASK, 0); + } + let cond_write = d.inst.name == "S_CMOVK_I32"; + let (mut u, mut def) = (0u128, 0u128); + for o in d.ienc.operands { + if o.ty == "OPR_SSRC_SPECIAL_SCC" { + if o.input { + u |= SCC_LIVE_BIT; + } + if o.output { + def |= SCC_LIVE_BIT; + } + continue; + } + let Some(f) = o.field else { continue }; + if f == "LITERAL" || o.implicit { + continue; + } + if !["SREG", "SSRC", "SDST", "OPR_SRC", "SMEM_OFFSET"].iter().any(|k| o.ty.contains(k)) { + continue; + } + if f == "SRC0" && d.variant != Variant::Plain { + if d.variant == Variant::Sdwa { + let ext = d.words.get(1).copied().unwrap_or(0); + if (ext >> 23) & 1 == 1 { + let code = ext & 0xFF; + if code < 106 { + u |= 1u128 << code; + } else if code == 253 { + u |= SCC_LIVE_BIT; + } + } + } + continue; + } + let Some(raw) = field_value(d.enc, &d.words, f) else { continue }; + let v = raw * register_scale(f); + if v == 253 && o.input { + u |= SCC_LIVE_BIT; + continue; + } + if v >= 106 { + continue; + } + let n = (o.size as u64).div_ceil(32).max(1); + for r in v..(v + n).min(106) { + if o.input || cond_write { + u |= 1u128 << r; + } + if o.output && !cond_write { + def |= 1u128 << r; + } + } + } + (u, def) +} + +fn compute_live_out(cfg: &Cfg, mblocks: &[MicroBlock], end_live: u128) -> Vec { + let n = mblocks.len(); + let mut b_use = vec![0u128; n]; + let mut b_def = vec![0u128; n]; + for (idx, blk) in mblocks.iter().enumerate() { + let (mut u, mut d) = (0u128, 0u128); + for &i in &blk.insts { + let (iu, id) = inst_sreg_scc_use_def(&cfg.insts[i]); + u |= iu & !d; + d |= id; + } + if let Term::Cond(ci, ..) = blk.term { + let (iu, _) = inst_sreg_scc_use_def(&cfg.insts[ci]); + u |= iu & !d; + } + b_use[idx] = u; + b_def[idx] = d; + } + let mut live_in = vec![0u128; n]; + let mut live_out = vec![0u128; n]; + loop { + let mut changed = false; + for idx in (0..n).rev() { + let out = match mblocks[idx].term { + Term::End => end_live, + Term::Jump(t) => if t < n { live_in[t] } else { end_live }, + Term::Cond(_, t, f) => { + let lt = if t < n { live_in[t] } else { end_live }; + let lf = if f < n { live_in[f] } else { end_live }; + lt | lf + } + }; + let inp = b_use[idx] | (out & !b_def[idx]); + if out != live_out[idx] || inp != live_in[idx] { + live_out[idx] = out; + live_in[idx] = inp; + changed = true; + } + } + if !changed { + break; + } + } + live_out +} + +/// If `blk` ends with a 3-instruction far-jump address computation (`s_getpc_b64 s[r:r+1]`, +/// `s_{add,sub}_u32 s[r]`, `s_{addc,subb}_u32 s[r+1]`) feeding a resolved `s_setpc_b64`, +/// return the destination SGPR base `r` (`< 105`) so dead far-jump veneers can be stripped. +fn resolved_far_jump_reg(cfg: &Cfg, blk: &MicroBlock) -> Option { + if !matches!(blk.term, Term::Jump(_)) || blk.insts.len() < 3 { + return None; + } + let len = blk.insts.len(); + let (i0, i1, i2) = (blk.insts[len - 3], blk.insts[len - 2], blk.insts[len - 1]); + if i1 != i0 + 1 || i2 != i1 + 1 { + return None; + } + let set = cfg.insts.get(i2 + 1)?; + if set.inst.name != "S_SETPC_B64" || set.far_target.is_none() { + return None; + } + let (get, lo, hi) = (&cfg.insts[i0], &cfg.insts[i1], &cfg.insts[i2]); + if get.inst.name != "S_GETPC_B64" { + return None; + } + if !matches!((lo.inst.name, hi.inst.name), ("S_ADD_U32", "S_ADDC_U32") | ("S_SUB_U32", "S_SUBB_U32")) { + return None; + } + let r = crate::gpu::rdna2::field_value(get.enc, &get.words, "SDST")?; + (r < 105).then_some(r) +} + +/// One virtual basic block in a compact plan (either a whole guest block or a split micro-block +/// isolating a repeated heavy memory instruction so its lowering is emitted once instead of once +/// per surrounding ALU context). +pub struct MicroBlock { + pub pc: u64, + pub insts: Vec, + pub term: Term, + pub is_header: bool, +} + +/// How the compact table encodes each micro-block's successor target(s). +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum NextEnc { + /// Pair of relative `(taken_off, not_taken_off)` indexed in `xcl_steps`. + Steps, + /// `not_taken = b + 1`; `field` holds the absolute `taken` block number directly. + Inline, + /// `not_taken = b + 1`; `field == 0` means `taken = b + 1`, else `xcl_targets[field - 1]`. + TargetPool, +} + pub struct Plan { - /// the reachable blocks in address order: the loop's block numbers + /// the reachable blocks in address order (same length as `mblocks`) pub order: Vec, + /// virtual blocks executed by the compact loop (targets in `term` are indices into `mblocks`) + pub mblocks: Vec, /// the class of each pub class: Vec, /// a block of each class (a block number) @@ -17,30 +195,52 @@ pub struct Plan { pub next: Vec<(u32, u32)>, /// the distinct pairs of offsets from a block to its two successors, sorted pub steps: Vec<(u32, u32)>, - /// an entry holds the block's taken successor itself; the other one is the next block + /// unique non-fallthrough taken targets for `NextEnc::TargetPool` + pub targets: Vec, + /// successor table encoding mode + pub next_enc: NextEnc, + /// an entry holds the block's taken successor itself (true for `Inline` and `TargetPool`) pub inline: bool, + /// per-block parameterized 32-bit literal when the block has exactly one parameterizable literal + pub blk_lit: Vec>, + /// whether `blk_lit` parameterization is enabled for this plan + pub use_lit: bool, + /// whether `S_GETPC_B64` block-PC parameterization is enabled for this plan + pub use_pc: bool, + /// union of live-out `(s0..s105 | SCC)` bitmasks across all micro-blocks in each class + pub class_live_out: Vec, } /// Most 32-bit words of tables a program may need to take the form by itself. -const MAX_TABLE_WORDS: usize = 12288; +const MAX_TABLE_WORDS: usize = 32768; impl Plan { /// Bits of a table entry: the class, and the taken successor or the index of the pair of offsets. fn widths(&self) -> (u32, u32) { - (bits(self.rep.len()), if self.inline { bits(self.order.len()) } else { bits(self.steps.len()) }) + let pb = match self.next_enc { + NextEnc::Steps => bits(self.steps.len()), + NextEnc::Inline => bits(self.mblocks.len()), + NextEnc::TargetPool => bits(self.targets.len() + 1), + }; + (bits(self.rep.len()), pb) } /// 32-bit words of the tables. pub fn words(&self) -> usize { let (cb, pb) = self.widths(); - (self.order.len() * (cb + pb) as usize).div_ceil(32) + 1 + if self.inline { 0 } else { self.steps.len() * 2 } + let extra = match self.next_enc { + NextEnc::Steps => self.steps.len() * 2, + NextEnc::Inline => 0, + NextEnc::TargetPool => self.targets.len(), + }; + (self.mblocks.len() * (cb + pb) as usize).div_ceil(32) + 1 + extra } } /// Whether a program takes the form by itself: large, mostly repeated blocks, small tables. pub fn wanted(cfg: &Cfg, p: &Plan) -> bool { - let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); - let all: usize = (0..p.order.len()).map(insts).sum(); + let insts = |n: usize| p.mblocks[n].insts.len(); + let all: usize = (0..p.mblocks.len()).map(insts).sum(); let once: usize = p.rep.iter().map(|&n| insts(n)).sum(); large(cfg) && once * 10 < all * 3 && p.words() <= MAX_TABLE_WORDS } @@ -52,59 +252,374 @@ pub fn large(cfg: &Cfg) -> bool { pub const END: u32 = u32::MAX; +fn is_heavy_mem(d: &crate::gpu::rdna2::Decoded) -> bool { + matches!( + d.enc.name, + "ENC_MUBUF" | "ENC_MTBUF" | "ENC_SMEM" | "ENC_MIMG" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" + ) && !matches!( + d.inst.name, + "S_DCACHE_INV" + | "S_DCACHE_WB" + | "S_DCACHE_DISCARD" + | "S_DCACHE_DISCARD_X2" + | "S_GL1_INV" + | "S_MEMTIME" + | "S_MEMREALTIME" + ) +} + +/// Whether a micro-block has exactly one parameterizable 32-bit literal instruction. +fn single_param_lit(cfg: &Cfg, blk: &MicroBlock) -> Option { + let mut found = None; + for &i in &blk.insts { + let d = &cfg.insts[i]; + if let Some(lit) = d.literal { + if d.inst.name == "S_SETREG_IMM32_B32" || d.enc.name == "ENC_MIMG" || found.is_some() { + return None; + } + found = Some(lit); + } + } + found +} + /// Sorts the reachable blocks into classes the lowering would emit the same for. +/// On large shaders, repeated heavy memory instructions (appearing `>= 4` times) are split +/// into standalone micro-blocks so each unique buffer/SMEM/image lowering is emitted once +/// instead of once per surrounding ALU context. pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { - let mut order = cfg.rpo.clone(); - order.sort_by_key(|&b| (cfg.blocks[b].pc, b)); - let mut number = vec![END; cfg.blocks.len()]; - for (n, &b) in order.iter().enumerate() { - number[b] = n as u32; + let mut orig_order = cfg.rpo.clone(); + orig_order.sort_by_key(|&b| (cfg.blocks[b].pc, b)); + + // Count exact heavy-memory instruction occurrences across reachable blocks. + let mut mem_counts: HashMap<(Vec, Option, Option<[u32; 4]>), usize> = HashMap::new(); + let allow_split = orig_order.len() >= 64; + if allow_split { + for &b in &orig_order { + for &i in &cfg.blocks[b].insts { + let d = &cfg.insts[i]; + if is_heavy_mem(d) { + let sampler = lw.static_samplers.get(&d.pc).copied(); + *mem_counts.entry((d.words.clone(), d.literal, sampler)).or_insert(0) += 1; + } + } + } } - let mut ids: HashMap<(Vec, &'static str), u32> = HashMap::new(); - let (mut class, mut rep, mut next) = (Vec::new(), Vec::new(), Vec::new()); - let mut falls = true; - for (n, &b) in order.iter().enumerate() { + + // Pass 1: split blocks around repeated heavy memory ops (`>= 4` occurrences). + let mut segs_per_orig: Vec<(usize, Vec>)> = Vec::with_capacity(orig_order.len()); + let mut orig_to_mb = vec![END; cfg.blocks.len()]; + let mut mb_cursor = 0u32; + for &b in &orig_order { let blk = &cfg.blocks[b]; - let mut key = vec![cfg.headers.contains(&b) as u64]; - for &i in &blk.insts { - let d = &cfg.insts[i]; - key.push(d.words.len() as u64); - key.extend(d.words.iter().map(|&w| w as u64)); - key.push(d.literal.map_or(u64::MAX, |l| l as u64)); - let sampler = lw.static_samplers.get(&d.pc); - key.push(sampler.is_some() as u64); - key.extend(sampler.into_iter().flatten().map(|&w| w as u64)); - // what `Lw::write_mask` asks of this address, for any register a mask can go to - if let Some(&l) = lw.whole_live.get(&d.pc) { - let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST")); - let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa); - key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3)); + let mut segs: Vec> = Vec::new(); + if allow_split && blk.insts.len() > 1 { + let mut cur: Vec = Vec::new(); + for &i in &blk.insts { + let d = &cfg.insts[i]; + let isolate = is_heavy_mem(d) + && mem_counts + .get(&(d.words.clone(), d.literal, lw.static_samplers.get(&d.pc).copied())) + .copied() + .unwrap_or(0) + >= 2; + if isolate { + if !cur.is_empty() { + segs.push(std::mem::take(&mut cur)); + } + segs.push(vec![i]); + } else { + cur.push(i); + } } - if d.inst.name == "S_GETPC_B64" { - key.push(d.pc); + if !cur.is_empty() { + segs.push(cur); } } - let (end, to) = match blk.term { - Term::End => ("end", (END, END)), - Term::Jump(t) => ("jump", (number[t], number[t])), - Term::Cond(i, t, f) => { - falls &= number[f] == n as u32 + 1; - (cfg.insts[i].inst.name, (number[t], number[f])) + if segs.is_empty() { + segs.push(blk.insts.clone()); + } + orig_to_mb[b] = mb_cursor; + mb_cursor += segs.len() as u32; + segs_per_orig.push((b, segs)); + } + + // Pass 2: materialize micro-blocks with remapped successor targets (stripping pure no-ops). + let mut order: Vec = Vec::with_capacity(mb_cursor as usize); + let mut mblocks: Vec = Vec::with_capacity(mb_cursor as usize); + for (orig_b, segs) in segs_per_orig { + let blk = &cfg.blocks[orig_b]; + let is_hdr = cfg.headers.contains(&orig_b); + let n_segs = segs.len(); + for (s, raw_insts) in segs.into_iter().enumerate() { + let my_id = mblocks.len(); + let pc = raw_insts.first().map_or(blk.pc, |&i| cfg.insts[i].pc); + let insts = if allow_split { + raw_insts.into_iter().filter(|&i| !is_pure_nop(cfg.insts[i].inst.name)).collect() + } else { + raw_insts + }; + let term = if s + 1 < n_segs { + Term::Jump(my_id + 1) + } else { + match blk.term { + Term::End => Term::End, + Term::Jump(t) => Term::Jump(orig_to_mb[t] as usize), + Term::Cond(ci, t, f) => Term::Cond(ci, orig_to_mb[t] as usize, orig_to_mb[f] as usize), + } + }; + order.push(orig_b); + mblocks.push(MicroBlock { pc, insts, term, is_header: s == 0 && is_hdr }); + } + } + + // Pass 3 (large shaders): strip dead far-jump veneers (`s_getpc_b64 + s_add_u32 + s_addc_u32` + // feeding a resolved `s_setpc_b64` when `s[r:r+1]` and `SCC` are dead at the jump target) and + // bypass empty non-header jump blocks so neither `xcl_blocks` nor `FUNCTION` pays for them. + let end_live = if lw.res.is_some() { ALL_SGPRS_MASK | SCC_LIVE_BIT } else { 0 }; + if allow_split { + let live_out = compute_live_out(cfg, &mblocks, end_live); + for (idx, blk) in mblocks.iter_mut().enumerate() { + if let Some(r) = resolved_far_jump_reg(cfg, blk) { + let clobber = (1u128 << r) | (1u128 << (r + 1)) | SCC_LIVE_BIT; + if (live_out[idx] & clobber) == 0 { + let new_len = blk.insts.len() - 3; + blk.insts.truncate(new_len); + } } - }; - let fresh = ids.len() as u32; - let c = *ids.entry((key, end)).or_insert(fresh); - if c == fresh { - rep.push(n); } - class.push(c); - next.push(to); + // Bypass empty non-header jump micro-blocks (entry 0 stays pinned at 0). + // Preserve `falls` (`Term::Cond` fallthrough `f == idx + 1`) by not bypassing a + // fallthrough block whose jump goes anywhere other than `cur + 1`. + let n_mb = mblocks.len(); + let mut is_fallthrough = vec![false; n_mb]; + for (idx, blk) in mblocks.iter().enumerate() { + if let Term::Cond(_, _, f) = blk.term { + if f == idx + 1 && f < n_mb { + is_fallthrough[f] = true; + } + } + } + let mut redir: Vec = (0..n_mb).collect(); + for start in 1..n_mb { + let mut cur = start; + let mut ft = is_fallthrough[start]; + for _ in 0..64 { + if cur == 0 || mblocks[cur].is_header || !mblocks[cur].insts.is_empty() { + break; + } + match mblocks[cur].term { + Term::Jump(t) if t < n_mb && t != cur => { + if ft && t != cur + 1 { + break; + } + cur = t; + ft |= is_fallthrough[cur]; + } + _ => break, + } + } + redir[start] = cur; + } + for blk in &mut mblocks { + match &mut blk.term { + Term::Jump(t) if *t < n_mb => *t = redir[*t], + Term::Cond(_, t, f) => { + if *t < n_mb { + *t = redir[*t]; + } + if *f < n_mb { + *f = redir[*f]; + } + } + _ => {} + } + if let Term::Cond(_, t, f) = blk.term { + if t == f { + blk.term = Term::Jump(t); + } + } + } + // Compact out bypassed/unreachable micro-blocks. + let mut reach = vec![false; n_mb]; + let mut stack = vec![0usize]; + reach[0] = true; + while let Some(u) = stack.pop() { + match mblocks[u].term { + Term::Jump(t) if t < n_mb && !reach[t] => { + reach[t] = true; + stack.push(t); + } + Term::Cond(_, t, f) => { + if t < n_mb && !reach[t] { + reach[t] = true; + stack.push(t); + } + if f < n_mb && !reach[f] { + reach[f] = true; + stack.push(f); + } + } + _ => {} + } + } + let mut remap = vec![END as usize; n_mb]; + let mut new_order = Vec::with_capacity(n_mb); + let mut new_mblocks = Vec::with_capacity(n_mb); + for (i, (orig_b, blk)) in order.into_iter().zip(mblocks.into_iter()).enumerate() { + if reach[i] { + remap[i] = new_mblocks.len(); + new_order.push(orig_b); + new_mblocks.push(blk); + } + } + for blk in &mut new_mblocks { + match &mut blk.term { + Term::Jump(t) if *t < n_mb => *t = remap[*t], + Term::Cond(_, t, f) => { + if *t < n_mb { + *t = remap[*t]; + } + if *f < n_mb { + *f = remap[*f]; + } + } + _ => {} + } + } + order = new_order; + mblocks = new_mblocks; + } + + let final_live_out = if allow_split { + compute_live_out(cfg, &mblocks, end_live) + } else { + vec![ALL_SGPRS_MASK | SCC_LIVE_BIT; mblocks.len()] + }; + + let build = |param_lit: bool, param_pc: bool| { + let mut ids: HashMap<(Vec, &'static str), u32> = HashMap::new(); + let (mut class, mut rep, mut next, mut blk_lit) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let mut falls = true; + for (n, blk) in mblocks.iter().enumerate() { + let p_lit = if param_lit { single_param_lit(cfg, blk) } else { None }; + blk_lit.push(p_lit); + let mut key = vec![blk.is_header as u64, p_lit.is_some() as u64]; + for &i in &blk.insts { + let d = &cfg.insts[i]; + let mask_lit = p_lit.is_some() && d.literal.is_some(); + let words = if mask_lit { &d.words[..d.words.len() - 1] } else { &d.words[..] }; + key.push(d.words.len() as u64); + key.extend(words.iter().map(|&w| w as u64)); + if mask_lit { + key.push(u64::MAX - 1); + } else { + key.push(d.literal.map_or(u64::MAX, |l| l as u64)); + } + let sampler = lw.static_samplers.get(&d.pc); + key.push(sampler.is_some() as u64); + key.extend(sampler.into_iter().flatten().map(|&w| w as u64)); + // what `Lw::write_mask` asks of this address, for any register a mask can go to + if let Some(&l) = lw.whole_live.get(&d.pc) { + let sdwa = ext_encoding(d).and_then(|e| crate::gpu::rdna2::field_value(e, &d.words, "SDST")); + let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa); + key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3)); + } + if d.inst.name == "S_GETPC_B64" { + key.push(if param_pc { d.pc.wrapping_sub(blk.pc) } else { d.pc }); + } + } + let (end, to) = match blk.term { + Term::End => ("end", (END, END)), + Term::Jump(t) => ("jump", (t as u32, t as u32)), + Term::Cond(i, t, f) => { + falls &= f == n + 1; + (cfg.insts[i].inst.name, (t as u32, f as u32)) + } + }; + let fresh = ids.len() as u32; + let c = *ids.entry((key, end)).or_insert(fresh); + if c == fresh { + rep.push(n); + } + class.push(c); + next.push(to); + } + (class, rep, next, blk_lit, falls) + }; + let base = build(false, false); + let has_getpc = allow_split && mblocks.iter().any(|blk| blk.insts.iter().any(|&i| cfg.insts[i].inst.name == "S_GETPC_B64")); + // Parameterize single-literal blocks (and S_GETPC_B64 when present) on large shaders only + // when the collapsed switch arms outweigh the packed lookup tables (`~2 B/block` per table). + let (use_lit, use_pc, (class, rep, next, blk_lit, falls)) = if allow_split { + let cand = build(true, has_getpc); + let saved_both = base.1.len().saturating_sub(cand.1.len()); + let table_cost = mblocks.len() * if has_getpc { 4 } else { 2 }; + if saved_both >= 64 && saved_both * 60 > table_cost { + let only_lit = if has_getpc { build(true, false) } else { cand.clone() }; + let saved_pc = only_lit.1.len().saturating_sub(cand.1.len()); + if has_getpc && saved_pc >= 64 && saved_pc * 60 > mblocks.len() * 2 { + (true, true, cand) + } else if base.1.len().saturating_sub(only_lit.1.len()) >= 64 + && base.1.len().saturating_sub(only_lit.1.len()) * 60 > mblocks.len() * 2 + { + (true, false, only_lit) + } else { + (false, false, base) + } + } else { + (false, false, base) + } + } else { + (false, false, base) + }; + let mut class_live_out = vec![0u128; rep.len()]; + for (mb_idx, &c) in class.iter().enumerate() { + class_live_out[c as usize] |= final_live_out[mb_idx]; } let steps: BTreeSet<(u32, u32)> = next.iter().enumerate().map(|(b, &to)| offsets(b, to)).collect(); - let mut p = Plan { order, class, rep, next, steps: steps.into_iter().collect(), inline: false }; - let pairs = p.words(); - p.inline = falls; - p.inline = falls && p.words() < pairs; + let targets: Vec = if falls { + let set: BTreeSet = next + .iter() + .enumerate() + .filter_map(|(b, &(t, _))| (t != END && t != b as u32 + 1).then_some(t)) + .collect(); + set.into_iter().collect() + } else { + Vec::new() + }; + let mut p = Plan { + order, + mblocks, + class, + rep, + next, + steps: steps.into_iter().collect(), + targets, + next_enc: NextEnc::Steps, + inline: false, + blk_lit, + use_lit, + use_pc, + class_live_out, + }; + let mut best_enc = NextEnc::Steps; + let mut best_words = p.words(); + if falls { + for cand_enc in [NextEnc::Inline, NextEnc::TargetPool] { + if cand_enc == NextEnc::TargetPool && p.targets.is_empty() { + continue; + } + p.next_enc = cand_enc; + let (cb, pb) = p.widths(); + if cb + pb <= 32 && p.words() < best_words { + best_words = p.words(); + best_enc = cand_enc; + } + } + } + p.next_enc = best_enc; + p.inline = matches!(best_enc, NextEnc::Inline | NextEnc::TargetPool); let (cb, pb) = p.widths(); (cb + pb <= 32).then_some(p) } @@ -118,12 +633,12 @@ fn bits(n: usize) -> u32 { (usize::BITS - n.saturating_sub(1).leading_zeros()).max(1) } -/// A constant table of 32-bit words. +/// A constant table of 32-bit words (emitted via LLVM `CST_CODE_DATA` without interning +/// each element as an individual `CST_CODE_INTEGER` constant). fn table(lw: &mut Lw, name: &str, words: &[u32]) -> Value { - let vals: Vec = words.iter().map(|&w| lw.c(w)).collect(); let i32 = lw.s.m.i32(); let at = lw.s.m.array(words.len() as u64, i32); - let init = lw.s.m.aggregate(at, &vals); + let init = lw.s.m.const_data_i32(words); lw.s.m.global(name, at, 0, Some(init), true, 4) } @@ -207,10 +722,13 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let width = cb + pb; let mut packed = vec![0u32; (n * width as usize).div_ceil(32) + 1]; for (b, &to) in p.next.iter().enumerate() { - let field = match (p.inline, to.0) { - (true, END) => 0, - (true, t) => t, - _ => p.steps.binary_search(&offsets(b, to)).expect("a pair of the plan") as u32, + let field = match (p.next_enc, to.0) { + (NextEnc::Inline, END) => 0, + (NextEnc::Inline, t) => t, + (NextEnc::TargetPool, END) => 0, + (NextEnc::TargetPool, t) if t == b as u32 + 1 => 0, + (NextEnc::TargetPool, t) => p.targets.binary_search(&t).expect("target in pool") as u32 + 1, + (NextEnc::Steps, _) => p.steps.binary_search(&offsets(b, to)).expect("a pair of the plan") as u32, }; let e = (p.class[b] | field << cb) as u64; let at = b * width as usize; @@ -219,7 +737,44 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block } let blocks = table(lw, "xcl_blocks", &packed); let steps: Vec = p.steps.iter().flat_map(|&(t, f)| [t, f]).collect(); - let steps = (!p.inline).then(|| table(lw, "xcl_steps", &steps)); + let steps = (p.next_enc == NextEnc::Steps).then(|| table(lw, "xcl_steps", &steps)); + let target_pool = (p.next_enc == NextEnc::TargetPool).then(|| table(lw, "xcl_targets", &p.targets)); + let pc_table = p.use_pc.then(|| { + let max_pc_dw = p.mblocks.iter().map(|blk| (blk.pc >> 2) as usize).max().unwrap_or(0); + let pc_w = bits(max_pc_dw + 1).min(32); + let mut pc_packed = vec![0u32; (n * pc_w as usize).div_ceil(32) + 1]; + for (b, blk) in p.mblocks.iter().enumerate() { + let v = (blk.pc >> 2) as u64; + let at = b * pc_w as usize; + pc_packed[at / 32] |= (v << (at % 32)) as u32; + pc_packed[at / 32 + 1] |= (v << (at % 32) >> 32) as u32; + } + (table(lw, "xcl_pc", &pc_packed), pc_w) + }); + let lit_table = p.use_lit.then(|| { + // Deduplicate unique 32-bit literals into a pool and bit-pack pool indices per block. + let mut pool: Vec = vec![0]; + let mut idx_map: HashMap = HashMap::from([(0, 0)]); + let mut blk_idx: Vec = Vec::with_capacity(n); + for &opt in &p.blk_lit { + let val = opt.unwrap_or(0); + let idx = *idx_map.entry(val).or_insert_with(|| { + let id = pool.len() as u32; + pool.push(val); + id + }); + blk_idx.push(idx); + } + let lit_w = bits(pool.len()).min(32); + let mut idx_packed = vec![0u32; (n * lit_w as usize).div_ceil(32) + 1]; + for (b, &id) in blk_idx.iter().enumerate() { + let v = id as u64; + let at = b * lit_w as usize; + idx_packed[at / 32] |= (v << (at % 32)) as u32; + idx_packed[at / 32 + 1] |= (v << (at % 32) >> 32) as u32; + } + (table(lw, "xcl_lit_idx", &idx_packed), table(lw, "xcl_lit_pool", &pool), lit_w) + }); let (at, to) = (lw.tmp_var(), lw.tmp_var()); let (at, to, budget) = (slot(lw, at), slot(lw, to), slot(lw, VAR_BUDGET)); @@ -241,12 +796,61 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let class = lw.andc(e, (1u32 << cb) - 1); let field = lw.lshrc(e, cb); let field = lw.andc(field, (1u32 << pb) - 1); + let blk_pc = pc_table.map(|(pc_tbl, pc_w)| { + let pm = if pc_w == 32 { + word(lw, pc_tbl, b) + } else { + let pw = lw.c(pc_w); + let pbit = lw.mul(b, pw); + let pi = lw.lshrc(pbit, 5); + let psh = lw.andc(pbit, 31); + let plo = word(lw, pc_tbl, pi); + let pi1 = lw.addc(pi, 1); + let phi = word(lw, pc_tbl, pi1); + let plo = lw.lshr(plo, psh); + let phi = lw.shlc(phi, 1); + let pup = lw.sub(k31, psh); + let phi = lw.shl(phi, pup); + let pe = lw.or(plo, phi); + lw.andc(pe, (1u32 << pc_w) - 1) + }; + lw.shlc(pm, 2) + }); + let blk_lit_val = lit_table.map(|(idx_tbl, pool_tbl, lit_w)| { + let id = if lit_w == 32 { + word(lw, idx_tbl, b) + } else { + let lw_c = lw.c(lit_w); + let lbit = lw.mul(b, lw_c); + let li = lw.lshrc(lbit, 5); + let lsh = lw.andc(lbit, 31); + let llo = word(lw, idx_tbl, li); + let li1 = lw.addc(li, 1); + let lhi = word(lw, idx_tbl, li1); + let llo = lw.lshr(llo, lsh); + let lhi = lw.shlc(lhi, 1); + let lup = lw.sub(k31, lsh); + let lhi = lw.shl(lhi, lup); + let le = lw.or(llo, lhi); + lw.andc(le, (1u32 << lit_w) - 1) + }; + word(lw, pool_tbl, id) + }); let (taken, not_taken) = if let Some(steps) = steps { let pi = lw.shlc(field, 1); let step_t = word(lw, steps, pi); let pi1 = lw.addc(pi, 1); let step_f = word(lw, steps, pi1); (lw.add(b, step_t), lw.add(b, step_f)) + } else if let Some(target_tbl) = target_pool { + let next_b = lw.addc(b, 1); + let is_fall = lw.cmpc(Pred::Eq, field, 0); + let one = lw.c(1); + let tidx = lw.sub(field, one); + let z = lw.c(0); + let safe_tidx = lw.sel(is_fall, z, tidx); + let pooled = word(lw, target_tbl, safe_tidx); + (lw.sel(is_fall, next_b, pooled), next_b) } else { (field, lw.addc(b, 1)) }; @@ -283,8 +887,8 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block lw.s.m.set_block(c); lw.init.mem = Some(c); lw.ssa.begin_log(); - let blk = &cfg.blocks[p.order[r]]; - if cfg.headers.contains(&p.order[r]) { + let blk = &p.mblocks[r]; + if blk.is_header { // a loop head spends the loop budget let left = lw.s.m.load(budget, 4); let none = lw.cmpc(Pred::Eq, left, 0); @@ -299,9 +903,13 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let l = lw.sub(left, one); lw.s.m.store(budget, l, 4); } + lw.compact_blk_pc = blk_pc.map(|v| (v, blk.pc)); + lw.compact_lit = if p.blk_lit[r].is_some() { blk_lit_val } else { None }; for &i in &blk.insts { lw.inst(&cfg.insts[i])?; } + lw.compact_blk_pc = None; + lw.compact_lit = None; let next = match blk.term { Term::End => lw.c(END), Term::Jump(_) => taken, @@ -310,7 +918,11 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block lw.sel(c, taken, not_taken) } }; + let live_out = p.class_live_out[k]; for var in lw.ssa.end_log().into_iter().filter(|&v| v < VAR_TMP) { + if (var < 106 || var == VAR_SCC) && (live_out & (1u128 << var)) == 0 { + continue; + } let (v, p) = (lw.rd(var), slot(lw, var)); lw.s.m.store(p, v, 4); } diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 5b278ebb40..bdf4da66e8 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -201,7 +201,7 @@ fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); let p = super::compact::plan(&cfg, &lw).unwrap(); - assert!(p.inline && p.words() > 8192 && p.words() <= 12288); + assert!(p.inline && p.order.len() > 16384 && p.words() <= 12288); assert!(super::compact::wanted(&cfg, &p)); let k = translate_full(&code, o).unwrap(); for initial in [0u32, u32::MAX - 1, 0u32.wrapping_sub(COPIES as u32), 0u32.wrapping_sub((2 * COPIES) as u32), 0u32.wrapping_sub(COPIES as u32 + 1)] { diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index a86c1f72d4..b688c92f0b 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -622,7 +622,7 @@ fn raw_buffer_oob_check_guards_32bit_wraparound() { // (`icmp uge`) for both `voff + OFFSET` and `off + bytes` (#1893). let code = prog(&[ ("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 3), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 16)], None), - ("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 16)], None), + ("BUFFER_ATOMIC_ADD", "ENC_MUBUF", &[("VDATA", 4), ("VADDR", 0), ("SRSRC", 0), ("SOFFSET", 128), ("OFFEN", 1), ("OFFSET", 20)], None), ]); let dxil = translate(&code, ko).expect("mubuf + atomic translates"); super::validate::validate(&dxil).expect("validates"); @@ -642,6 +642,7 @@ fn compute_movrel_uses_program_max_vgpr_and_masks_m0() { ("V_MOV_B32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 129)], None), ("V_MOVRELS_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", 256 + 1)], None), ("V_MOV_B32", "ENC_VOP1", &[("VDST", 5), ("SRC0", 130)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 1), ("DATA", 0), ("SADDR", 0x7D), ("OFFSET", 0)], None), ]); let cs = CsInterface { threads: [32, 1, 1], user_sgprs: 2, tgid: [false; 3], tg_size: false, tid_components: 1 }; let k = super::kernel::translate_compute(&code, ko, &cs).expect("compute movrel translates"); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 452d517998..22cc20d7f7 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -546,6 +546,8 @@ impl Lw { .max() .unwrap_or(0), exec_cache: HashMap::new(), + compact_blk_pc: None, + compact_lit: None, xs: None, xw: None, xc: None, diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 41c85abdf4..3bc1cd8d31 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -180,6 +180,19 @@ impl Lw { /// This lane's bit of the mask (lo, hi), cached per block. pub fn lanebit(&mut self, lo: Value, hi: Value) -> Value { + if self.wave64 { + match (self.s.m.const_u64(lo), self.s.m.const_u64(hi)) { + (Some(0xFFFF_FFFF), Some(0xFFFF_FFFF)) => return self.b(true), + (Some(0), Some(0)) => return self.b(false), + _ => {} + } + } else { + match self.s.m.const_u64(lo) { + Some(0xFFFF_FFFF) => return self.b(true), + Some(0) => return self.b(false), + _ => {} + } + } let key = (self.cur(), lo, hi); if let Some(&v) = self.exec_cache.get(&key) { return v; @@ -190,6 +203,14 @@ impl Lw { } else { lo }; + if let Some(k) = self.s.m.const_u64(w) { + if k == 0xFFFF_FFFF { + return self.b(true); + } + if k == 0 { + return self.b(false); + } + } let l = self.lane31; let sh = self.bin(BinOp::LShr, w, l); let b = self.andc(sh, 1); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 13dfb3277a..8c9dd4b9d6 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -226,6 +226,10 @@ pub struct Lw { pub static_used: Vec<([u32; 4], bool, super::ops::Sampler)>, pub sampler_base: u32, pub exec_cache: HashMap<(Block, Value, Value), Value>, + /// dynamic block-start PC `(blk_pc_val, rep_blk_pc)` when lowering compact `S_GETPC_B64` blocks + pub compact_blk_pc: Option<(Value, u64)>, + /// dynamic 32-bit literal value when lowering a single-literal parameterized compact block + pub compact_lit: Option, /// groupshared exchange words of the split form /// split form: the halves' exchange words (storage, first index) and the lane counter pub xs: Option<(super::ops::GroupShared, u32)>, @@ -691,6 +695,10 @@ impl Lw { } /// 32-bit value of a scalar source code (0..255) or VALU source (256+ = VGPR). + fn lit_c(&mut self, lit: u32) -> Value { + self.compact_lit.unwrap_or_else(|| self.c(lit)) + } + pub fn code32(&mut self, code: u64, lit: Option, f16: bool) -> Option { Some(match code { 0..=124 | 126 | 127 => self.sreg(code), @@ -714,7 +722,7 @@ impl Lw { self.u(z) } 253 => self.scc(), - 255 => self.c(lit?), + 255 => self.lit_c(lit?), 256..=511 => self.vreg(code - 256), 235..=238 => self.c(0), 239 => self.c(0x7FFF_FFFF), @@ -738,9 +746,9 @@ impl Lw { 251 | 252 | 253 => (self.code32(code, None, false)?, self.c(0)), 255 => { if f64 { - (self.c(0), self.c(lit?)) + (self.c(0), self.lit_c(lit?)) } else { - (self.c(lit?), self.c(0)) + (self.lit_c(lit?), self.c(0)) } } 256..=510 => (self.vreg(code - 256), self.vreg(code - 255)), @@ -757,7 +765,7 @@ impl Lw { pub fn read(&mut self, d: &Decoded, o: &Operand, f16: bool) -> Option { match o.field { - Some("LITERAL") => Some(self.c(d.literal?)), + Some("LITERAL") => Some(self.lit_c(d.literal?)), Some(f) => { let v = Self::field(d, f); let width = d.enc.field_width(f); @@ -766,7 +774,7 @@ impl Lw { } match o.ty { "OPR_SIMM16" => Some(self.c(v as u32)), - "OPR_SIMM32" => Some(self.c(d.literal?)), + "OPR_SIMM32" => Some(self.lit_c(d.literal?)), _ => self.code32(v, d.literal, f16), } } @@ -1316,8 +1324,14 @@ impl Lw { return err(d, "indirect branch"); } if name == "s_getpc_b64" { - let pc = d.pc + d.len as u64; - let (lo, hi) = (self.c(pc as u32), self.c(0)); + let lo = match self.compact_blk_pc { + Some((blk_pc, rep_blk_pc)) => { + let rel = (d.pc + d.len as u64).wrapping_sub(rep_blk_pc) as u32; + if rel == 0 { blk_pc } else { self.addc(blk_pc, rel) } + } + None => self.c((d.pc + d.len as u64) as u32), + }; + let hi = self.c(0); self.write64(&dst, lo, hi); return Ok(()); } diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index a952b8567c..b2805c5f17 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -1324,8 +1324,31 @@ impl Lw { }) } - /// The recompiler's `float_compare`: NaN tested explicitly. + /// Float compare: single-instruction IEEE-754 ordered/unordered `fcmp` for `f32`, + /// explicit `isnan_d` for `f64`. pub fn float_compare(&mut self, opn: &str, a: Value, b: Value) -> Option { + let is_f32 = self.s.m.type_of(a) == self.s.m.f32(); + if is_f32 { + return Some(match opn { + "f" => self.b(false), + "t" | "tru" => self.b(true), + "lt" => self.fcmp(Pred::FOLt, a, b), + "eq" => self.fcmp(Pred::FOEq, a, b), + "le" => self.fcmp(Pred::FOLe, a, b), + "gt" => self.fcmp(Pred::FOGt, a, b), + "ge" => self.fcmp(Pred::FOGe, a, b), + "lg" => self.fcmp(Pred::FONe, a, b), + "o" => self.fcmp(Pred::FOrd, a, b), + "u" => self.fcmp(Pred::FUno, a, b), + "nlt" => self.fcmp(Pred::FUGe, a, b), + "neq" => self.fcmp(Pred::FUNe, a, b), + "nle" => self.fcmp(Pred::FUGt, a, b), + "ngt" => self.fcmp(Pred::FULe, a, b), + "nge" => self.fcmp(Pred::FULt, a, b), + "nlg" => self.fcmp(Pred::FUEq, a, b), + _ => return None, + }); + } let rel = |s: &mut Self, r: &str| -> Option { Some(match r { "lt" => s.fcmp(Pred::FOLt, a, b), diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index 60f4341917..9145a21d7e 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; -use super::bitstream::{signed, BitWriter}; +use super::bitstream::{signed, AbbrevOp, BitWriter}; mod opt; pub(super) mod split; @@ -58,6 +58,9 @@ enum ConstDef { Undef(Ty), Null(Ty), Aggregate(Ty, Vec), + /// Packed `i32` constant array (`CST_CODE_DATA = 22`), avoiding per-element `CST_CODE_INTEGER` + /// interning for large lookup tables (e.g. `compact.rs`). + DataI32(Ty, Vec), } #[derive(Clone)] @@ -468,6 +471,16 @@ impl Module { self.constant(ConstDef::Aggregate(ty, elems.to_vec())) } + /// Packed `[N x i32]` constant data array (`CST_CODE_DATA`), avoiding interning each element. + pub fn const_data_i32(&mut self, words: &[u32]) -> Value { + let i32 = self.i32(); + let at = self.array(words.len() as u64, i32); + if words.is_empty() { + return self.null(at); + } + self.constant(ConstDef::DataI32(at, words.to_vec())) + } + // ---- functions and globals /// Declares (or finds) a function by name. @@ -517,7 +530,12 @@ impl Module { self.ptr(t, 0) } Value::Const(c) => match &self.consts[c as usize] { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }, Value::Inst(i) => self.insts[i as usize].ty, } @@ -837,34 +855,59 @@ impl Module { // are dropped. Value numbering follows that order. let (order, pos) = self.block_layout(); - // Global variables nothing references (e.g. an exchange array the code never - // needed) are left out: the validator rejects unused internal declarations. - // Likewise declarations of functions no longer called (after `optimize`). + // Global variables, functions, and constants nothing references (after `optimize`) + // are left out: the validator rejects unused internal globals, and pruning dead + // constants shrinks both `BLOCK_CONSTANTS` and every relative operand ID in `FUNCTION`. let mut gused = vec![false; self.globals.len()]; let mut fused: Vec = self.funcs.iter().map(|f| f.defined).collect(); + let mut cused = vec![false; self.consts.len()]; { - let mut mark = |v: Value| match v { - Value::Global(g) => gused[g as usize] = true, + let mut work_g: Vec = Vec::new(); + let mut work_c: Vec = Vec::new(); + let mark = |v: Value, gused: &mut [bool], fused: &mut [bool], cused: &mut [bool], work_g: &mut Vec, work_c: &mut Vec| match v { + Value::Global(g) => { + let g = g as usize; + if !gused[g] { + gused[g] = true; + work_g.push(g); + } + } Value::Func(f) => fused[f as usize] = true, - _ => {} + Value::Const(c) => { + let c = c as usize; + if !cused[c] { + cused[c] = true; + work_c.push(c); + } + } + Value::Inst(_) => {} }; for &b in &order { for &i in &self.blocks[b] { let op = &self.insts[i as usize].op; if let Op::Call(f, _) = op { - mark(Value::Func(*f)); + mark(Value::Func(*f), &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c); } - op.for_each_operand(&mut mark); - } - } - for c in &self.consts { - if let ConstDef::Aggregate(_, e) = c { - e.iter().copied().for_each(&mut mark); + op.for_each_operand(|v| mark(v, &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c)); } } for m in &self.md { if let MdDef::Val(_, v) = m { - mark(*v); + mark(*v, &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c); + } + } + while !work_g.is_empty() || !work_c.is_empty() { + while let Some(g) = work_g.pop() { + if let Some(init) = self.globals[g].init { + mark(init, &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c); + } + } + while let Some(c) = work_c.pop() { + if let ConstDef::Aggregate(_, e) = &self.consts[c] { + for &v in e { + mark(v, &mut gused, &mut fused, &mut cused, &mut work_g, &mut work_c); + } + } } } } @@ -886,7 +929,15 @@ impl Module { } } let fmap = &fmap; - let n_consts = self.consts.len() as u64; + let mut cmap: Vec> = vec![None; self.consts.len()]; + let mut n_consts = 0u64; + for (c, used) in cused.iter().enumerate() { + if *used { + cmap[c] = Some(n_consts); + n_consts += 1; + } + } + let cmap = &cmap; let const_base = n_globals + n_funcs; let inst_base = const_base + n_consts; @@ -907,7 +958,7 @@ impl Module { match v { Value::Global(g) => gmap[g as usize].expect("use of a dropped global"), Value::Func(f) => n_globals + fmap[f as usize].expect("use of a dropped function"), - Value::Const(c) => const_base + c as u64, + Value::Const(c) => const_base + cmap[c as usize].expect("use of a dropped constant"), Value::Inst(i) => inst_ids[i as usize].unwrap_or_else(|| { self.fail(format!("use of a void instruction %{i}")); 0 @@ -962,19 +1013,34 @@ impl Module { } // Module-level constants. - if !self.consts.is_empty() { + if n_consts > 0 { + const ABBREV_CST_INT: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_INTEGER as u64), AbbrevOp::Vbr(6)]; + const ABBREV_CST_F32: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_FLOAT as u64), AbbrevOp::Fixed(32)]; + const ABBREV_CST_DATA: &[AbbrevOp] = &[AbbrevOp::Literal(CST_CODE_DATA as u64), AbbrevOp::ArrayFixed(32)]; w.enter_block(BLOCK_CONSTANTS); + let ab_int = w.define_abbrev(ABBREV_CST_INT); + let ab_f32 = w.define_abbrev(ABBREV_CST_F32); + let ab_data = w.define_abbrev(ABBREV_CST_DATA); let mut cur_ty = None; - for c in &self.consts { + for (ci, c) in self.consts.iter().enumerate() { + if !cused[ci] { + continue; + } let t = match c { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }; if cur_ty != Some(t) { w.record(CST_CODE_SETTYPE, &[t.0 as u64]); cur_ty = Some(t); } match c { - ConstDef::Int(_, v) => w.record(CST_CODE_INTEGER, &[signed(*v)]), + ConstDef::Int(_, v) => w.emit_abbrev(ab_int, ABBREV_CST_INT, &[signed(*v)]), + ConstDef::Float(_, bits) if *bits <= u32::MAX as u64 => w.emit_abbrev(ab_f32, ABBREV_CST_F32, &[*bits]), ConstDef::Float(_, bits) => w.record(CST_CODE_FLOAT, &[*bits]), ConstDef::Undef(_) => w.record(CST_CODE_UNDEF, &[]), ConstDef::Null(_) => w.record(CST_CODE_NULL, &[]), @@ -982,6 +1048,10 @@ impl Module { let ops: Vec = e.iter().map(|&v| abs(v)).collect(); w.record(CST_CODE_AGGREGATE, &ops) } + ConstDef::DataI32(_, words) => { + let ops: Vec = words.iter().map(|&x| x as u64).collect(); + w.emit_abbrev(ab_data, ABBREV_CST_DATA, &ops); + } } } w.end_block(); @@ -1022,15 +1092,16 @@ impl Module { } w.end_block(); - // The entry's body. - w.enter_block(BLOCK_FUNCTION); + // The entry's body (abbrev width 4 -> 12 user abbreviations for hot DXIL opcodes). + w.enter_block_with_width(BLOCK_FUNCTION, 4); + let ab = FuncAbbrevs::define(&mut w); w.record(FUNC_CODE_DECLAREBLOCKS, &[order.len() as u64]); let mut inst_id = inst_base; let mut operands = Vec::new(); for &b in &order { for k in 0..self.blocks[b].len() { let i = self.blocks[b][k] as usize; - self.write_inst(&mut w, i, inst_id, &abs, &pos, &mut operands); + self.write_inst(&mut w, &ab, i, inst_id, &abs, &pos, &mut operands); if !self.is_void(self.insts[i].ty) { inst_id += 1; } @@ -1184,6 +1255,7 @@ impl Module { fn write_inst( &self, w: &mut BitWriter, + ab: &FuncAbbrevs, i: usize, inst_id: u64, abs: &dyn Fn(Value) -> u64, @@ -1209,21 +1281,22 @@ impl Module { ops.clear(); match &self.insts[i].op { Op::Bin(op, a, b, flags) => { - ops.extend_from_slice(&[rel(*a), rel(*b), *op as u64]); - if *flags != 0 { - ops.push(*flags); + if *flags == 0 { + w.emit_abbrev(ab.binop, ABBREV_BINOP, &[rel(*a), rel(*b), *op as u64]); + } else { + ops.extend_from_slice(&[rel(*a), rel(*b), *op as u64, *flags]); + w.record(FUNC_CODE_INST_BINOP, ops); } - w.record(FUNC_CODE_INST_BINOP, ops) } - Op::Cast(op, v, t) => w.record(FUNC_CODE_INST_CAST, &[rel(*v), t.0 as u64, *op as u64]), - Op::Cmp(p, a, b) => w.record(FUNC_CODE_INST_CMP2, &[rel(*a), rel(*b), *p as u64]), - Op::Select(c, t, f) => w.record(FUNC_CODE_INST_VSELECT, &[rel(*t), rel(*f), rel(*c)]), - Op::Extract(a, idx) => w.record(FUNC_CODE_INST_EXTRACTVAL, &[rel(*a), *idx as u64]), + Op::Cast(op, v, t) => w.emit_abbrev(ab.cast, ABBREV_CAST, &[rel(*v), t.0 as u64, *op as u64]), + Op::Cmp(p, a, b) => w.emit_abbrev(ab.cmp2, ABBREV_CMP2, &[rel(*a), rel(*b), *p as u64]), + Op::Select(c, t, f) => w.emit_abbrev(ab.vselect, ABBREV_VSELECT, &[rel(*t), rel(*f), rel(*c)]), + Op::Extract(a, idx) => w.emit_abbrev(ab.extract, ABBREV_EXTRACT, &[rel(*a), *idx as u64]), Op::Call(f, args) => { let fd = &self.funcs[*f as usize]; - ops.extend_from_slice(&[0, 1 << 15, fd.ty.0 as u64, rel(Value::Func(*f))]); + ops.extend_from_slice(&[fd.ty.0 as u64, rel(Value::Func(*f))]); ops.extend(args.iter().map(|&a| rel(a))); - w.record(FUNC_CODE_INST_CALL, ops) + w.emit_abbrev(ab.call, ABBREV_CALL, ops); } Op::Phi(inc) => { ops.push(self.insts[i].ty.0 as u64); @@ -1232,22 +1305,30 @@ impl Module { ops.push(signed(inst_id as i64 - abs(v) as i64)); ops.push(bb(b)); } - w.record(FUNC_CODE_INST_PHI, ops) + w.emit_abbrev(ab.phi, ABBREV_PHI, ops); } Op::Load(p, align) => { let a = if *align == 0 { 0 } else { align.trailing_zeros() as u64 + 1 }; - w.record(FUNC_CODE_INST_LOAD, &[rel(*p), self.insts[i].ty.0 as u64, a, 0]) + if a == 3 { + w.emit_abbrev(ab.load, ABBREV_LOAD, &[rel(*p), self.insts[i].ty.0 as u64]); + } else { + w.record(FUNC_CODE_INST_LOAD, &[rel(*p), self.insts[i].ty.0 as u64, a, 0]); + } } Op::Store(p, v, align) => { let a = if *align == 0 { 0 } else { align.trailing_zeros() as u64 + 1 }; - w.record(FUNC_CODE_INST_STORE, &[rel(*p), rel(*v), a, 0]) + if a == 3 { + w.emit_abbrev(ab.store, ABBREV_STORE, &[rel(*p), rel(*v)]); + } else { + w.record(FUNC_CODE_INST_STORE, &[rel(*p), rel(*v), a, 0]); + } } Op::Gep(p, idx) => { let pt = self.value_ty(*p); let (src, _) = self.pointee_of(pt).unwrap_or((pt, 0)); - ops.extend_from_slice(&[1, src.0 as u64, rel(*p)]); + ops.extend_from_slice(&[src.0 as u64, rel(*p)]); ops.extend(idx.iter().map(|&v| rel(v))); - w.record(FUNC_CODE_INST_GEP, ops) + w.emit_abbrev(ab.gep, ABBREV_GEP, ops); } Op::AtomicRmw(op, p, v) => { // [ptr, val, op, vol, ordering, synchscope (crossthread = 1)] @@ -1263,8 +1344,8 @@ impl Module { let a = align.trailing_zeros() as u64 + 1; w.record(FUNC_CODE_INST_ALLOCA, &[t.0 as u64, i32t.0 as u64, abs(*n), a | 1 << 6]) } - Op::Br(b) => w.record(FUNC_CODE_INST_BR, &[bb(*b)]), - Op::CondBr(c, t, f) => w.record(FUNC_CODE_INST_BR, &[bb(*t), bb(*f), rel(*c)]), + Op::Br(b) => w.emit_abbrev(ab.br, ABBREV_BR, &[bb(*b)]), + Op::CondBr(c, t, f) => w.emit_abbrev(ab.condbr, ABBREV_CONDBR, &[bb(*t), bb(*f), rel(*c)]), Op::Switch(v, d, cases) => { ops.extend_from_slice(&[self.value_ty(*v).0 as u64, rel(*v), bb(*d)]); for &(c, b) in cases { @@ -1284,7 +1365,12 @@ impl Module { Value::Global(g) => self.globals[g as usize].ptr, Value::Func(f) => self.type_ids[&TypeDef::Ptr(self.funcs[f as usize].ty, 0)], Value::Const(c) => match &self.consts[c as usize] { - ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, + ConstDef::Int(t, _) + | ConstDef::Float(t, _) + | ConstDef::Undef(t) + | ConstDef::Null(t) + | ConstDef::Aggregate(t, _) + | ConstDef::DataI32(t, _) => *t, }, Value::Inst(i) => self.insts[i as usize].ty, } @@ -1343,6 +1429,7 @@ const CST_CODE_UNDEF: u32 = 3; const CST_CODE_INTEGER: u32 = 4; const CST_CODE_FLOAT: u32 = 6; const CST_CODE_AGGREGATE: u32 = 7; +const CST_CODE_DATA: u32 = 22; const METADATA_STRING: u32 = 1; const METADATA_VALUE: u32 = 2; @@ -1371,6 +1458,66 @@ const FUNC_CODE_INST_GEP: u32 = 43; const FUNC_CODE_INST_STORE: u32 = 44; const FUNC_CODE_INST_CMPXCHG: u32 = 46; +const ABBREV_BINOP: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BINOP as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(4)]; +const ABBREV_CAST: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_CAST as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(4)]; +const ABBREV_CMP2: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_CMP2 as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Fixed(6)]; +const ABBREV_VSELECT: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_VSELECT as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5), AbbrevOp::Vbr(5)]; +const ABBREV_EXTRACT: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_EXTRACTVAL as u64), AbbrevOp::Vbr(5), AbbrevOp::Vbr(4)]; +const ABBREV_LOAD: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_LOAD as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5), AbbrevOp::Literal(3), AbbrevOp::Literal(0)]; +const ABBREV_STORE: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_STORE as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5), AbbrevOp::Literal(3), AbbrevOp::Literal(0)]; +const ABBREV_BR: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BR as u64), AbbrevOp::Vbr(6)]; +const ABBREV_CONDBR: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_BR as u64), AbbrevOp::Vbr(6), AbbrevOp::Vbr(6), AbbrevOp::Vbr(5)]; +const ABBREV_CALL: &[AbbrevOp] = &[ + AbbrevOp::Literal(FUNC_CODE_INST_CALL as u64), + AbbrevOp::Literal(0), + AbbrevOp::Literal(1 << 15), + AbbrevOp::Vbr(5), + AbbrevOp::Vbr(6), + AbbrevOp::ArrayVbr(5), +]; +const ABBREV_PHI: &[AbbrevOp] = &[AbbrevOp::Literal(FUNC_CODE_INST_PHI as u64), AbbrevOp::Vbr(5), AbbrevOp::ArrayVbr(6)]; +const ABBREV_GEP: &[AbbrevOp] = &[ + AbbrevOp::Literal(FUNC_CODE_INST_GEP as u64), + AbbrevOp::Literal(1), + AbbrevOp::Vbr(5), + AbbrevOp::Vbr(5), + AbbrevOp::ArrayVbr(5), +]; + +struct FuncAbbrevs { + binop: u32, + cast: u32, + cmp2: u32, + vselect: u32, + extract: u32, + load: u32, + store: u32, + br: u32, + condbr: u32, + call: u32, + phi: u32, + gep: u32, +} + +impl FuncAbbrevs { + fn define(w: &mut BitWriter) -> Self { + Self { + binop: w.define_abbrev(ABBREV_BINOP), + cast: w.define_abbrev(ABBREV_CAST), + cmp2: w.define_abbrev(ABBREV_CMP2), + vselect: w.define_abbrev(ABBREV_VSELECT), + extract: w.define_abbrev(ABBREV_EXTRACT), + load: w.define_abbrev(ABBREV_LOAD), + store: w.define_abbrev(ABBREV_STORE), + br: w.define_abbrev(ABBREV_BR), + condbr: w.define_abbrev(ABBREV_CONDBR), + call: w.define_abbrev(ABBREV_CALL), + phi: w.define_abbrev(ABBREV_PHI), + gep: w.define_abbrev(ABBREV_GEP), + } + } +} + // ------------------------------------------------------- introspection /// What an instruction is, for analyses over the built function (e.g. the @@ -1517,6 +1664,23 @@ impl Module { _ => None, } } + + /// The `f32` value of a float constant (also unwraps `bitcast i32_const to float`). + pub fn const_f32(&self, v: Value) -> Option { + match v { + Value::Const(c) => match &self.consts[c as usize] { + ConstDef::Float(t, bits) if matches!(self.types[t.0 as usize], TypeDef::Float) => Some(f32::from_bits(*bits as u32)), + _ => None, + }, + Value::Inst(i) => match self.insts[i as usize].op { + Op::Cast(CastOp::BitCast, src, to) if matches!(self.types[to.0 as usize], TypeDef::Float) => { + self.const_u64(src).map(|b| f32::from_bits(b as u32)) + } + _ => None, + }, + _ => None, + } + } } impl Module { diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index a604fa757c..37e39f8160 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -99,7 +99,20 @@ impl Module { match op { Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) | Op::Gep(..) => Cse::Dom, Op::Load(p, _) if self.is_const_global_ptr(*p) => Cse::Dom, - Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => Cse::Dom, + Op::Call(f, _) if self.funcs[*f as usize].attrs == FnAttrs::ReadNone => { + let name = &self.funcs[*f as usize].name; + // AMD RDNA4 (`amdxc64.dll`) crashes on null deref if a raw `createHandleFromHeap` + // handle is shared across distinct `annotateHandle` resource kinds or across basic + // blocks, or if `annotateHandle` / `getDimensions` crosses basic blocks. + if name.starts_with("dx.op.createHandleFromHeap") { + Cse::No + } else if name.starts_with("dx.op.annotateHandle") || name.starts_with("dx.op.getDimensions") { + Cse::Block + } else { + Cse::Dom + } + } + Op::Call(f, _) if self.funcs[*f as usize].name.starts_with("dx.op.getDimensions") => Cse::Block, Op::Call(f, _) if self.wave_call(*f) && !self.funcs[*f as usize].name.starts_with("dx.op.waveIsFirstLane") => Cse::Block, _ => Cse::No, } @@ -523,286 +536,707 @@ impl Module { vec![HashMap::new(); self.blocks.len()] } - /// Cleans up the entry function (see the module docs of `opt`). Values - /// keep their identities; replaced ones simply lose their uses. - /// - /// `XCL_DXIL_NO_OPT=phi,cse,cfg,dce,merge` (any subset, or `all`) skips passes, for bisecting. - pub fn optimize(&mut self) { - let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); - let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); - let mut order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); - // malformed IR (a use before its definition or of a void result) is left for the - // writer to report, not cleaned away - if !self.uses_well_formed(&order) { - return; + fn is_hoistable_readnone_call(&self, f: u32, args: &[Value], in_entry: &[bool]) -> bool { + let fd = &self.funcs[f as usize]; + if fd.attrs != FnAttrs::ReadNone || fd.name.ends_with(".f64") { + return false; } - // unreachable blocks: emptied (the writer drops them) - let mut reach = vec![false; self.blocks.len()]; - for &b in &order { - reach[b as usize] = true; + // Never hoist `createHandleFromHeap`, `annotateHandle`, or `getDimensions` across blocks + // (AMD RDNA4 `amdxc64` requires heap handles / annotations / dimensions to stay block-local). + let ok_name = [ + "dx.op.groupId.", + "dx.op.threadId.", + "dx.op.threadIdInGroup.", + "dx.op.flattenedThreadIdInGroup.", + "dx.op.createHandleFromBinding", + ] + .iter() + .any(|p| fd.name.starts_with(p)); + if !ok_name { + return false; } - for (b, r) in reach.iter().enumerate() { - if !r { - self.blocks[b].clear(); - } + args.iter().all(|a| match *a { + Value::Const(_) => true, + Value::Inst(j) => in_entry.get(j as usize).copied().unwrap_or(false), + _ => false, + }) + } + + /// Hoists duplicate entry-available `ReadNone` intrinsics (such as `dx.op.groupId` in + /// compact switch arms, or `createHandleFromHeap` + `annotateHandle` pairs) into entry + /// block 0 so every block shares a single dominating definition. + fn hoist_entry_readnone(&mut self, order: &[u32], repl: &mut Vec>) -> bool { + if order.is_empty() || self.blocks[0].is_empty() { + return false; } - for &b in &order { - for k in 0..self.blocks[b as usize].len() { - let i = self.blocks[b as usize][k] as usize; - if let Op::Phi(inc) = &mut self.insts[i].op { - inc.retain(|p| reach[p.1 .0 as usize]); + let mut any_changed = false; + // Two passes: pass 0 hoists `createHandleFromHeap` / `groupId`, pass 1 hoists + // `annotateHandle` whose handle argument was just hoisted into entry block 0. + for _pass in 0..2 { + let mut in_entry = vec![false; self.insts.len()]; + for &i in &self.blocks[0] { + if repl[i as usize].is_none() { + in_entry[i as usize] = true; } } + let mut counts: HashMap<(u32, Vec), usize> = HashMap::new(); + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + if repl[i].is_some() { + continue; + } + let (f, raw_args) = match &self.insts[i].op { + Op::Call(f, args) => (*f, args.clone()), + _ => continue, + }; + let args: Vec = raw_args.into_iter().map(|a| resolve(repl, a)).collect(); + if self.is_hoistable_readnone_call(f, &args, &in_entry) { + *counts.entry((f, args)).or_insert(0) += 1; + } + } + } + let mut hoisted: HashMap<(u32, Vec), Value> = HashMap::new(); + // Reuse any call already in entry block 0 first. + for k in 0..self.blocks[0].len() { + let i = self.blocks[0][k] as usize; + if repl[i].is_some() { + continue; + } + let (f, raw_args) = match &self.insts[i].op { + Op::Call(f, args) => (*f, args.clone()), + _ => continue, + }; + let args: Vec = raw_args.into_iter().map(|a| resolve(repl, a)).collect(); + let key = (f, args); + if counts.get(&key).copied().unwrap_or(0) >= 2 { + hoisted.entry(key).or_insert(Value::Inst(i as u32)); + } + } + let mut changed = false; + let term = if self.blocks[0].last().is_some_and(|&t| { + matches!( + self.insts[t as usize].op, + Op::Br(_) | Op::CondBr(..) | Op::Switch(..) | Op::Ret | Op::Unreachable + ) + }) { + self.blocks[0].pop() + } else { + None + }; + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + if repl[i].is_some() { + continue; + } + let (f, raw_args, ty) = match &self.insts[i].op { + Op::Call(f, args) => (*f, args.clone(), self.insts[i].ty), + _ => continue, + }; + let args: Vec = raw_args.into_iter().map(|a| resolve(repl, a)).collect(); + if !self.is_hoistable_readnone_call(f, &args, &in_entry) { + continue; + } + let key = (f, args); + if counts.get(&key).copied().unwrap_or(0) < 2 { + continue; + } + let entry_val = *hoisted.entry(key.clone()).or_insert_with(|| { + let id = self.insts.len() as u32; + self.insts.push(super::InstDef { op: Op::Call(key.0, key.1), ty }); + self.def_block.push(Block(0)); + self.blocks[0].push(id); + repl.push(None); + Value::Inst(id) + }); + if entry_val != Value::Inst(i as u32) { + repl[i] = Some(entry_val); + changed = true; + } + } + } + if let Some(t) = term { + self.blocks[0].push(t); + } + if !changed { + break; + } + any_changed = true; } + any_changed + } - let mut repl: Vec> = vec![None; self.insts.len()]; - - // trivial phis (all incoming values the phi itself or one value), to a fixed point - if !skip("phi") { - self.simplify_phis(&order, &mut repl); - } - - // CSE along the dominator tree (preorder walk with a scoped table) - let idom = self.idoms(&order); - let mut kids: Vec> = vec![Vec::new(); self.blocks.len()]; - for &b in order.iter().skip(1) { - if let Some(d) = idom[b as usize] { - kids[d].push(b as usize); + /// Intra-block store-to-load forwarding and dead-store elimination for non-escaping scalar + /// `alloca` slots (primarily the register slots of `compact.rs`), plus removal of stores to + /// scalar allocas that have zero surviving loads anywhere in the function. + fn opt_local_allocas(&mut self, order: &[u32], repl: &mut [Option]) -> bool { + let mut scalar_allocas: Vec = vec![false; self.insts.len()]; + let mut any_alloca = false; + for &b in order { + for &i in &self.blocks[b as usize] { + let idx = i as usize; + if repl[idx].is_some() { + continue; + } + if let Op::Alloca(ty, n, _) = self.insts[idx].op { + if self.const_u64(n) == Some(1) + && !matches!( + self.types[ty.0 as usize], + super::TypeDef::Array(..) | super::TypeDef::Struct(..) | super::TypeDef::Int(64) | super::TypeDef::Double + ) + { + scalar_allocas[idx] = true; + any_alloca = true; + } + } } } - let mut table: HashMap<(Op, Ty), Value> = HashMap::new(); - // (block, undo log length) frames; undo log holds keys to remove / restore - let mut undo: Vec<((Op, Ty), Option)> = Vec::new(); - enum Step { - Enter(usize), - Leave(usize), + if !any_alloca { + return false; } - let mut stack = if skip("cse") { Vec::new() } else { vec![Step::Enter(0)] }; - let mut cse_replaced = false; - while let Some(step) = stack.pop() { - let b = match step { - Step::Leave(mark) => { - while undo.len() > mark { - let (k, old) = undo.pop().unwrap(); - match old { - Some(v) => table.insert(k, v), - None => table.remove(&k), - }; + // Disqualify any alloca whose address escapes (used anywhere except as ptr of Load/Store). + for &b in order { + for &i in &self.blocks[b as usize] { + let idx = i as usize; + if repl[idx].is_some() { + continue; + } + match &self.insts[idx].op { + Op::Load(p, _) => { + let _ = p; // pointer operand is valid + } + Op::Store(_p, v, _) => { + if let Value::Inst(j) = *v { + scalar_allocas[j as usize] = false; + } } + other => other.for_each_operand(|v| { + if let Value::Inst(j) = v { + scalar_allocas[j as usize] = false; + } + }), + } + } + } + if !scalar_allocas.iter().any(|&x| x) { + return false; + } + + let mut dead_store = vec![false; self.insts.len()]; + let mut loaded = vec![false; self.insts.len()]; + let mut changed = false; + + for &b in order { + let mut known: HashMap = HashMap::new(); + let mut last_store: HashMap = HashMap::new(); + let len = self.blocks[b as usize].len(); + for k in 0..len { + let i = self.blocks[b as usize][k] as usize; + if repl[i].is_some() { continue; } - Step::Enter(b) => b, - }; - stack.push(Step::Leave(undo.len())); - let mut local: HashMap<(Op, Ty), Value> = HashMap::new(); - for k in 0..self.blocks[b].len() { - let i = self.blocks[b][k] as usize; - let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); - op.map_operands(|v| resolve(&mut repl, v)); - if repl[i].is_none() { - if let Some(s) = self.simplify_op(&op, self.insts[i].ty) { - repl[i] = Some(s); - cse_replaced = true; - } else { - let kind = self.cse_kind(&op); - if kind != Cse::No { - let key = (op.clone(), self.insts[i].ty); - let t = if kind == Cse::Dom { &mut table } else { &mut local }; - if let Some(&v) = t.get(&key) { + match self.insts[i].op { + Op::Load(Value::Inst(a), _) if scalar_allocas[a as usize] => { + if let Some(&v) = known.get(&a) { + let v = resolve(repl, v); + if self.value_ty(v) == self.insts[i].ty { repl[i] = Some(v); - cse_replaced = true; - } else { - let old = t.insert(key.clone(), Value::Inst(i as u32)); - if kind == Cse::Dom { - undo.push((key, old)); - } + changed = true; + continue; } - } else if matches!(&op, Op::Call(f, _) if self.funcs[*f as usize].name == "dx.op.discard") { - // `dx.op.discard` demotes lanes mid-block, changing the active lane - // set for subsequent wave/quad intrinsics in the same basic block. - local.clear(); } + loaded[a as usize] = true; + last_store.remove(&a); + known.insert(a, Value::Inst(i as u32)); + } + Op::Store(Value::Inst(a), v, _) if scalar_allocas[a as usize] => { + let v = resolve(repl, v); + if known.get(&a).copied().map(|kv| resolve(repl, kv)) == Some(v) { + dead_store[i] = true; + changed = true; + continue; + } + if let Some(prev) = last_store.insert(a, i) { + dead_store[prev] = true; + changed = true; + } + known.insert(a, v); } + _ => {} } - self.insts[i].op = op; } - for &c in kids[b].iter().rev() { - stack.push(Step::Enter(c)); + } + + // Any scalar alloca with zero surviving loads anywhere in the function needs no stores. + for &b in order { + for &i in &self.blocks[b as usize] { + let idx = i as usize; + if !dead_store[idx] { + if let Op::Store(Value::Inst(a), _, _) = self.insts[idx].op { + if scalar_allocas[a as usize] && !loaded[a as usize] { + dead_store[idx] = true; + changed = true; + } + } + } } } - // second trivial-phi fixed point if CSE/simplification collapsed incoming values - if cse_replaced && !skip("phi") { - self.simplify_phis(&order, &mut repl); + + if changed { + for &b in order { + self.blocks[b as usize].retain(|&i| !dead_store[i as usize]); + } } - // phis may name values defined later (back edges): resolve before CFG folding so - // terminators see constants exposed by both CSE and the second trivial-phi pass. - for &b in &order { - for k in 0..self.blocks[b as usize].len() { - let i = self.blocks[b as usize][k] as usize; - self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); + changed + } + + /// Removes immediately redundant `dx.op.barrier` calls within a basic block when no + /// memory-visible side effect occurred since an equally-strong or stronger barrier. + fn elim_redundant_barriers(&mut self, order: &[u32]) -> bool { + let mut removed = false; + for &b in order { + let mut active_mask: Option = None; + let mut keep: Vec = Vec::with_capacity(self.blocks[b as usize].len()); + for &i in &self.blocks[b as usize] { + let op = &self.insts[i as usize].op; + match op { + Op::Call(f, args) if self.funcs[*f as usize].name == "dx.op.barrier" => { + let mode = args.get(1).and_then(|&v| self.const_u64(v)); + match (active_mask, mode) { + (Some(prev), Some(cur)) if (cur & !prev) == 0 => { + removed = true; + continue; + } + (Some(prev), Some(cur)) => active_mask = Some(prev | cur), + (None, Some(cur)) => active_mask = Some(cur), + _ => active_mask = None, + } + } + Op::Store(..) | Op::AtomicRmw(..) | Op::CmpXchg(..) => active_mask = None, + Op::Load(p, _) if !self.is_const_global_ptr(*p) => active_mask = None, + Op::Call(f, _) if self.funcs[*f as usize].attrs != FnAttrs::ReadNone => active_mask = None, + _ => {} + } + keep.push(i); + } + if keep.len() != self.blocks[b as usize].len() { + self.blocks[b as usize] = keep; } } - // CSE, trivial-phi folding, or dominating branches can prove a terminator constant. Fold - // it before DCE, then rebuild reachability and predecessor edges so unreachable blocks and - // obsolete PHI edges are pruned cleanly while preserving loop backedges. - let mut cfg_folded = false; - if !skip("cfg") { - let facts = self.branch_facts(&order); - for &b in &order { - let Some(&i) = self.blocks[b as usize].last() else { continue }; - let replacement = match self.insts[i as usize].op.clone() { - Op::CondBr(c, t, f) => match self.const_u64(c).or_else(|| facts[b as usize].get(&c).copied()) { - Some(0) => Some(Op::Br(f)), - Some(1) => Some(Op::Br(t)), - _ => None, - }, - Op::Switch(v, default, cases) => self.const_u64(v).or_else(|| facts[b as usize].get(&v).copied()).map(|needle| { - let target = cases.iter().find_map(|(case, target)| (self.const_u64(*case) == Some(needle)).then_some(*target)).unwrap_or(default); - Op::Br(target) - }), - _ => None, - }; - if let Some(op) = replacement { - self.insts[i as usize].op = op; - cfg_folded = true; + removed + } + + /// Recursively derives implied constant facts from a known boolean value `v == val` (bounded + /// depth so complex expressions stay strictly O(1)). + fn record_fact( + &self, + v: Value, + val: u64, + depth: u8, + facts: &mut HashMap, + undo: &mut Vec<(Value, Option)>, + ) { + if matches!(v, Value::Const(_)) { + return; + } + if facts.get(&v) == Some(&val) { + return; + } + let old = facts.insert(v, val); + undo.push((v, old)); + if depth == 0 { + return; + } + let Value::Inst(i) = v else { return }; + match self.insts[i as usize].op { + Op::Bin(BinOp::And, a, b, 0) if val == 1 && self.int_width(self.insts[i as usize].ty) == Some(1) => { + self.record_fact(a, 1, depth - 1, facts, undo); + self.record_fact(b, 1, depth - 1, facts, undo); + } + Op::Bin(BinOp::Or, a, b, 0) if val == 0 && self.int_width(self.insts[i as usize].ty) == Some(1) => { + self.record_fact(a, 0, depth - 1, facts, undo); + self.record_fact(b, 0, depth - 1, facts, undo); + } + Op::Bin(BinOp::Xor, a, b, 0) if self.int_width(self.insts[i as usize].ty) == Some(1) => { + if self.const_u64(b) == Some(1) { + self.record_fact(a, val ^ 1, depth - 1, facts, undo); + } else if self.const_u64(a) == Some(1) { + self.record_fact(b, val ^ 1, depth - 1, facts, undo); + } + } + Op::Cmp(Pred::Eq, a, b) if val == 1 => { + if self.int_width(self.value_ty(a)).is_some_and(|w| w <= 32) { + if let Some(k) = self.const_u64(b) { + self.record_fact(a, k, depth - 1, facts, undo); + } else if let Some(k) = self.const_u64(a) { + self.record_fact(b, k, depth - 1, facts, undo); + } } } + Op::Cmp(Pred::Ne, a, b) if val == 0 => { + if self.int_width(self.value_ty(a)).is_some_and(|w| w <= 32) { + if let Some(k) = self.const_u64(b) { + self.record_fact(a, k, depth - 1, facts, undo); + } else if let Some(k) = self.const_u64(a) { + self.record_fact(b, k, depth - 1, facts, undo); + } + } + } + _ => {} } - if cfg_folded { - order = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + } + + fn apply_facts_to_op(&mut self, op: &mut Op, facts: &HashMap) -> bool { + if facts.is_empty() { + return false; + } + let mut changed = false; + let lookup = |m: &mut Self, v: &mut Value, changed: &mut bool| { + if let Some(&k) = facts.get(v) { + let ty = m.value_ty(*v); + if m.int_width(ty).is_some_and(|w| w <= 32) { + *v = m.const_int(ty, k); + *changed = true; + } + } + }; + match op { + Op::Select(c, t, f) => { + lookup(self, c, &mut changed); + lookup(self, t, &mut changed); + lookup(self, f, &mut changed); + } + Op::CondBr(c, ..) => lookup(self, c, &mut changed), + Op::Switch(v, ..) => lookup(self, v, &mut changed), + Op::Bin(_, a, b, 0) | Op::Cmp(_, a, b) => { + lookup(self, a, &mut changed); + lookup(self, b, &mut changed); + } + Op::Cast(CastOp::ZExt | CastOp::SExt | CastOp::Trunc, v, _) => { + lookup(self, v, &mut changed); + } + _ => {} + } + changed + } + + /// Cleans up the entry function (see the module docs of `opt`). Values + /// keep their identities; replaced ones simply lose their uses. + /// + /// `XCL_DXIL_NO_OPT=phi,cse,cfg,dce,merge,alloca,facts,hoist,barrier` (any subset, or `all`) + /// skips passes, for bisecting. + pub fn optimize(&mut self) { + let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); + let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); + let order0: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + // malformed IR (a use before its definition or of a void result) is left for the + // writer to report, not cleaned away + if !self.uses_well_formed(&order0) { + return; + } + + const MAX_OPT_ITERS: usize = 4; + for _iter in 0..MAX_OPT_ITERS { + let mut iter_changed = false; + let mut order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let insts_before: usize = order.iter().map(|&b| self.blocks[b as usize].len()).sum(); + let blocks_before = order.len(); + + // unreachable blocks: emptied (the writer drops them) let mut reach = vec![false; self.blocks.len()]; - let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; for &b in &order { reach[b as usize] = true; - for succ in self.successors(b as usize) { - if let Some(p) = preds.get_mut(succ.0 as usize) { - if !p.contains(&b) { - p.push(b); - } - } - } } for (b, r) in reach.iter().enumerate() { - if !r { + if !r && !self.blocks[b].is_empty() { self.blocks[b].clear(); + iter_changed = true; } } for &b in &order { - for &i in &self.blocks[b as usize] { - let Op::Phi(inc) = &mut self.insts[i as usize].op else { break }; - inc.retain(|p| preds[b as usize].contains(&p.1 .0)); + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + if let Op::Phi(inc) = &mut self.insts[i].op { + inc.retain(|p| reach[p.1 .0 as usize]); + } } } + + let mut repl: Vec> = vec![None; self.insts.len()]; + + // trivial phis (all incoming values the phi itself or one value), to a fixed point if !skip("phi") { self.simplify_phis(&order, &mut repl); - for &b in &order { - for k in 0..self.blocks[b as usize].len() { - let i = self.blocks[b as usize][k] as usize; - self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); - } - } } - } - // dead instructions: live = side effects, terminators and their operands, transitively - let (i64t, f64t) = self.existing_i64_f64(); - let wide: Vec = i64t.into_iter().chain(f64t).collect(); - let mut live = vec![false; self.insts.len()]; - let mut work: Vec = Vec::new(); - for &b in &order { - for &i in &self.blocks[b as usize] { - if repl[i as usize].is_none() && (skip("dce") || !self.removable(&self.insts[i as usize].op, self.insts[i as usize].ty, &wide)) { - live[i as usize] = true; - work.push(i); + // intra-block scalar alloca store->load forwarding & dead-store elimination + if !skip("alloca") && self.opt_local_allocas(&order, &mut repl) { + iter_changed = true; + } + + // hoist repeated constant-argument ReadNone intrinsics (e.g. dx.op.groupId) to entry + if !skip("hoist") { + if self.hoist_entry_readnone(&order, &mut repl) { + repl.resize(self.insts.len(), None); + iter_changed = true; } } - } - while let Some(i) = work.pop() { - self.insts[i as usize].op.for_each_operand(|v| { - if let Value::Inst(j) = v { - if !live[j as usize] { - live[j as usize] = true; - work.push(j); + + // CSE + FACTS branch-condition propagation along the dominator tree + let idom = self.idoms(&order); + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in &order { + for s in self.successors(b as usize) { + if !preds[s.0 as usize].contains(&(b as usize)) { + preds[s.0 as usize].push(b as usize); } } - }); - } - for b in &mut self.blocks { - b.retain(|&i| live[i as usize]); - } - - if !skip("merge") && self.simplify_cfg() { - let order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); - let mut repl2: Vec> = vec![None; self.insts.len()]; - let mut phi_changed = false; - while !skip("phi") { - let mut changed = false; - for &b in &order { - for &i in &self.blocks[b as usize] { - let i = i as usize; - if repl2[i].is_some() { - continue; + } + let mut kids: Vec> = vec![Vec::new(); self.blocks.len()]; + for &b in order.iter().skip(1) { + if let Some(d) = idom[b as usize] { + kids[d].push(b as usize); + } + } + let use_facts = !skip("facts"); + let mut table: HashMap<(Op, Ty), Value> = HashMap::new(); + let mut undo: Vec<((Op, Ty), Option)> = Vec::new(); + let mut facts: HashMap = HashMap::new(); + let mut fact_undo: Vec<(Value, Option)> = Vec::new(); + enum Step { + Enter(usize), + Leave(usize, usize), + } + let mut stack = if skip("cse") { Vec::new() } else { vec![Step::Enter(0)] }; + let mut cse_replaced = false; + while let Some(step) = stack.pop() { + let b = match step { + Step::Leave(mark, fmark) => { + while undo.len() > mark { + let (k, old) = undo.pop().unwrap(); + match old { + Some(v) => table.insert(k, v), + None => table.remove(&k), + }; } - let Op::Phi(inc) = &self.insts[i].op else { break }; - let me = Value::Inst(i as u32); - let mut same: Option = None; - let mut trivial = true; - for &(v, _) in inc { - let v = resolve(&mut repl2, v); - if v == me || Some(v) == same { - continue; + while fact_undo.len() > fmark { + let (k, old) = fact_undo.pop().unwrap(); + match old { + Some(v) => facts.insert(k, v), + None => facts.remove(&k), + }; + } + continue; + } + Step::Enter(b) => b, + }; + stack.push(Step::Leave(undo.len(), fact_undo.len())); + // Push dominating branch facts when `b` has a single CFG predecessor (`idom[b]`). + if use_facts && preds[b].len() == 1 { + let p = preds[b][0]; + if let Some(&term_i) = self.blocks[p].last() { + match self.insts[term_i as usize].op.clone() { + Op::CondBr(c, t, f) if t != f => { + let c = resolve(&mut repl, c); + if t.0 as usize == b { + self.record_fact(c, 1, 4, &mut facts, &mut fact_undo); + } else if f.0 as usize == b { + self.record_fact(c, 0, 4, &mut facts, &mut fact_undo); + } } - if same.is_some() { - trivial = false; - break; + Op::Switch(v, default, cases) if default.0 as usize != b => { + let matching: Vec = cases.iter().filter(|(_, t)| t.0 as usize == b).map(|(c, _)| *c).collect(); + if let [case] = matching.as_slice() { + if let Some(k) = self.const_u64(*case) { + let v = resolve(&mut repl, v); + self.record_fact(v, k, 2, &mut facts, &mut fact_undo); + } + } } - same = Some(v); + _ => {} } - if let (true, Some(v)) = (trivial, same) { - repl2[i] = Some(v); - changed = true; - phi_changed = true; + } + } + let mut local: HashMap<(Op, Ty), Value> = HashMap::new(); + for k in 0..self.blocks[b].len() { + let i = self.blocks[b][k] as usize; + let mut op = std::mem::replace(&mut self.insts[i].op, Op::Ret); + op.map_operands(|v| resolve(&mut repl, v)); + if use_facts && !facts.is_empty() && self.apply_facts_to_op(&mut op, &facts) { + cse_replaced = true; + } + // Collapse chained EXEC-predicated VGPR selects under the same condition in place: + // `select(c, t, select(c, _, f2)) -> select(c, t, f2)` and + // `select(c, select(c, t2, _), f) -> select(c, t2, f)`. + if let Op::Select(c, ref mut t, ref mut f) = op { + if let Value::Inst(j) = *f { + if let Op::Select(c2, _, f2) = self.insts[j as usize].op { + if c2 == c { + *f = resolve(&mut repl, f2); + cse_replaced = true; + } + } + } + if let Value::Inst(j) = *t { + if let Op::Select(c2, t2, _) = self.insts[j as usize].op { + if c2 == c { + *t = resolve(&mut repl, t2); + cse_replaced = true; + } + } } } + if repl[i].is_none() { + if let Some(s) = self.simplify_op(&op, self.insts[i].ty) { + repl[i] = Some(s); + cse_replaced = true; + } else { + let kind = self.cse_kind(&op); + if kind != Cse::No { + let key = (op.clone(), self.insts[i].ty); + let t = if kind == Cse::Dom { &mut table } else { &mut local }; + if let Some(&v) = t.get(&key) { + repl[i] = Some(v); + cse_replaced = true; + } else { + let old = t.insert(key.clone(), Value::Inst(i as u32)); + if kind == Cse::Dom { + undo.push((key, old)); + } + } + } else if matches!(&op, Op::Call(f, _) if self.funcs[*f as usize].name == "dx.op.discard") { + // `dx.op.discard` demotes lanes mid-block, changing the active lane + // set for subsequent wave/quad intrinsics in the same basic block. + local.clear(); + } + } + } + self.insts[i].op = op; } - if !changed { - break; + for &c in kids[b].iter().rev() { + stack.push(Step::Enter(c)); } } - if phi_changed { + if cse_replaced { + iter_changed = true; + } + // second trivial-phi fixed point if CSE/simplification collapsed incoming values + if cse_replaced && !skip("phi") { + self.simplify_phis(&order, &mut repl); + } + // phis may name values defined later (back edges): resolve before CFG folding so + // terminators see constants exposed by both CSE and the second trivial-phi pass. + for &b in &order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); + } + } + // CSE, trivial-phi folding, or dominating branches can prove a terminator constant. Fold + // it before DCE, then rebuild reachability and predecessor edges so unreachable blocks and + // obsolete PHI edges are pruned cleanly while preserving loop backedges. + let mut cfg_folded = false; + if !skip("cfg") { + let bfacts = self.branch_facts(&order); for &b in &order { - for k in 0..self.blocks[b as usize].len() { - let i = self.blocks[b as usize][k] as usize; - self.insts[i].op.map_operands(|v| resolve(&mut repl2, v)); + let Some(&i) = self.blocks[b as usize].last() else { continue }; + let replacement = match self.insts[i as usize].op.clone() { + Op::CondBr(c, t, f) => match self.const_u64(c).or_else(|| bfacts[b as usize].get(&c).copied()) { + Some(0) => Some(Op::Br(f)), + Some(1) => Some(Op::Br(t)), + _ => None, + }, + Op::Switch(v, default, cases) => self.const_u64(v).or_else(|| bfacts[b as usize].get(&v).copied()).map(|needle| { + let target = cases.iter().find_map(|(case, target)| (self.const_u64(*case) == Some(needle)).then_some(*target)).unwrap_or(default); + Op::Br(target) + }), + _ => None, + }; + if let Some(op) = replacement { + self.insts[i as usize].op = op; + cfg_folded = true; + iter_changed = true; } } } - if !skip("dce") { - live.fill(false); - work.clear(); + if cfg_folded { + order = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let mut reach = vec![false; self.blocks.len()]; + let mut preds: Vec> = vec![Vec::new(); self.blocks.len()]; for &b in &order { - for &i in &self.blocks[b as usize] { - if repl2[i as usize].is_none() && !self.removable(&self.insts[i as usize].op, self.insts[i as usize].ty, &wide) { - live[i as usize] = true; - work.push(i); + reach[b as usize] = true; + for succ in self.successors(b as usize) { + if let Some(p) = preds.get_mut(succ.0 as usize) { + if !p.contains(&b) { + p.push(b); + } } } } - while let Some(i) = work.pop() { - self.insts[i as usize].op.for_each_operand(|v| { - if let Value::Inst(j) = v { - if !live[j as usize] { - live[j as usize] = true; - work.push(j); - } + for (b, r) in reach.iter().enumerate() { + if !r { + self.blocks[b].clear(); + } + } + for &b in &order { + for &i in &self.blocks[b as usize] { + let Op::Phi(inc) = &mut self.insts[i as usize].op else { break }; + inc.retain(|p| preds[b as usize].contains(&p.1 .0)); + } + } + if !skip("phi") { + self.simplify_phis(&order, &mut repl); + for &b in &order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + self.insts[i].op.map_operands(|v| resolve(&mut repl, v)); } - }); + } } - for b in &mut self.blocks { - b.retain(|&i| live[i as usize]); + } + + if !skip("barrier") && self.elim_redundant_barriers(&order) { + iter_changed = true; + } + + // dead instructions: live = side effects, terminators and their operands, transitively + let (i64t, f64t) = self.existing_i64_f64(); + let wide: Vec = i64t.into_iter().chain(f64t).collect(); + let mut live = vec![false; self.insts.len()]; + let mut work: Vec = Vec::new(); + for &b in &order { + for &i in &self.blocks[b as usize] { + if repl[i as usize].is_none() && (skip("dce") || !self.removable(&self.insts[i as usize].op, self.insts[i as usize].ty, &wide)) { + live[i as usize] = true; + work.push(i); + } } } - debug_assert!(self.uses_well_formed(&order)); + while let Some(i) = work.pop() { + self.insts[i as usize].op.for_each_operand(|v| { + if let Value::Inst(j) = v { + if !live[j as usize] { + live[j as usize] = true; + work.push(j); + } + } + }); + } + for b in &mut self.blocks { + b.retain(|&i| live[i as usize]); + } + + if !skip("merge") && self.simplify_cfg() { + iter_changed = true; + } + + let order_after: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + let insts_after: usize = order_after.iter().map(|&b| self.blocks[b as usize].len()).sum(); + debug_assert!(self.uses_well_formed(&order_after)); + if !iter_changed || (insts_after == insts_before && order_after.len() == blocks_before) { + break; + } } } @@ -1682,4 +2116,103 @@ mod tests { assert!(!s.features.contains(&Feature::Int64Ops), "pruned i64 branch must clear Int64Ops"); assert!(!s.features.contains(&Feature::ResourceHeapIndexing), "pruned heap handle must clear ResourceHeapIndexing"); } + + #[test] + fn local_alloca_store_load_forwarding_and_dse() { + let mut m = Module::new(); + m.define_entry("main"); + let i32 = m.i32(); + let slot = m.alloca(i32, 4); + let out = m.global("out", i32, 3, None, false, 4); + let c1 = m.i32c(11); + let c2 = m.i32c(22); + m.store(slot, c1, 4); + let v1 = m.load(slot, 4); + m.store(slot, c2, 4); + let v2 = m.load(slot, 4); + let sum = m.bin(BinOp::Add, v1, v2); + m.store(out, sum, 4); + m.ret(); + + m.optimize(); + + let ops: Vec<&Op> = m.blocks[0].iter().map(|&i| &m.insts[i as usize].op).collect(); + assert!(!ops.iter().any(|op| matches!(op, Op::Alloca(..))), "scalar alloca must be eliminated: {ops:?}"); + assert!(!ops.iter().any(|op| matches!(op, Op::Load(..))), "forwarded loads must be removed: {ops:?}"); + assert!( + ops.iter().any(|op| matches!(op, Op::Store(p, v, _) if *p == out && m.const_u64(*v) == Some(33))), + "store must fold forwarded 11 + 22 == 33: {ops:?}" + ); + } + + #[test] + fn hoist_entry_readnone_and_keep_heap_handles_unshared() { + use crate::gpu::dxil::container::Stage; + use crate::gpu::dxil::shader::Shader; + let mut s = Shader::new(Stage::Compute, (6, 6)); + let i32 = s.m.i32(); + let cond_ptr = s.m.global("cond", i32, 3, None, false, 4); + let out = s.m.global("out", i32, 3, None, false, 4); + let cv = s.m.load(cond_ptr, 4); + let zero = s.m.i32c(0); + let cond = s.m.cmp(Pred::Ne, cv, zero); + let b1 = s.m.new_block(); + let b2 = s.m.new_block(); + let join = s.m.new_block(); + s.m.cond_br(cond, b1, b2); + + s.m.set_block(b1); + let g1 = s.group_id(0); + let h1 = s.heap_raw_buffer_uav(zero, false); + let r1 = s.raw_load(h1, zero, 1)[0]; + let v1 = s.m.bin(BinOp::Add, g1, r1); + s.m.br(join); + + s.m.set_block(b2); + let g2 = s.group_id(0); + let h2 = s.heap_raw_buffer_uav(zero, false); + let r2 = s.raw_load(h2, zero, 1)[0]; + let v2 = s.m.bin(BinOp::Add, g2, r2); + s.m.br(join); + + s.m.set_block(join); + let p = s.m.phi(i32); + s.m.add_incoming(p, v1, b1); + s.m.add_incoming(p, v2, b2); + s.m.store(out, p, 4); + s.m.ret(); + + s.m.optimize(); + + let count_calls = |prefix: &str| -> usize { + s.m.blocks + .iter() + .flatten() + .filter(|&&i| matches!(s.m.insts[i as usize].op, Op::Call(f, _) if s.m.funcs[f as usize].name.starts_with(prefix))) + .count() + }; + assert_eq!(count_calls("dx.op.groupId."), 1, "groupId must hoist to entry block"); + assert_eq!(count_calls("dx.op.createHandleFromHeap"), 2, "createHandleFromHeap must stay unshared across blocks for RDNA4"); + assert_eq!(count_calls("dx.op.annotateHandle"), 2, "annotateHandle must stay block-local for RDNA4"); + } + + #[test] + fn redundant_barriers_eliminated_within_block() { + use crate::gpu::dxil::container::Stage; + use crate::gpu::dxil::ops::barrier; + use crate::gpu::dxil::shader::Shader; + let mut s = Shader::new(Stage::Compute, (6, 6)); + s.barrier(barrier::ALL_SYNC); + s.barrier(barrier::GROUP_SYNC); + s.barrier(barrier::ALL_SYNC); + s.m.ret(); + + s.m.optimize(); + + let barriers = s.m.blocks[0] + .iter() + .filter(|&&i| matches!(s.m.insts[i as usize].op, Op::Call(f, _) if s.m.funcs[f as usize].name == "dx.op.barrier")) + .count(); + assert_eq!(barriers, 1, "adjacent covered barriers must collapse to one"); + } } diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 26cb82daea..89718e8ad5 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -1106,6 +1106,8 @@ mod tests { let taken = lw.cmp(Pred::ULt, tid, width); lw.s.m.cond_br(taken, next, alt); lw.s.m.set_block(alt); + let alt_val = lw.addc(val, 1); + lw.s.raw_store(mem, offset, &[alt_val]); lw.s.m.br(next); lw.s.m.set_block(next); } diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index 4871311334..0fcaa1bda9 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -6,6 +6,14 @@ use super::lower::Lw; use super::module::{BinOp, Pred, Value}; use super::ops_core::op; +/// Native RDNA float lowering (`XCL_RDNA_FLOAT`, default on, `=0` disables): emits single-op +/// `dx.op.unary(Frc)` for `v_fract_f32` and eliminates redundant `== 0` checks in `mul_legacy` / +/// `fma_legacy` whenever an operand is a known finite non-zero (or zero) constant. +pub fn rdna_float_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_RDNA_FLOAT").map_or(true, |v| v.trim() != "0")) +} + impl Lw { /// `cvt_u32`: NaN / ≤ 0 → 0, ≥ 2^32 → 0xFFFFFFFF. pub fn cvt_u32(&mut self, f: Value) -> Value { @@ -69,8 +77,12 @@ impl Lw { let one = self.u(c); self.sub(h, one) } + /// `fract_f`: x - floor(x), below 1.0. pub fn fract_f(&mut self, x: Value) -> Value { + if rdna_float_enabled() { + return self.un(op::FRC, x); + } let fl = self.un(op::ROUND_NI, x); let r = self.fsub(x, fl); let one = self.fc(1.0); @@ -219,6 +231,16 @@ impl Lw { } /// `mul_legacy`: 0 · anything = 0. pub fn mul_legacy(&mut self, a: Value, b: Value) -> Value { + if rdna_float_enabled() { + let ca = self.s.m.const_f32(a); + let cb = self.s.m.const_f32(b); + if ca == Some(0.0) || cb == Some(0.0) { + return self.fc(0.0); + } + if ca.is_some_and(|x| x.is_finite() && x != 0.0) || cb.is_some_and(|x| x.is_finite() && x != 0.0) { + return self.fmul(a, b); + } + } let z = self.fc(0.0); let az = self.fcmp(Pred::FOEq, a, z); let bz = self.fcmp(Pred::FOEq, b, z); @@ -234,6 +256,16 @@ impl Lw { } /// `fma_legacy`: (a == 0 || b == 0) ? c : mad(a, b, c). pub fn fma_legacy(&mut self, a: Value, b: Value, c: Value) -> Value { + if rdna_float_enabled() { + let ca = self.s.m.const_f32(a); + let cb = self.s.m.const_f32(b); + if ca == Some(0.0) || cb == Some(0.0) { + return c; + } + if ca.is_some_and(|x| x.is_finite() && x != 0.0) || cb.is_some_and(|x| x.is_finite() && x != 0.0) { + return self.fmad(a, b, c); + } + } let z = self.fc(0.0); let az = self.fcmp(Pred::FOEq, a, z); let bz = self.fcmp(Pred::FOEq, b, z); diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs index 1ae5c75a4e..747afa1784 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -396,7 +396,7 @@ fn heap_windows_graphics_stages_validate() { ps_code.extend(e("S_ENDPGM", "ENC_SOPP", &[])); let vs = VsInterface { inputs: vec![], outputs: vec![sig("SV_Position", 1, 0)], attr_base: 4, params: None }; - let ps = PsInterface { inputs: vec![sig("SV_Position", 1, 0)], outputs: vec![sig("SV_Target", 64, 0)], input_ena: 0, attrs: None }; + let ps = PsInterface { inputs: vec![sig("SV_Position", 1, 0)], outputs: vec![sig("SV_Target", 64, 0)], input_ena: 0, attrs: None, early_depth: false }; let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 3, max_primitives: 1 }; let has_dxc = super::dxc::location().is_ok(); diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 6164cca0bf..72bf5f3058 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -106,13 +106,11 @@ pub fn in_switch_form(f: impl FnOnce() -> R) -> R { /// Whether translated shaders reach the memory windows through the shared descriptor heap /// (`Options::heap_windows`; descriptors `MEM_HEAP_BASE`..=`MEM_HEAP_NULL` made by `console_heap::set_window_views`) -/// instead of a `switch` over root UAVs. Opt-in: on with `XCL_HEAP_WINDOWS=1`, unless the views -/// could not be made (no shared heap: then the switch, as before). Off by default: two NVIDIA -/// setups failed with it (the driver's compiler ending the process; a device removal when the -/// views are made on an 8 GB card) that other machines do not show. +/// instead of a `switch` over root UAVs. Default ON (`XCL_HEAP_WINDOWS=0` to fall back to the +/// 4-arm switch form), unless the views could not be made (no shared heap: then the switch). pub fn heap_windows() -> bool { static ENV: OnceLock = OnceLock::new(); - *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() + *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").map_or(true, |v| v.trim() != "0")) && !crate::hle::d3d12x::console_heap::window_views_failed() } /// `XCL_HEAP_FLAT` (default on with heap windows; `=0` to disable): the direct DXIL translator From 61121fe4d2fc2bc41f40cc94d1f4c3f117108e07 Mon Sep 17 00:00:00 2001 From: razormontana <60733278+razormontana@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:58:59 +0100 Subject: [PATCH 152/258] DirectStorage: wake waiters from ordered completion events (#1833) Implement the X1 event marker at slot 12. A queue retains a duplicate handle until prior requests have retired, then signals or discards it with the rest of its ordered notifications. Both schedulers pass the real-vtable completion tests. The baseline slot times out on the event wait. Assisted-by: Codex (GPT-6.2 Sol) --- README.md | 2 +- crates/xcl/src/hle/dstorage.rs | 30 +++++- crates/xcl/src/hle/dstorage/parallel_tests.rs | 102 +++++++++++++++++- 3 files changed, 126 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 786f6bfc3d..8413f755c0 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif | **kernelx** | ✅ | title memory (budget from MicrosoftGame.Config, physical pages), threads on the PC's processors, modules, OS / console info | unit + end-to-end tests | | **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows) | GPU tests: loads, stores and atomics across windows | | **File system** | ✅ | console paths (`GAME:`, `G:`, `D:` …) → the game folder; writes go to an overlay, the game folder is never modified; the console's drives: `S:\` (persistent local storage) and `T:\` (temp) in the title's data folder; free disk space answered for console paths | end-to-end: the test title's folder stays byte-identical; PLS and free space through the real call path | -| **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, zlib, and BCPack – the console's texture compression – for BC1, BC3, BC4, BC5, BC6H and BC7 (BC2 and the hardware swizzle are refused) | unit tests on synthetic streams; retail BCPack chunks of all six modes byte-identical with a reference decoder (`XCL_SAMPLE_BCPACK`) | +| **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, queued event notifications, zlib, and BCPack – the console's texture compression – for BC1, BC3, BC4, BC5, BC6H and BC7 (BC2 and the hardware swizzle are refused) | unit tests on synthetic streams; retail BCPack chunks of all six modes byte-identical with a reference decoder (`XCL_SAMPLE_BCPACK`) | diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index b9aab9ed6c..92061b4f18 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -18,7 +18,8 @@ //! * queue: QueryInterface, AddRef, Release, EnqueueRequest, EnqueueStatus(array, index), //! EnqueueSignal(fence, value), Submit, CancelRequestsWithTag(mask, value), Close, //! GetErrorEvent, RetrieveErrorRecord (0x290 bytes), Query (0x1C: the desc, then empty -//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then 6 more, +//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then the X1 +//! EnqueueSetEvent(handle) method and 5 more, //! * file: QueryInterface, AddRef, Release, Close, GetHandle, 2 unknown, GetId, then 4 more; //! status array: QueryInterface, AddRef, Release, IsComplete(index), GetHResult(index), //! then 5 more. @@ -26,8 +27,9 @@ //! Each queue has a worker thread: submitted requests run in order (file reads through the //! VFS like the title's own, memory copies, zlib, BCPack where `hle::bcpack` rebuilds the //! blocks of the mode), a status entry gets the first failure of the requests since the -//! previous one, a signal sets the fence from the CPU. Methods not listed are logged and -//! answer E_NOTIMPL; BCPack BC2 and modes above 7, and the hardware swizzle, are refused. +//! previous one, a signal sets the fence from the CPU, and an event signals a Win32 waiter. +//! Unlisted methods log and answer E_NOTIMPL. BCPack BC2, modes above 7, and the hardware +//! swizzle are refused. #![allow(non_snake_case)] @@ -36,7 +38,7 @@ mod parallel; use std::ffi::c_void; use std::os::windows::fs::FileExt; -use std::os::windows::io::AsRawHandle; +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; @@ -45,7 +47,7 @@ use serde::{Deserialize, Serialize}; use windows_sys::core::GUID; use windows_sys::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE}; use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; -use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent}; +use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent, EVENT_MODIFY_STATE}; use crate::util::{HRESULT, S_OK}; @@ -1035,6 +1037,7 @@ enum Entry { Status(Arc, u32), /// a fence (one reference held) and the value it gets Signal(FenceRef, u64), + SetEvent(OwnedHandle), #[cfg(test)] /// Test-only barrier to hold the worker deterministically while testing submitted-batch cancellation. Gate(Arc), @@ -1198,6 +1201,9 @@ impl QueueInner { Entry::Signal(fence, value) => unsafe { fence.signal(value); }, + Entry::SetEvent(event) => unsafe { + SetEvent(event.as_raw_handle()); + }, #[cfg(test)] Entry::Gate(b) => { b.wait(); @@ -1285,6 +1291,7 @@ fn queue_vtbl() -> &'static [usize] { queue_get_error_event as usize, queue_retrieve_error_record as usize, queue_query as usize, + queue_enqueue_set_event as usize, // IDStorageQueueX1 ], 18, ) @@ -1450,6 +1457,19 @@ unsafe extern "system" fn queue_enqueue_signal(p: *mut c_void, fence: *mut c_voi q.enqueue(Entry::Signal(FenceRef(fence as usize), value)); } +unsafe extern "system" fn queue_enqueue_set_event(p: *mut c_void, event: HANDLE) { + let q = queue(p); + if q.closed.load(Ordering::Acquire) || event.is_null() { + return; + } + // Retain a separate handle until the marker reaches the worker or is discarded. + let mut duplicate = std::ptr::null_mut(); + let me = GetCurrentProcess(); + if DuplicateHandle(me, event, me, &mut duplicate, EVENT_MODIFY_STATE, 0, 0) != 0 { + q.enqueue(Entry::SetEvent(OwnedHandle::from_raw_handle(duplicate))); + } +} + unsafe extern "system" fn queue_submit(p: *mut c_void) { let q = queue(p); if !q.closed.load(Ordering::Acquire) { diff --git a/crates/xcl/src/hle/dstorage/parallel_tests.rs b/crates/xcl/src/hle/dstorage/parallel_tests.rs index 5d5214e4fb..23632eb1eb 100644 --- a/crates/xcl/src/hle/dstorage/parallel_tests.rs +++ b/crates/xcl/src/hle/dstorage/parallel_tests.rs @@ -2,11 +2,14 @@ use super::super::*; use super::*; use std::io::Write; use std::os::windows::ffi::OsStrExt; +use std::os::windows::io::{FromRawHandle, OwnedHandle}; use std::panic::{self, AssertUnwindSafe}; use std::path::PathBuf; use std::ptr::null_mut; use std::thread; use std::time::{Duration, Instant}; +use windows_sys::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}; +use windows_sys::Win32::System::Threading::WaitForSingleObject; const TIMEOUT: Duration = Duration::from_secs(5); const TEST_BUDGET: usize = 1024 * 1024; @@ -109,11 +112,15 @@ struct TestQueue(*mut c_void); impl TestQueue { fn new(pool: Option>, hook: Option) -> Self { + Self::with_desc(64, &IID_QUEUE, pool, hook) + } + + fn with_desc(capacity: u16, iid: &GUID, pool: Option>, hook: Option) -> Self { let mut desc = [0; 0x18]; - desc[8..10].copy_from_slice(&64u16.to_le_bytes()); + desc[8..10].copy_from_slice(&capacity.to_le_bytes()); let mut raw = null_mut(); assert_eq!( - unsafe { factory_create_queue(null_mut(), desc.as_ptr(), &IID_QUEUE, &mut raw) }, + unsafe { factory_create_queue(null_mut(), desc.as_ptr(), iid, &mut raw) }, S_OK ); let queue = Self(raw); @@ -137,6 +144,14 @@ impl TestQueue { unsafe { queue_enqueue_status(self.0, status.0, slot) }; } + fn enqueue_set_event(&self, event: &OwnedHandle) { + unsafe { + let vtable = *(self.0 as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, HANDLE) = std::mem::transmute(*vtable.add(12)); + enqueue(self.0, event.as_raw_handle()); + } + } + fn submit(&self) { unsafe { queue_submit(self.0) }; } @@ -262,6 +277,89 @@ fn await_later_preparation(events: &mpsc::Receiver) { } } +fn completion_event() -> OwnedHandle { + let event = unsafe { CreateEventW(null_mut(), 1, 0, null_mut()) }; + assert!(!event.is_null()); + unsafe { OwnedHandle::from_raw_handle(event) } +} + +#[test] +fn completion_event_auto_submits_a_half_full_sequential_queue() { + with_deadline(|| { + let payload = vec![0x7b; 48 * 1024]; + let file = TestFile::compressed(&[&payload]); + let mut output = vec![0x5d; payload.len()]; + let queue = TestQueue::with_desc(6, &IID_QUEUE_X1, None, None); + let status = TestStatus::new(1); + let event = completion_event(); + unsafe { queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1)) }; + queue.status(&status, 0); + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT); + queue.enqueue_set_event(&event); + + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 2_000) }, WAIT_OBJECT_0); + assert_eq!(status.result(0), S_OK); + assert_eq!(output, payload); + }); +} + +#[test] +fn completion_event_waits_for_parallel_retirement_and_keeps_its_handle() { + with_deadline(|| { + let payload = vec![0x4d; 48 * 1024]; + let file = TestFile::compressed(&[&payload]); + let mut output = vec![0; payload.len()]; + let mut failed = vec![0x72; payload.len()]; + let pool = test_pool(2, TEST_BUDGET); + let (gate, milestones, release) = gated_hook(TestEvent::BeforeDecode(1)); + let last_retired = Arc::new(AtomicU64::new(0)); + let retired = Arc::clone(&last_retired); + let hook = Arc::new(move |event| { + if let TestEvent::Retired(seq) = event { + retired.store(seq, Ordering::Release); + } + gate(event); + }); + let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, Some(pool), Some(hook)); + let status = TestStatus::new(1); + let event = completion_event(); + let observer = event.try_clone().unwrap(); + + let mut short = file.request(0, failed.as_mut_ptr() as usize, 2); + short[0x30..0x34].copy_from_slice(&(file.chunks[0].1 + 1).to_le_bytes()); + unsafe { + queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1)); + queue.enqueue(&short); + } + queue.enqueue_set_event(&event); + queue.status(&status, 0); + queue.submit(); + + assert_eq!(receive(&milestones), TestEvent::BeforeDecode(1)); + let early_wait = unsafe { WaitForSingleObject(observer.as_raw_handle(), 0) }; + drop(event); + release.send(()).unwrap(); + assert_eq!(early_wait, WAIT_TIMEOUT); + assert_eq!(unsafe { WaitForSingleObject(observer.as_raw_handle(), 2_000) }, WAIT_OBJECT_0); + assert_eq!(last_retired.load(Ordering::Acquire), 2); + assert_eq!(status.wait(0), E_END_OF_FILE); + assert_eq!(output, payload); + assert!(failed.iter().all(|&byte| byte == 0x72)); + }); +} + +#[test] +fn completion_event_close_discards_the_pending_marker() { + let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, None, None); + let event = completion_event(); + queue.enqueue_set_event(&event); + assert_eq!(queue.inner().pending.lock().unwrap().entries.len(), 1); + unsafe { queue_close(queue.0) }; + + assert!(queue.inner().pending.lock().unwrap().entries.is_empty()); + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT); +} + #[test] fn parallel_out_of_order_completion_retires_fifo() { with_deadline(|| { From 6e9787ce95863cf7788408bd35f686fc502b306b Mon Sep 17 00:00:00 2001 From: Kalmarv <59708937+Kalmarv@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:05:13 -0500 Subject: [PATCH 153/258] Recompiler: direct PS compares skip the per-quad mask where no helper bit is read Since #2083 every pixel-shader compare on the direct route rebuilds its quad's four bits from quad reads of its operands and four WaveActiveBallot passes. On 610 retail PS that makes the DXIL 1.42x larger than before #2083; the driver time grew with it (+28 % to +81 % on an RTX 4060, measured in #2083). recomp/ps_masks.rs picks the cheapest form a compare's mask allows: the lane's own bit when the mask is never read whole, WaveActiveBallot | own bit (HLSL ballot_px_local) when it is read whole but nothing reads another lane's helper bit, cond ? EXEC : 0 for scalar operands. In the ballot | own form every lane's copy of the mask has the live lanes' bits and its own right, so EXEC predication, v_cndmask and carry-ins stay exact in helper lanes and so do the values derivatives read later. A forward taint analysis refuses it where a helper bit of another lane is read: a non-bitwise SALU, SCC / VCCZ, a scalar operand, DPP / ds_swizzle / bpermute / permlane / readfirstlane while EXEC carries it, or values a branch on such an EXEC lets differ between lanes. A subset of the entry EXEC (a kill's live-pixel mask) has no helper bits and stays exact. Kept compares OR in their own bit. 610 PS: 43 % own bit, 31 % ballot | own, 4 % cond ? EXEC : 0, 23 % kept; DXIL x0.784 (x1.109 of before #2083), all validate. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/compact.rs | 1 + crates/xcl/src/gpu/dxil/kernel.rs | 6 +- crates/xcl/src/gpu/dxil/lanes.rs | 33 +- crates/xcl/src/gpu/dxil/lower.rs | 2 + crates/xcl/src/gpu/dxil/lower_valu.rs | 33 +- crates/xcl/src/gpu/recomp/mod.rs | 1 + crates/xcl/src/gpu/recomp/ps_masks.rs | 539 ++++++++++++++++++++++++++ 7 files changed, 610 insertions(+), 5 deletions(-) create mode 100644 crates/xcl/src/gpu/recomp/ps_masks.rs diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 91f8ebbd28..63ae012587 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -525,6 +525,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { let to = crate::gpu::rdna2::sgpr_uses(d).1.into_iter().chain([106]).chain(sdwa); key.extend(to.filter(|&r| r < 126).map(|r| (l >> r) as u64 & 3)); } + key.push(lw.ps_masks.get(&d.pc).map_or(0, |&f| f as u64 + 1)); if d.inst.name == "S_GETPC_B64" { key.push(if param_pc { d.pc.wrapping_sub(blk.pc) } else { d.pc }); } diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 22cc20d7f7..444220a59c 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 = 9; +pub const TRANSLATOR_VERSION: u32 = 10; /// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this /// translator, with the HLSL path as the fallback for what it cannot translate yet. @@ -564,6 +564,7 @@ impl Lw { gfx: None, gfx_half: None, whole_live: Default::default(), + ps_masks: Default::default(), guard_override: None, mask_override: None, local_masks: false, @@ -612,6 +613,9 @@ impl Lw { if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); } + if matches!(entry, Entry::Pixel(_)) && !split { + lw.ps_masks = crate::gpu::recomp::ps_masks::forms(insts); + } lw.setup_storage(uses_lds, if split { slot } else { 1 }); if let (Some(t), true) = (group_threads, split) { lw.partner = match t { diff --git a/crates/xcl/src/gpu/dxil/lanes.rs b/crates/xcl/src/gpu/dxil/lanes.rs index 3bc1cd8d31..3cf1b61601 100644 --- a/crates/xcl/src/gpu/dxil/lanes.rs +++ b/crates/xcl/src/gpu/dxil/lanes.rs @@ -480,6 +480,33 @@ impl Lw { (lo, hi) } + /// Pixel-shader mask with only the live lanes' bits right besides this lane's own + /// (`recomp::ps_masks`; parity with HLSL `ballot_px_local`): `WaveActiveBallot`, which + /// leaves helper lanes out, OR this lane's bit; `own_only` leaves out the ballot too. + pub fn ballot_ps_local(&mut self, cond: Value, own_only: bool) -> (Value, Value) { + let z = self.c(0); + let b = self.u(cond); + let l31 = self.lane31; + let b = self.bin(BinOp::Shl, b, l31); + let (mut lo, mut hi) = if self.wave64 { + let u = self.upper; + (self.sel(u, z, b), self.sel(u, b, z)) + } else { + (b, z) + }; + if !own_only { + let w = self.s.wave_ballot(cond); + let (wl, wh) = match (self.wave64, self.gfx_half) { + (true, _) => (w[0], w[1]), + (false, Some(h)) => (self.sel(h, w[1], w[0]), z), + (false, None) => (w[0], z), + }; + lo = self.or(lo, wl); + hi = self.or(hi, wh); + } + (lo, hi) + } + /// Pixel-shader ballot from a precomputed 4-bit quad mask `q` (bit `p` = member `p`'s /// predicate, identical across all 4 lanes of each quad; parity with HLSL `ballot_px_quad` /// in `recomp/emit.rs`): 4 `WaveActiveBallot` passes spread each quad's member `p` from @@ -770,8 +797,8 @@ mod ps_ballot_tests { assert!(dis.contains("dx.op.quadReadLaneAt.i32"), "wave64 {wave64}: PS VOPC must quad-read VGPR operands via quadReadLaneAt:\n{dis}"); assert!(!dis.contains("dx.op.quadOp"), "wave64 {wave64}: PS VOPC must not emit quadOp on compare results (#134):\n{dis}"); - // Standalone VOPC with no DPP / readfirstlane (so `rla` is never called): - // proves VOPC itself emits the 4 VGPR operand `quadReadLaneAt` reads and zero `quadOp`. + // Standalone VOPC with no DPP / readfirstlane (so `rla` is never called), whose + // mask only `v_cndmask` reads: the lane's own bit (`recomp::ps_masks`), no quad ops. let mut vopc_only = Vec::new(); vopc_only.extend(encode(if wave64 { "S_WQM_B64" } else { "S_WQM_B32" }, "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None).unwrap()); vopc_only.extend(encode("V_CMP_LT_F32", "ENC_VOPC", &[("SRC0", 128), ("VSRC1", 2)], None).unwrap()); @@ -781,7 +808,7 @@ mod ps_ballot_tests { let kv = kernel::translate_pixel(&vopc_only, opt, &psi).expect("translate VOPC-only PS"); validate::validate(&kv.dxil).expect("validate VOPC-only PS"); let vdis = validate::disassemble(&kv.dxil).expect("disassemble VOPC-only PS"); - assert_eq!(vdis.matches("call i32 @dx.op.quadReadLaneAt.i32(").count(), 4, "wave64 {wave64}: expected 4 operand quad reads for V_CMP_LT_F32(0, v2):\n{vdis}"); + assert_eq!(vdis.matches("call i32 @dx.op.quadReadLaneAt.i32(").count(), 0, "wave64 {wave64}: V_CMP_LT_F32(0, v2) read only by v_cndmask needs no quad reads:\n{vdis}"); assert!(!vdis.contains("dx.op.quadOp"), "wave64 {wave64}: VOPC-only PS must not emit quadOp:\n{vdis}"); // Entry EXEC alone (no post-entry ballot) must stay live-lanes-only (no quad reads). diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 8c9dd4b9d6..5933620518 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -260,6 +260,8 @@ pub struct Lw { pub gfx_half: Option, /// split form: SGPRs whole-live after each instruction (`recomp::x64_masks::by_pc`) pub whole_live: std::collections::BTreeMap, + /// pixel shaders: compares whose mask needs less than the per-quad form (`recomp::ps_masks`) + pub ps_masks: std::collections::BTreeMap, /// set when an exchange was needed where it is not supported pub exchange_error: Option, pub pc: u64, diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index b2805c5f17..9030698381 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -5,6 +5,7 @@ use super::lower::{err, ext_encoding, Dst, LResult, Lw, Mods, VAR_VGPR}; use super::module::{BinOp, Pred, Value}; use super::ops_core::op; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; +use crate::gpu::recomp::ps_masks::Form as PsForm; /// A source operand: one dword, or a mask pair (SGPR pair / VCC). #[derive(Clone, Copy)] @@ -1241,6 +1242,26 @@ impl Lw { if matches!(dst, Dst::Null) && matches!(ty, "f32" | "i32" | "u32") { return Ok(()); } + // the forms `recomp::ps_masks` found enough for this mask + let form = if self.split { None } else { self.ps_masks.get(&d.pc).copied() }; + if let Some(form) = form { + let c = self.vopc_cond(d, opn, ty, ua, ub, m)?; + let (lo, hi) = if form == PsForm::Uniform { + let (el, eh) = self.exec_mask(); + let z = self.c(0); + (self.sel(c, el, z), self.sel(c, eh, z)) + } else { + let a = self.act(); + let c = self.land(a, c); + self.ballot_ps_local(c, form == PsForm::Own) + }; + if self.wave64 { + self.write64(&dst, lo, hi); + } else { + self.write32(&dst, lo); + } + return Ok(()); + } let is_vgpr = |o: &Operand| match o.field { Some("LITERAL") | None => false, Some(f) => { @@ -1276,7 +1297,17 @@ impl Lw { let sh = self.shlc(up, p); q = self.or(q, sh); } - let (lo, hi) = self.ballot_ps_quad(q); + let (mut lo, mut hi) = self.ballot_ps_quad(q); + // the quad's live lanes read this lane's EXEC bit from their own copy of EXEC, + // which a compare in the local form may have left without it (`recomp::ps_masks`) + if !self.ps_masks.is_empty() && !self.split { + let c = self.vopc_cond(d, opn, ty, ua, ub, m)?; + let a = self.act(); + let c = self.land(a, c); + let (ol, oh) = self.ballot_ps_local(c, true); + lo = self.or(lo, ol); + hi = self.or(hi, oh); + } if self.wave64 { self.write64(&dst, lo, hi); } else { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 7866598897..c0a8b57ffb 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -61,6 +61,7 @@ pub(crate) mod emit; pub mod mesh_dispatch; pub mod mesh_wave; pub mod partition; +pub mod ps_masks; pub mod x64_masks; pub mod pso; pub use emit::mesh_passthrough; diff --git a/crates/xcl/src/gpu/recomp/ps_masks.rs b/crates/xcl/src/gpu/recomp/ps_masks.rs new file mode 100644 index 0000000000..28013110a2 --- /dev/null +++ b/crates/xcl/src/gpu/recomp/ps_masks.rs @@ -0,0 +1,539 @@ +//! Pixel shaders (#2083): which compare masks need each helper lane's bit from its quad. +//! +//! On the console a pixel shader's masks hold helper lanes' bits; here `WaveActiveBallot` +//! leaves them out, so `Lw::ballot_ps_quad` rebuilds every quad's four bits from quad reads +//! of the compare's operands. That costs four ballots and up to eight quad reads per compare. +//! Most masks need less. With `WaveActiveBallot(c) | own bit` (HLSL `ballot_px_local`) every +//! lane's copy of the mask has the live lanes' bits and its own bit right, so EXEC +//! predication, `v_cndmask` selectors and carry-ins stay exact in helper lanes, and so do the +//! values they compute; only another helper lane's bit can be wrong. This forward analysis +//! frees a compare when nothing reads such a bit: +//! - bitwise SALU (and, or, xor, andn2, not, mov, cselect, saveexec, wrexec) carries the mask on; +//! - any other SALU read, SCC or VCCZ of it, a VALU / SMEM scalar operand refuse it; +//! - so do cross-lane instructions while EXEC carries it: DPP, `ds_swizzle` / `bpermute`, +//! permlane read their source lane's bit of the reader's EXEC, `v_readfirstlane` the +//! first set one (waterfall loops); +//! - a branch on such an EXEC (EXECZ, or SCC of a write to EXEC) lets copies of the mask take +//! different paths: lanes that skip have their own bit 0, but the SGPRs and SCC the region +//! writes differ after it (refused if read), and so does EXEC if the region widens it; +//! - a register known to be a subset of the entry EXEC (the live lanes: the kill mask) has +//! no helper bits at all, so it is exact whatever it was computed from. +//! A compare that keeps the per-quad form under such an EXEC ORs in its own bit, which the +//! quad's other lanes may not have seen (`Lw::vopc`). + +use crate::gpu::rdna2::{self, Decoded, Variant, F_CONDITIONAL, F_INDIRECT, F_TERMINATOR}; +use super::x64_masks; +use std::collections::BTreeMap; + +const VCC: u128 = 3 << 106; +const EXEC: u128 = 3 << 126; + +fn fv(d: &Decoded, f: &str) -> Option { + rdna2::field_value(d.enc, &d.words, f) +} +fn b64(n: &str) -> bool { + n.ends_with("_B64") || n.contains("_B64_") +} +fn regs(code: u64, n: u64) -> u128 { + if code < 128 { ((1u128 << n) - 1) << code } else { 0 } +} +fn is_salu(d: &Decoded) -> bool { + matches!(d.enc.name, "ENC_SOP1" | "ENC_SOP2" | "ENC_SOPK" | "ENC_SOPC") +} +pub fn is_site(d: &Decoded) -> bool { + let n = d.inst.name; + n.starts_with("V_CMP") && d.variant == Variant::Plain && !n.starts_with("V_CMP_F_") && !n.starts_with("V_CMPX_F_") +} +fn bitwise(n: &str) -> bool { + n.contains("_SAVEEXEC_") + || n.contains("_WREXEC") + || ["S_AND_B", "S_OR_B", "S_XOR_B", "S_ANDN2_B", "S_ORN2_B", "S_NAND_B", "S_NOR_B", "S_XNOR_B", "S_NOT_B", "S_MOV_B32", "S_MOV_B64", "S_CMOV_B", "S_CSELECT_B"] + .iter() + .any(|p| n.starts_with(p)) +} +fn writes_scc(n: &str) -> bool { + (bitwise(n) && !n.starts_with("S_MOV") && !n.starts_with("S_CMOV") && !n.starts_with("S_CSELECT")) + || ["S_CMP", "S_BITCMP", "S_ADD_", "S_ADDC_", "S_SUB_", "S_SUBB_", "S_MIN_", "S_MAX_", "S_LSHL", "S_LSHR", "S_ASHR", "S_BFE_", "S_ABSDIFF", "S_WQM", "S_BCNT", "S_QUADMASK", "S_ABS_", "S_ADDK", "S_CMPK"] + .iter() + .any(|p| n.starts_with(p)) +} +fn reads_scc(n: &str) -> bool { + n.starts_with("S_CSELECT") || n.starts_with("S_CMOV") || n.starts_with("S_ADDC") || n.starts_with("S_SUBB") +} +/// every SGPR the instruction writes (also the partial writes `uses` leaves out) +fn writes(d: &Decoded) -> u128 { + let n = d.inst.name; + if n.starts_with("S_MOVRELD") { + return !0; + } + let (_, mut w) = x64_masks::uses(d); + if is_salu(d) { + if let Some(s) = fv(d, "SDST") { + w |= regs(s, if b64(n) { 2 } else { 1 }); + } + } + w +} +fn per_lane(d: &Decoded) -> u128 { + let n = d.inst.name; + if !(matches!(n, "V_CNDMASK_B32" | "V_ADD_CO_CI_U32" | "V_SUB_CO_CI_U32" | "V_SUBREV_CO_CI_U32") || n.starts_with("V_DIV_FMAS")) { + return 0; + } + match fv(d, "SRC2") { + Some(v) if d.enc.name.starts_with("ENC_VOP3") => regs(v, 2), + _ => VCC, + } +} +fn xlane(d: &Decoded) -> bool { + matches!(d.variant, Variant::Dpp16 | Variant::Dpp8) + || matches!(d.inst.name, "DS_SWIZZLE_B32" | "DS_BPERMUTE_B32" | "DS_PERMUTE_B32" | "V_PERMLANE16_B32" | "V_PERMLANEX16_B32" | "V_READFIRSTLANE_B32") +} + +#[derive(Clone, Copy, PartialEq, Default)] +struct St { + t: u128, + a: u128, + scc: u8, +} +impl St { + fn join(self, o: St) -> St { + St { t: self.t | o.t, a: self.a | o.a, scc: self.scc.max(o.scc) } + } +} + +/// SGPRs known to be a subset of a reference mask after `d`, from those before it +/// (`set`; EXEC's bit 126 in it: EXEC is). AND / ANDN2 keep a bounded first operand's +/// bound, OR / XOR / CSELECT need both, a compare's mask is a subset of EXEC. +fn subset_after(d: &Decoded, set: u128) -> u128 { + let n = d.inst.name; + let w = writes(d); + let mut out = set & !w; + let e_in = set >> 126 & 1 != 0; + if n.starts_with("V_CMP") { + if e_in { + out |= w; + } + return out; + } + if !is_salu(d) { + return out; + } + let wd = if b64(n) { 2 } else { 1 }; + let isb = |c: Option| c.is_some_and(|c| c == 128 || { let r = regs(c, wd); r != 0 && r & !set == 0 }); + let (s0, s1, sd) = (fv(d, "SSRC0"), fv(d, "SSRC1"), fv(d, "SDST")); + let sdr = sd.map_or(0, |v| regs(v, wd)); + if n.contains("_SAVEEXEC_") { + if e_in { + out |= sdr; + } + let ex = if n.starts_with("S_AND_SAVEEXEC") { + isb(s0) || e_in + } else if n.starts_with("S_ANDN1_SAVEEXEC") { + e_in + } else if n.starts_with("S_ANDN2_SAVEEXEC") { + isb(s0) + } else if n.starts_with("S_OR_SAVEEXEC") || n.starts_with("S_XOR_SAVEEXEC") { + isb(s0) && e_in + } else { + false + }; + if ex { + out |= EXEC; + } + return out; + } + let b = if n.starts_with("S_ANDN2_WREXEC") { + isb(s0) + } else if n.starts_with("S_ANDN1_WREXEC") { + isb(s1) + } else if n.starts_with("S_MOV_B") { + isb(s0) + } else if n.starts_with("S_AND_B") { + isb(s0) || isb(s1) + } else if n.starts_with("S_ANDN2_B") { + isb(s0) + } else if n.starts_with("S_OR_B") || n.starts_with("S_XOR_B") || n.starts_with("S_CSELECT_B") { + isb(s0) && isb(s1) + } else { + false + }; + if b { + out |= w; + } + out +} + +/// SGPRs that are a subset of the live lanes (the entry EXEC) after each instruction: +/// their helper-lane bits are 0, so the local form leaves them exact +fn live_subsets(insts: &[Decoded], succ: &[Vec]) -> Vec { + let n = insts.len(); + let mut zin = vec![!0u128; n]; + let mut seen = vec![false; n]; + zin[0] = EXEC; + seen[0] = true; + let mut work = vec![0usize]; + let mut queued = vec![false; n]; + queued[0] = true; + while let Some(i) = work.pop() { + queued[i] = false; + let o = subset_after(&insts[i], zin[i]); + for &j in &succ[i] { + let nz = if seen[j] { zin[j] & o } else { o }; + if !seen[j] || nz != zin[j] { + seen[j] = true; + zin[j] = nz; + if !queued[j] { + queued[j] = true; + work.push(j); + } + } + } + } + (0..n).map(|i| if seen[i] { subset_after(&insts[i], zin[i]) } else { !0 }).collect() +} + +/// A conditional branch's region (forward: up to its target; backward: the loop) and what +/// differs after it when copies of the mask disagree on taking it. +struct Region { + joins: Vec, + /// SGPRs it writes + w: u128, + scc: bool, + /// it widens EXEC, or runs something EXEC does not mask (v_writelane, scalar stores, + /// messages) that the lanes skipping it would miss + bad: bool, +} + +/// The form each pixel-shader compare's mask can take, by address (compares not in it +/// keep the per-quad form of `Lw::ballot_ps_quad`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Form { + /// never read whole: the lane's own bit + Own, + /// read whole, but no other lane's helper bit is: `WaveActiveBallot | own bit` + Local, + /// both operands scalar / constant: `cond ? EXEC : 0` + Uniform, +} + +pub fn forms(insts: &[Decoded]) -> BTreeMap { + let n = insts.len(); + let mut out = BTreeMap::new(); + if n == 0 { + return out; + } + let pcs: std::collections::BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); + let mut indirect = vec![false; n]; + let succ: Vec> = insts + .iter() + .enumerate() + .map(|(i, d)| { + let next = if i + 1 < n { Some(i + 1) } else { None }; + if let Some(t) = d.far_target { + return pcs.get(&t).copied().into_iter().collect(); + } + if d.inst.flags & F_INDIRECT != 0 || d.inst.name == "S_SETPC_B64" || d.inst.name == "S_SWAPPC_B64" { + indirect[i] = true; + return Vec::new(); + } + let mut v = Vec::new(); + if let Some(t) = rdna2::branch_target(d) { + v.extend(pcs.get(&t).copied()); + if d.inst.flags & F_CONDITIONAL != 0 { + v.extend(next); + } + } else if d.inst.flags & F_TERMINATOR == 0 { + v.extend(next); + } + v + }) + .collect(); + let z = live_subsets(insts, &succ); + // conditional branches: the region whose execution may differ between copies + let mut region: Vec> = (0..n).map(|_| None).collect(); + for (b, d) in insts.iter().enumerate() { + if d.inst.flags & F_CONDITIONAL == 0 { + continue; + } + let Some(t) = rdna2::branch_target(d).and_then(|t| pcs.get(&t).copied()) else { continue }; + let (lo, hi, mut joins) = if t > b { (b + 1, t, vec![t]) } else { (t, b + 1, vec![b + 1]) }; + if t <= b { + for k in lo..hi { + for &s in &succ[k] { + if (s < lo || s >= hi) && !joins.contains(&s) { + joins.push(s); + } + } + } + } + let (mut w, mut scc, mut bad) = (0u128, false, false); + let mut bound: u128 = EXEC; + for k in lo..hi.min(n) { + let dk = &insts[k]; + w |= writes(dk) & !EXEC; + scc |= writes_scc(dk.inst.name); + bound = subset_after(dk, bound); + let nk = dk.inst.name; + bad |= writes(dk) & EXEC != 0 && bound >> 126 & 1 == 0 + || nk == "V_WRITELANE_B32" + || nk.starts_with("S_SENDMSG") + || dk.enc.name == "ENC_SMEM" && (nk.contains("STORE") || nk.contains("ATOMIC")); + } + region[b] = Some(Region { joins, w, scc, bad }); + } + let live = x64_masks::whole_live_out(insts, false); + for site in 0..n { + let d = &insts[site]; + if !is_site(d) { + continue; + } + let dst = writes(d); + if dst == 0 { + continue; + } + if live[site] & dst == 0 && !d.inst.name.starts_with("V_CMPX") { + out.insert(d.pc, Form::Own); + continue; + } + // both operands scalar / constant: the mask is `cond ? EXEC : 0`, no ballot needed + let uniform = d.enc.name.starts_with("ENC_VOP3") && fv(d, "SRC0").is_some_and(|v| v < 256) && fv(d, "SRC1").is_some_and(|v| v < 256); + if uniform { + out.insert(d.pc, Form::Uniform); + } else if run(insts, &succ, &indirect, &z, ®ion, site).is_ok() { + out.insert(d.pc, Form::Local); + } + } + out +} + +fn run(insts: &[Decoded], succ: &[Vec], indirect: &[bool], z: &[u128], region: &[Option], site: usize) -> Result<(), &'static str> { + let n = insts.len(); + let mut sin = vec![St::default(); n]; + let mut extra = vec![St::default(); n]; + let mut div = vec![false; n]; + let mut work = vec![site]; + let mut queued = vec![false; n]; + queued[site] = true; + while let Some(i) = work.pop() { + queued[i] = false; + let st = sin[i].join(extra[i]); + if st == St::default() && i != site { + continue; + } + let d = &insts[i]; + let nm = d.inst.name; + let (whole, _) = x64_masks::uses(d); + let w = writes(d); + if (whole | per_lane(d)) & st.a != 0 { + return Err("read of a diverged register"); + } + if indirect[i] && (st.t | st.a) != 0 { + return Err("indirect jump"); + } + let mut o = St { t: st.t & !w, a: st.a & !w, scc: st.scc }; + let mut branch_div = false; + if d.enc.name == "ENC_SOPP" { + if nm.starts_with("S_CBRANCH_EXEC") { + branch_div = st.t & EXEC != 0; + } else if nm.starts_with("S_CBRANCH_SCC") { + if st.scc == 2 { + return Err("branch on SCC of a mask"); + } + branch_div = st.scc == 1; + } else if nm.starts_with("S_CBRANCH_VCC") { + if st.t & VCC != 0 { + return Err("branch on VCCZ"); + } + } else if whole & st.t != 0 { + return Err("other SOPP read"); + } + } else if is_salu(d) { + let rt = whole & st.t != 0; + if reads_scc(nm) && st.scc != 0 { + return Err("SCC read (cselect / cmov / addc)"); + } + if rt && !bitwise(nm) { + return Err(if nm.starts_with("S_CMP") || nm.starts_with("S_BITCMP") { + "s_cmp / s_bitcmp" + } else if nm.starts_with("S_WQM") { + "s_wqm" + } else { + "other SALU" + }); + } + match () { + _ if nm.contains("_SAVEEXEC_") || nm.contains("_WREXEC") => { + let et = st.t & EXEC != 0; + let srct = whole & !EXEC & st.t != 0; + let sd = w & !EXEC; + if et || srct { + o.t |= EXEC; + } + if nm.contains("_WREXEC") { + if et || srct { + o.t |= sd; + } + } else if et { + o.t |= sd; + } + } + _ => { + if rt { + o.t |= w; + } + } + } + if writes_scc(nm) { + // SCC of a bitwise op is its result != 0: exact when the result is live-only + let exact = w & !EXEC & !z[i] == 0 && (w & EXEC == 0 || z[i] >> 126 & 1 != 0); + o.scc = if rt && !exact { if w & EXEC != 0 { 1 } else { 2 } } else { 0 }; + } + } else if d.enc.name == "ENC_SMEM" { + if whole & st.t != 0 { + return Err("SMEM operand"); + } + } else { + // VALU / VMEM / DS / export + if st.a & EXEC != 0 { + return Err("diverged EXEC"); + } + let exec_data = d.variant == Variant::Plain && ["SRC0", "SRC1", "SRC2"].iter().any(|f| matches!(fv(d, f), Some(126 | 127))); + if whole & !EXEC & st.t != 0 || exec_data && st.t & EXEC != 0 { + return Err("VALU / VMEM scalar operand"); + } + if st.t & EXEC != 0 && xlane(d) { + return Err(match d.variant { + Variant::Dpp16 | Variant::Dpp8 => "DPP under the mask", + _ if nm == "V_READFIRSTLANE_B32" => "readfirstlane under the mask", + _ => "ds_swizzle / permute under the mask", + }); + } + if is_site(d) && (i == site || st.t & EXEC != 0) { + o.t |= w; + } + } + o.t &= !z[i]; + if branch_div && !div[i] { + div[i] = true; + if let Some(r) = ®ion[i] { + if r.bad { + return Err("branch on the mask over EXEC changes or unmasked work"); + } + for &j in &r.joins { + let e = St { t: 0, a: r.w, scc: if r.scc { 2 } else { 0 } }; + let ne = extra[j].join(e); + if ne != extra[j] { + extra[j] = ne; + if !queued[j] { + queued[j] = true; + work.push(j); + } + } + } + } + } + for &j in &succ[i] { + let ns = sin[j].join(o); + if ns != sin[j] { + sin[j] = ns; + if !queued[j] { + queued[j] = true; + work.push(j); + } + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::gpu::rdna2::encode; + + const V: u64 = 256; + type I = (&'static str, &'static str, Vec<(&'static str, u64)>); + + /// The form of every compare in `prog` (wave64; `S_ENDPGM` appended), in order. + fn forms_of(prog: &[I]) -> Vec> { + let mut code: Vec = prog.iter().flat_map(|(n, e, f)| encode(n, e, f, None).unwrap_or_else(|err| panic!("{n}: {err}"))).collect(); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut insts = Vec::new(); + let mut off = 0; + while off < code.len() { + let d = rdna2::decode(&code[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + rdna2::resolve_far_jumps(&mut insts); + let f = forms(&insts); + insts.iter().filter(|d| is_site(d)).map(|d| f.get(&d.pc).copied()).collect() + } + fn sop1(n: &'static str, d: u64, s: u64) -> I { + (n, "ENC_SOP1", vec![("SDST", d), ("SSRC0", s)]) + } + fn sop2(n: &'static str, d: u64, a: u64, b: u64) -> I { + (n, "ENC_SOP2", vec![("SDST", d), ("SSRC0", a), ("SSRC1", b)]) + } + fn cmp(src1: u64) -> I { + ("V_CMP_LT_F32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", src1)]) + } + fn dpp(dst: u64, src: u64) -> I { + ("V_MOV_B32", "VOP1_VOP_DPP16", vec![("VDST", dst), ("SRC0", 0xFA), ("VSRC0", src), ("DPP_CTRL", 0xB1), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]) + } + fn branch(n: &'static str, words: u64) -> I { + (n, "ENC_SOPP", vec![("SIMM16", words)]) + } + + #[test] + fn masks_read_lane_by_lane_or_restored_before_derivatives_take_the_cheap_forms() { + let wqm = sop1("S_WQM_B64", 126, 126); + // v_cndmask alone reads it: the own bit + assert_eq!(forms_of(&[wqm.clone(), cmp(2), ("V_CNDMASK_B32", "ENC_VOP2", vec![("VDST", 4), ("SRC0", 128), ("VSRC1", 2)])]), [Some(Form::Own)]); + // EXEC from it, restored before the DPP derivative: the local form + let save = sop1("S_AND_SAVEEXEC_B64", 22, 106); + let mov = ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", V + 3)]); + let restore = sop1("S_MOV_B64", 126, 22); + assert_eq!(forms_of(&[wqm.clone(), cmp(3), save.clone(), mov.clone(), restore.clone(), dpp(8, 7)]), [Some(Form::Local)]); + // the DPP under that EXEC reads the source lane's bit of the reader's copy: kept + assert_eq!(forms_of(&[wqm.clone(), cmp(3), save, mov, dpp(8, 7), restore]), [None]); + // scalar operands: cond ? EXEC : 0 + let ucmp = ("V_CMP_LT_F32", "ENC_VOP3", vec![("VDST", 106), ("SRC0", 4), ("SRC1", 128)]); + assert_eq!(forms_of(&[wqm, ucmp, sop1("S_AND_SAVEEXEC_B64", 22, 106), dpp(8, 7)]), [Some(Form::Uniform)]); + } + + #[test] + fn masks_read_across_lanes_keep_the_quad_form() { + let wqm = sop1("S_WQM_B64", 126, 126); + // s_cbranch_vccz: a helper lane's bit alone sends the live lanes into the block + assert_eq!(forms_of(&[wqm.clone(), cmp(2), sop2("S_AND_B64", 106, 126, 106), branch("S_CBRANCH_VCCZ", 1), ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 7), ("SRC0", 128)])]), [None]); + // waterfall loop: v_readfirstlane picks the first lane of an EXEC that carries the mask + let body: Vec = vec![ + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 4), ("SRC0", V + 2)]), + ("V_CMP_EQ_F32", "ENC_VOPC", vec![("SRC0", 4), ("VSRC1", 2)]), + sop1("S_AND_SAVEEXEC_B64", 26, 106), + sop2("S_XOR_B64", 126, 26, 126), + ]; + let mut prog = vec![wqm, sop1("S_MOV_B64", 24, 126)]; + prog.extend(body); + prog.push(branch("S_CBRANCH_EXECNZ", (-5i64) as u16 as u64)); + prog.push(sop1("S_MOV_B64", 126, 24)); + assert_eq!(forms_of(&prog), [None]); + } + + #[test] + fn a_kill_mask_of_live_lanes_stays_exact() { + // s20 = the entry EXEC (live lanes only); a v_cmpx kill clears its lanes from it, and + // the branch on SCC (any pixel left) sees no helper bit: the local form is enough + let prog: Vec = vec![ + sop1("S_MOV_B64", 20, 126), + sop1("S_WQM_B64", 126, 126), + ("V_CMPX_LT_F32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 2)]), + sop2("S_ANDN2_B64", 20, 20, 126), + branch("S_CBRANCH_SCC0", 2), + sop1("S_WQM_B64", 2, 20), + sop2("S_AND_B64", 126, 126, 2), + ]; + assert_eq!(forms_of(&prog), [Some(Form::Local)]); + } +} From b5fc71d088dbe88638e51384f9271049b5edbfdd Mon Sep 17 00:00:00 2001 From: MacieGx Date: Wed, 25 Nov 2026 12:27:24 +0100 Subject: [PATCH 154/258] Recompiler: a PS reads float16 attributes packed two per dword per half A retail title's world pixel shaders (#505; 173 of its 362) pack their float16 interpolants: two components per dword (component c of a register in dword c / 2, the even one in the low half) and up to two signature registers per attribute, the second after the dwords the first one's components take (1 for .xy, 2 for .xyz / .xyzw). The PS reads each half with v_interp_p2_f16, SRC0 bit 8 choosing the high one. XCL refused the PS input table of such programs (records [6, reg, mask, attr, 0, reg2, packed reg, flags]: flag 8 = float16, flag 16 = byte 5 names the second register, byte 6 below byte 1 from the first pair on), so every attribute, plain ones included, fell back to "the N-th register" and the ones after a pair read their neighbour. The PS also converted the raw packed dword as a float, ignored the high bit and declared the float16 inputs nointerpolation. Now the table parses, each (dword, half) of a packed attribute maps to its element and component (f16_registers, ps_f16_slot; a record that repeats its own register pairs it with the next float16 register no other attribute names), and the PS reads that component as a float, interpolated with the attribute's own mode. Both translators (HLSL and direct DXIL). The layout was checked on the title's dumped programs: every v_interp_p2_f16 (dword, half) of 376 of 378 packed attributes in 362 PS is a declared component (2 read one past a .xy register). Not covered here: the VS / mesh side still exports the packed dwords raw (the next commit), so the GPU test feeds the PS from a PC VS that hands over each component as a float. register always in dwords 2-3, a repeated register paired with itself - which does not match the title's programs after a .xy register; both have since dropped their float16 part in favour of this change. Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/core_tests.rs | 92 ++++++++++++++++++++ crates/xcl/src/gpu/dxil/lower_gfx.rs | 18 +++- crates/xcl/src/gpu/recomp/emit.rs | 23 +++-- crates/xcl/src/gpu/recomp/mod.rs | 120 +++++++++++++++++++++++++- 4 files changed, 241 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index b688c92f0b..629b9efc78 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -154,6 +154,98 @@ fn direct_and_hlsl_graphics_stages_link() { assert_eq!(draw(&hvs, &dps), want, "HLSL VS + direct PS"); } +/// Float16 interpolants packed two per dword, two registers in one attribute (TEXCOORD1.xyz +/// and TEXCOORD4.xyzw in attribute 0, as a retail title's world shaders have them): the PS +/// reads each half with `v_interp_p2_f16` (SRC0 bit 8: the high half) and gets that component +/// of its own element interpolated across the triangle; the float attribute after the pair +/// keeps its register. Both translators. Before: the table was refused, the PS converted the +/// raw packed dword of a `nointerpolation` input and attribute 1 was read from TEXCOORD4. +#[test] +fn f16_packed_attributes_interpolate_per_half() { + use crate::gpu::dxbc::SigElement as S; + use crate::gpu::recomp::{runner, translate, Mode, Options, PsAttr, PsInterface}; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; + if !super::graphics::tests::draw_ready() { + return; + } + if crate::gpu::recomp::dxc::location().is_err() { + return runner::skip_test("no DXC"); + } + let el = |name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8| S { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 }; + const V: u64 = 256; + let user = vec![el("TEXCOORD", 1, 0, 6, 1, 0x7), el("TEXCOORD", 4, 0, 6, 2, 0xF), el("TEXCOORD", 3, 0, 3, 3, 0xF)]; + // a PC VS handing over each component as a float: COLOR c -> TEXCOORD1 = (c0, c1, c2, 0), + // TEXCOORD4 = (c3, c0, c1, c2), TEXCOORD3 = c reversed + let pc_vs = "struct I { float2 pos : POSITION; float4 c : COLOR0; };\nstruct O { float4 pos : SV_Position; float4 t1 : TEXCOORD1; float4 t4 : TEXCOORD4; float4 t3 : TEXCOORD3; };\nO main(I i) { O o; o.pos = float4(i.pos, 0.0, 1.0); o.t1 = float4(i.c.xyz, 0.0); o.t4 = float4(i.c.w, i.c.xyz); o.t3 = i.c.wzyx; return o; }\n"; + let pvs = crate::gpu::recomp::dxc::compile(pc_vs, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pc_vs}")); + let psi = PsInterface { + inputs: std::iter::once(el("SV_Position", 0, 1, 3, 0, 0xF)).chain(user.iter().cloned()).collect(), + outputs: vec![el("SV_Target", 0, 64, 3, 0, 0xF)], + input_ena: 0x302, + attrs: Some(vec![ + PsAttr { kind: 6, register: 1, mask: 3, flat: false, f16: true, pair: Some(2) }, + PsAttr { kind: 6, register: 3, mask: 0xF, flat: false, f16: false, pair: None }, + ]), + }; + // a PS returning four values: Some((dword, high)) of attribute 0, None: attr1[k] as f32 + let ps_code = |sel: [Option<(u64, u64)>; 4]| { + let mut ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = Vec::new(); + for (k, s) in sel.iter().enumerate() { + let k = k as u64; + match *s { + Some((chan, high)) => { + let attr = chan << 6 | high << 8; + ops.push(("V_INTERP_P1LL_F16", "ENC_VOP3", vec![("VDST", 8 + k), ("SRC1", V), ("SRC0", attr)], None)); + ops.push(("V_INTERP_P2_F16", "ENC_VOP3", vec![("VDST", 4 + k), ("SRC1", V + 1), ("SRC0", attr), ("SRC2", V + 8 + k)], None)); + ops.push(("V_CVT_F32_F16", "ENC_VOP1", vec![("VDST", 4 + k), ("SRC0", V + 4 + k)], None)); + } + None => { + ops.push(("V_INTERP_P1_F32", "ENC_VINTRP", vec![("VDST", 4 + k), ("VSRC", 0), ("ATTR", 1), ("ATTRCHAN", k)], None)); + ops.push(("V_INTERP_P2_F32", "ENC_VINTRP", vec![("VDST", 4 + k), ("VSRC", 1), ("ATTR", 1), ("ATTRCHAN", k)], None)); + } + } + } + ops.push(("EXP", "ENC_EXP", vec![("TGT", 0), ("EN", 0xF), ("VSRC0", 4), ("VSRC1", 5), ("VSRC2", 6), ("VSRC3", 7), ("DONE", 1), ("VM", 1)], None)); + let list: Vec<(&str, &str, &[(&str, u64)], Option)> = ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + prog(&list) + }; + let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + // COLOR = (x, y, x / 4 + 1 / 2, y / 2 - 1 / 4) at each vertex: exact in float16, and linear + // in the pixel's position + let color = |x: f32, y: f32| [x, y, 0.25 * x + 0.5, 0.5 * y - 0.25]; + let verts: Vec = [[-1.0f32, -1.0], [-1.0, 3.0], [3.0, -1.0]].iter().flat_map(|p| [p[0], p[1]].into_iter().chain(color(p[0], p[1]))).collect(); + let layout = [ + runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }, + runner::VertexElement { semantic: "COLOR", index: 0, format: DXGI_FORMAT_R32G32B32A32_FLOAT, offset: 8 }, + ]; + // what each selection reads, as indices into COLOR (4: nothing declared there, 0) + let cases: [([Option<(u64, u64)>; 4], [usize; 4], &str); 4] = [ + ([Some((0, 0)), Some((0, 1)), Some((1, 0)), Some((2, 0))], [0, 1, 2, 3], "TEXCOORD1.xyz, TEXCOORD4.x"), + ([Some((2, 1)), Some((3, 0)), Some((3, 1)), Some((1, 1))], [0, 1, 2, 4], "TEXCOORD4.yzw, TEXCOORD1.w"), + ([Some((3, 1)), Some((2, 0)), Some((0, 1)), Some((0, 0))], [2, 3, 1, 0], "both registers, mixed halves"), + ([None, None, None, None], [3, 2, 1, 0], "the float attribute after the pair"), + ]; + for (sel, want, what) in cases { + let code = ps_code(sel); + let pt = translate(&code, &Options { mode: Mode::Pixel(psi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert!(pt.complete(), "{what}: {:?}", pt.unsupported_why); + assert!(!pt.hlsl.contains("nointerpolation"), "{what}: the float16 inputs interpolate\n{}", pt.hlsl); + let hps = crate::gpu::recomp::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); + let dps = super::kernel::translate_pixel(&code, ko, &psi).unwrap().dxil; + for (stages, vs, ps) in [("PC VS + HLSL PS", &pvs, &hps), ("PC VS + direct PS", &pvs, &dps)] { + let px = runner::draw(vs, ps, &layout, &verts, 24, &[], &[], 8, [9.0; 4]).unwrap(); + for y in 0..8usize { + for x in 0..8usize { + let c = color((x as f32 + 0.5) / 4.0 - 1.0, 1.0 - (y as f32 + 0.5) / 4.0); + let expected = want.map(|k| if k == 4 { 0.0 } else { c[k] }); + let got = px[y * 8 + x]; + assert!(got.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-3), "{what}, {stages}: pixel ({x},{y}) = {got:?}, expected {expected:?}"); + } + } + } + } +} + fn sig(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> crate::gpu::dxbc::SigElement { crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } } diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs index a337d470bc..6b0a3e0848 100644 --- a/crates/xcl/src/gpu/dxil/lower_gfx.rs +++ b/crates/xcl/src/gpu/dxil/lower_gfx.rs @@ -14,7 +14,7 @@ use super::lower::{err, LResult, Lw}; use super::module::{Pred, Value}; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded}; -use crate::gpu::recomp::{elements_at, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, PsInterface, VsInterface}; +use crate::gpu::recomp::{elements_at, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, PsInterface, VsInterface}; /// An output element: its signature handle, components and the temporaries holding them. pub struct GfxOut { @@ -166,7 +166,8 @@ impl Lw { for (k, e) in ranked(&ps.inputs, false).iter().enumerate() { let attr = ps_slot_attribute(ps, k); let m = attr.and_then(|a| modes.get(&(a as u32))).cloned().unwrap_or_default(); - let float = e.component_type == 3; + // float16 read through a packed attribute interpolates like a float + let float = e.component_type == 3 || (e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some())); let interp = if !float { Interp::Constant } else { @@ -401,11 +402,20 @@ impl Lw { let s1 = f("SRC1"); (f("VDST"), if s1 >= 256 { s1 - 256 } else { s1 }, f("SRC0") & 0x3F, f("SRC0") >> 6 & 3) }; - let Some(slot) = ps_attribute_slot(&ps, attr as usize, chan as usize) else { return err(d, "attribute outside ISG1") }; + // a float16-packed attribute: the PC input is the component itself (SRC0 bit 8: the + // high half of the dword); a half nothing declares reads 0 + let place = match ps_attribute_f16(&ps, attr as usize).filter(|_| name.ends_with("_f16")) { + Some(regs) => ps_f16_slot(&ps, ®s, chan as usize, d.enc.name != "ENC_VINTRP" && f("SRC0") >> 8 & 1 == 1), + None => match ps_attribute_slot(&ps, attr as usize, chan as usize) { + Some(slot) => Some((slot, chan as usize)), + None => return err(d, "attribute outside ISG1"), + }, + }; let load = |lw: &mut Lw| -> Value { + let Some((slot, comp)) = place else { return lw.c(0) }; let g = lw.gfx.as_mut().expect("gfx"); let (sig, _) = g.ps_in[slot]; - let x = g.io.load_input(&mut lw.s, sig, 0, chan as u8); + let x = g.io.load_input(&mut lw.s, sig, 0, comp as u8); let i32 = lw.s.m.i32(); lw.s.m.bitcast(x, i32) }; diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 1d15f865fa..36c64698bf 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; -use super::{elements_at, param_registers, ps_attribute_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use super::{elements_at, param_registers, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; use super::upper_lanes::Read; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -2475,10 +2475,21 @@ impl Em { fn interp(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> { let Mode::Pixel(ps) = &self.opt.mode else { return Err("interpolation outside PS") }; let (vdst, ij, attr, chan) = Self::interp_fields(d); - let Some(slot) = ps_attribute_slot(ps, attr as usize, chan as usize) else { - return Err("attribute outside ISG1"); + // a float16-packed attribute (two registers, two components per dword): the PC input + // is the component itself, interpolated as a float – SRC0 bit 8 picks the high half + let high = d.enc.name != "ENC_VINTRP" && rdna2::field_value(d.enc, &d.words, "SRC0").unwrap_or(0) >> 8 & 1 == 1; + let src = match ps_attribute_f16(ps, attr as usize).filter(|_| name.ends_with("_f16")) { + Some(regs) => match ps_f16_slot(ps, ®s, chan as usize, high) { + Some((slot, comp)) => format!("xi.a{slot}[{comp}]"), + None => "0.0f".to_string(), + }, + None => { + let Some(slot) = ps_attribute_slot(ps, attr as usize, chan as usize) else { + return Err("attribute outside ISG1"); + }; + format!("xi.a{slot}[{chan}]") + } }; - let src = format!("xi.a{slot}[{chan}]"); let act = self.act(); match name { "v_interp_p1_f32" | "v_interp_p1ll_f16" | "v_interp_p1lv_f16" => { @@ -5293,7 +5304,9 @@ impl Em { // the mode of the attribute this input is read through (none: never read) let attr = ps_slot_attribute(ps, k); let mut m = attr.and_then(|a| self.ps_modes.get(&(a as u32))).cloned().unwrap_or_default(); - if e.component_type != 3 { + // float16 read through a packed attribute interpolates like a float + let f16 = e.component_type == 6 && attr.is_some_and(|a| ps_attribute_f16(ps, a).is_some()); + if e.component_type != 3 && !f16 { m = "nointerpolation".into(); } let _ = writeln!(h, " {m} {}4 a{k} : {};", hlsl_type(e), e.semantic()); diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index c0a8b57ffb..6833182b3c 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -388,6 +388,10 @@ pub struct PsAttr { pub register: u8, pub mask: u8, pub flat: bool, + /// float16 values, two per dword (record flag 8) – see `f16_registers` + pub f16: bool, + /// the record names a second register (flag 16; the same register again: not named) + pub pair: Option, } /// The PS input table of an FSSM: SPI_PS_INPUT_ENA and, per `v_interp attrN`, the register it @@ -395,6 +399,11 @@ pub struct PsAttr { /// mask, attribute number, 0, 0, register again, 1 flat / 2 interpolated; then the record count /// (+0x100) and SPI_PS_INPUT_ENA (+0x110). Checked on every cached PS of three titles (472, 34, /// 1): consistent, and covering every attribute the code reads. +/// +/// A title that packs its float16 interpolants (378 such records in 362 PS of one): byte 7 also +/// has 8 (float16, two per dword) and 16 (byte 5 = the second register of the attribute), and +/// byte 6 is the register counted after that packing (below the DXIL register from the first +/// pair on). pub fn ps_input_table(fssm: &[u8]) -> Option<(u32, Vec)> { let base = 0x130 + fssm_shift(fssm)?; let rd = |o: usize| fssm.get(o..o + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); @@ -405,10 +414,11 @@ pub fn ps_input_table(fssm: &[u8]) -> Option<(u32, Vec)> { let mut out = Vec::with_capacity(n); for k in 0..n { let r = fssm.get(base + 8 * k..base + 8 * k + 8)?; - if r[3] as usize != k || r[4] != 0 || r[5] != 0 || r[6] != r[1] { + let (f16, pair) = (r[7] & 8 != 0, r[7] & 16 != 0); + if r[3] as usize != k || r[4] != 0 || (!pair && r[5] != 0) || (pair && !f16) || r[6] > r[1] { return None; } - out.push(PsAttr { kind: r[0], register: r[1], mask: r[2], flat: r[7] == 1 }); + out.push(PsAttr { kind: r[0], register: r[1], mask: r[2], flat: r[7] & 3 == 1, f16, pair: pair.then_some(r[5]) }); } Some((ena, out)) } @@ -446,6 +456,47 @@ pub fn vs_output_table(fssm: &[u8]) -> Option> { Some(out) } +/// Where a float16-packed param / attribute keeps its registers: (register, first dword). +/// The console's compiler puts two float16 components in a dword – component c of a register +/// in dword c / 2, the even one in the low half – and up to two registers in one param: the +/// second follows the dwords the first one's components take (2 for .xyz / .xyzw, 1 for .xy). +/// The registers pair up in order, so where a table does not name the second one it is the +/// next float16 register that starts no param of its own (`claimed`). Checked against the +/// code of a retail title: every `v_interp_p2_f16` channel / half of 376 packed attributes +/// (362 PS) is a declared component (2 more read one past a .xy register), and the enable +/// mask of every `exp param` of 383 packed params (442 MS) is exactly these dwords. +pub fn f16_registers(sig: &[SigElement], first: u32, second: Option, pair: bool, claimed: &dyn Fn(u32) -> bool) -> Vec<(u32, usize)> { + let second = match second { + Some(r) if r != first => Some(r), + _ if !pair => None, + _ => sig.iter().filter(|e| e.component_type == 6 && e.system_value == 0 && e.register > first && !claimed(e.register)).map(|e| e.register).min(), + }; + let width = sig.iter().filter(|e| e.system_value == 0 && e.register == first).map(|e| 8 - e.mask.leading_zeros() as usize).max().unwrap_or(4); + std::iter::once((first, 0)).chain(second.map(|r| (r, width.div_ceil(2)))).collect() +} + +/// The registers of a float16-packed PS attribute with the first dword of each (None: the +/// attribute is not packed). +pub fn ps_attribute_f16(ps: &PsInterface, attr: usize) -> Option> { + let t = ps.attrs.as_ref()?; + let a = t.get(attr).filter(|a| a.f16)?; + let claimed = |r: u32| t.iter().any(|b| b.register as u32 == r || b.pair.is_some_and(|p| p as u32 == r)); + Some(f16_registers(&ps.inputs, a.register as u32, a.pair.map(|p| p as u32), a.pair.is_some(), &claimed)) +} + +/// The place in `ranked(inputs, false)` and the component of the float16 in half `high` of +/// dword `chan` of a packed attribute (`regs`: `ps_attribute_f16`). None: no such component. +pub fn ps_f16_slot(ps: &PsInterface, regs: &[(u32, usize)], chan: usize, high: bool) -> Option<(usize, usize)> { + let &(r, first) = regs.iter().rev().find(|&&(_, first)| first <= chan)?; + let comp = 2 * (chan - first) + high as usize; + if comp > 3 { + return None; + } + let all = ranked(&ps.inputs, false); + let slot = all.iter().position(|e| e.register == r && e.mask >> comp & 1 == 1).or_else(|| all.iter().position(|e| e.register == r))?; + Some((slot, comp)) +} + /// The register `v_interp attr` reads: the console's table, else the attr-th distinct register. pub fn ps_attribute_register(ps: &PsInterface, attr: usize) -> Option { match &ps.attrs { @@ -466,7 +517,10 @@ pub fn ps_attribute_slot(ps: &PsInterface, attr: usize, chan: usize) -> Option Option { let r = ranked(&ps.inputs, false).get(slot)?.register; match &ps.attrs { - Some(t) => t.iter().position(|a| a.register as u32 == r), + Some(t) => t + .iter() + .position(|a| a.register as u32 == r) + .or_else(|| (0..t.len()).find(|&k| ps_attribute_f16(ps, k).is_some_and(|regs| regs.iter().any(|&(x, _)| x == r)))), None => param_registers(&ps.inputs, false).iter().position(|&x| x == r), } } @@ -1726,6 +1780,66 @@ mod attribute_tests { } } + /// A signature with float16 elements (component type 6) between float ones, in the shapes a + /// retail title's PS / MS pack: r7 holds two elements, r9 a single component. + fn f16_sig() -> Vec { + let e = |name: &str, index: u32, ct: u32, register: u32, mask: u8| SigElement { component_type: ct, mask, ..input(name, index, register, mask) }; + let mut pos = input("SV_Position", 0, 0, 0); + pos.system_value = 1; + vec![ + pos, + e("COLOR", 0, 6, 1, 0xF), + e("COLOR", 1, 6, 2, 0xF), + e("TEXCOORD", 0, 3, 3, 0x3), + e("TEXCOORD", 1, 6, 4, 0x7), + e("TEXCOORD", 4, 6, 5, 0xF), + e("TEXCOORD", 3, 3, 6, 0xF), + e("TEXCOORD", 7, 6, 7, 0x3), + e("TEXCOORD", 8, 6, 7, 0xC), + e("TEXCOORD", 9, 6, 8, 0x7), + e("TEXCOORD", 14, 6, 9, 0x1), + ] + } + + /// Float16 interpolants packed two per dword and two registers per attribute (the record + /// shapes of a retail title's PS, FSSM sub-version 6): the table parses, each (dword, half) + /// names its element and component, the second register is found where the record does not + /// name it, and the attributes after a pair keep their registers. + #[test] + fn f16_packed_attributes() { + let sig = f16_sig(); + let mut f = vec![0u8; 0x400]; + f[0x10] = 6; + // PS input records: [6, reg, 3, attr, 0, reg2, packed register, 0x1a]; attr 4 repeats + // its own register (the second one is r8); attr 5 is a single float16 (0x0a) + let recs: [[u8; 8]; 6] = [[6, 1, 3, 0, 0, 2, 1, 26], [6, 3, 3, 1, 0, 0, 2, 2], [6, 4, 3, 2, 0, 5, 3, 26], [6, 6, 15, 3, 0, 0, 4, 2], [6, 7, 3, 4, 0, 7, 5, 26], [6, 9, 1, 5, 0, 0, 6, 10]]; + f[0x138..0x138 + 48].copy_from_slice(&recs.concat()); + f[0x138 + 0x100] = 6; + f[0x138 + 0x110] = 2; + let (_, attrs) = ps_input_table(&f).unwrap(); + assert_eq!(attrs.iter().map(|a| (a.register, a.f16, a.pair)).collect::>(), [(1, true, Some(2)), (3, false, None), (4, true, Some(5)), (6, false, None), (7, true, Some(7)), (9, true, None)]); + let ps = PsInterface { inputs: sig, attrs: Some(attrs), ..Default::default() }; + assert_eq!((0..6).map(|a| ps_attribute_f16(&ps, a)).collect::>(), [Some(vec![(1, 0), (2, 2)]), None, Some(vec![(4, 0), (5, 2)]), None, Some(vec![(7, 0), (8, 2)]), Some(vec![(9, 0)])]); + let all = ranked(&ps.inputs, false); + // "semantic.component" of a (dword, half) + let at = |attr: usize, chan: usize, high: bool| ps_f16_slot(&ps, &ps_attribute_f16(&ps, attr).unwrap(), chan, high).map(|(s, c)| format!("{}.{c}", all[s].semantic())).unwrap_or_default(); + assert_eq!([at(0, 0, false), at(0, 0, true), at(0, 1, true), at(0, 2, false), at(0, 3, true)], ["COLOR0.0", "COLOR0.1", "COLOR0.3", "COLOR1.0", "COLOR1.3"]); + assert_eq!([at(2, 1, false), at(2, 2, true)], ["TEXCOORD1.2", "TEXCOORD4.1"]); + // two elements in the first register; a half past the last one's components + assert_eq!([at(4, 0, true), at(4, 1, true), at(4, 2, false)], ["TEXCOORD7.1", "TEXCOORD8.3", "TEXCOORD9.0"]); + assert_eq!([at(5, 0, false), at(5, 2, false)], ["TEXCOORD14.0", ""]); + // the attributes after a pair read their own registers + assert_eq!([1, 3].map(|a| all[ps_attribute_slot(&ps, a, 0).unwrap()].semantic()), ["TEXCOORD0", "TEXCOORD3"]); + assert_eq!((0..10).map(|j| ps_slot_attribute(&ps, j)).collect::>(), [0, 0, 1, 2, 2, 3, 4, 4, 4, 5].map(Some)); + // a second register without the float16 flag is not this table + f[0x138 + 7] = 18; + assert_eq!(ps_input_table(&f), None); + + // a .xy register takes one dword: the second register starts at dword 1 + let narrow = vec![SigElement { component_type: 6, mask: 0x3, ..input("COLOR", 3, 1, 0x3) }, SigElement { component_type: 6, mask: 0x7, ..input("TEXCOORD", 8, 2, 0x7) }]; + assert_eq!(f16_registers(&narrow, 1, None, true, &|r| r == 1), [(1, 0), (2, 1)]); + } + /// Minecraft's UI vertex shader: an ISG1 input the program never reads (NORMAL0, r1) gets /// no fetch-shader VGPRs – POSITION0 (r2) is read in v8, TEXCOORD0 (r3) in v12. #[test] From 110d7254c666da98d22086226debacc72ad5b7bc Mon Sep 17 00:00:00 2001 From: MacieGx Date: Wed, 25 Nov 2026 12:32:03 +0100 Subject: [PATCH 155/258] Recompiler: VS / mesh exports unpack float16 params packed two per dword The other half of the previous commit: the VS and mesh (NGG) programs that feed those pixel shaders export their float16 interpolants packed the same way - two components per dword, up to two signature registers per exp param. XCL refused the output table of such programs (records [6, reg, param, reg, 0, 1 | 3]: 1 = float16, 3 = more than one dword) and fell back to "the N-th register", so every param after a pair went to its neighbour's register; a packed param went raw into its first register alone. A mesh program never used its table at all. Now the table parses for VS and mesh programs (MsInterface::params) and a packed param is unpacked where it is exported: each half goes as a float to its own component of its own element, in the VS outputs and in the mesh record, in both translators. The table does not name the second register of a pair: the float16 registers pair up in order, so it is the next one no other param starts with (f16_registers). Checked on the title's dumped programs: the enable mask of every exp param of 383 packed params in 442 MS is exactly the predicted dwords. A mesh program with a table now takes its params' registers from it, float16 or not, as a VS already did; without one nothing changes. dwords 2-3 and paired a mesh program's registers without its table; it has since dropped that part in favour of this change. Co-Authored-By: Claude Fable 5.2 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/core_tests.rs | 40 ++++++- crates/xcl/src/gpu/dxil/kernel.rs | 2 +- crates/xcl/src/gpu/dxil/lower.rs | 2 + crates/xcl/src/gpu/dxil/lower_gfx.rs | 19 +++- crates/xcl/src/gpu/dxil/lower_mem.rs | 20 +++- crates/xcl/src/gpu/recomp/emit.rs | 32 ++++-- .../xcl/src/gpu/recomp/heap_window_tests.rs | 2 +- crates/xcl/src/gpu/recomp/mod.rs | 74 ++++++++++-- crates/xcl/src/gpu/recomp/tests.rs | 105 +++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 4 +- 10 files changed, 259 insertions(+), 41 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 629b9efc78..fdb27fbf29 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -158,12 +158,14 @@ fn direct_and_hlsl_graphics_stages_link() { /// and TEXCOORD4.xyzw in attribute 0, as a retail title's world shaders have them): the PS /// reads each half with `v_interp_p2_f16` (SRC0 bit 8: the high half) and gets that component /// of its own element interpolated across the triangle; the float attribute after the pair -/// keeps its register. Both translators. Before: the table was refused, the PS converted the -/// raw packed dword of a `nointerpolation` input and attribute 1 was read from TEXCOORD4. +/// keeps its register. The console VS exports the packed dwords as param 0 and unpacks them +/// into the same components. Every combination of the direct and the HLSL stages, and a PC VS. +/// Before: the tables were refused, the PS converted the raw packed dword of a +/// `nointerpolation` input and attribute 1 was read from TEXCOORD4. #[test] fn f16_packed_attributes_interpolate_per_half() { use crate::gpu::dxbc::SigElement as S; - use crate::gpu::recomp::{runner, translate, Mode, Options, PsAttr, PsInterface}; + use crate::gpu::recomp::{runner, translate, Mode, Options, OutParam, PsAttr, PsInterface, VsInterface}; use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32_FLOAT}; if !super::graphics::tests::draw_ready() { return; @@ -173,7 +175,32 @@ fn f16_packed_attributes_interpolate_per_half() { } let el = |name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8| S { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 }; const V: u64 = 256; + // COLOR c in v8..v11 -> halves h0..h3 in v12..v15; param 0 = (h0 | h1 << 16, h2, h3 | h0 << 16, + // h1 | h2 << 16): TEXCOORD1 = (c0, c1, c2), TEXCOORD4 = (c3, c0, c1, c2); param 1 = c reversed + let mut vs_ops: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 0), ("SRC0", V + 4)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 2), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 3), ("SRC0", 242)], None), + ("EXP", "ENC_EXP", vec![("TGT", 12), ("EN", 0xF), ("VSRC0", 0), ("VSRC1", 1), ("VSRC2", 2), ("VSRC3", 3), ("DONE", 1)], None), + ]; + for i in 0..4u64 { + vs_ops.push(("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 12 + i), ("SRC0", V + 8 + i)], None)); + } + for (dst, lo, hi) in [(16u64, 12u64, 13u64), (18, 15, 12), (19, 13, 14)] { + vs_ops.push(("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", dst), ("SRC0", V + lo), ("SRC1", V + hi)], None)); + } + vs_ops.push(("EXP", "ENC_EXP", vec![("TGT", 32), ("EN", 0xF), ("VSRC0", 16), ("VSRC1", 14), ("VSRC2", 18), ("VSRC3", 19)], None)); + vs_ops.push(("EXP", "ENC_EXP", vec![("TGT", 33), ("EN", 0xF), ("VSRC0", 11), ("VSRC1", 10), ("VSRC2", 9), ("VSRC3", 8)], None)); + let vs_list: Vec<(&str, &str, &[(&str, u64)], Option)> = vs_ops.iter().map(|(n, e, f, l)| (*n, *e, f.as_slice(), *l)).collect(); + let vs_code = prog(&vs_list); let user = vec![el("TEXCOORD", 1, 0, 6, 1, 0x7), el("TEXCOORD", 4, 0, 6, 2, 0xF), el("TEXCOORD", 3, 0, 3, 3, 0xF)]; + let vsi = VsInterface { + inputs: vec![el("POSITION", 0, 0, 3, 0, 3), el("COLOR", 0, 0, 3, 1, 0xF)], + outputs: std::iter::once(el("SV_Position", 0, 1, 3, 0, 0xF)).chain(user.iter().cloned()).collect(), + attr_base: 4, + params: Some(vec![OutParam { register: 1, f16: true, pair: true }, OutParam { register: 3, f16: false, pair: false }]), + }; // a PC VS handing over each component as a float: COLOR c -> TEXCOORD1 = (c0, c1, c2, 0), // TEXCOORD4 = (c3, c0, c1, c2), TEXCOORD3 = c reversed let pc_vs = "struct I { float2 pos : POSITION; float4 c : COLOR0; };\nstruct O { float4 pos : SV_Position; float4 t1 : TEXCOORD1; float4 t4 : TEXCOORD4; float4 t3 : TEXCOORD3; };\nO main(I i) { O o; o.pos = float4(i.pos, 0.0, 1.0); o.t1 = float4(i.c.xyz, 0.0); o.t4 = float4(i.c.w, i.c.xyz); o.t3 = i.c.wzyx; return o; }\n"; @@ -210,6 +237,10 @@ fn f16_packed_attributes_interpolate_per_half() { prog(&list) }; let ko = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + let vt = translate(&vs_code, &Options { mode: Mode::Vertex(vsi.clone()), wave64: true, ..Default::default() }).unwrap(); + assert!(vt.complete(), "{:?}", vt.unsupported_why); + let hvs = crate::gpu::recomp::dxc::compile(&vt.hlsl, "main", "vs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", vt.hlsl)); + let dvs = super::kernel::translate_vertex(&vs_code, ko, &vsi).unwrap().dxil; // COLOR = (x, y, x / 4 + 1 / 2, y / 2 - 1 / 4) at each vertex: exact in float16, and linear // in the pixel's position let color = |x: f32, y: f32| [x, y, 0.25 * x + 0.5, 0.5 * y - 0.25]; @@ -232,7 +263,8 @@ fn f16_packed_attributes_interpolate_per_half() { assert!(!pt.hlsl.contains("nointerpolation"), "{what}: the float16 inputs interpolate\n{}", pt.hlsl); let hps = crate::gpu::recomp::dxc::compile(&pt.hlsl, "main", "ps_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", pt.hlsl)); let dps = super::kernel::translate_pixel(&code, ko, &psi).unwrap().dxil; - for (stages, vs, ps) in [("PC VS + HLSL PS", &pvs, &hps), ("PC VS + direct PS", &pvs, &dps)] { + let pairs = [("PC VS + HLSL PS", &pvs, &hps), ("PC VS + direct PS", &pvs, &dps), ("HLSL VS + HLSL PS", &hvs, &hps), ("direct VS + direct PS", &dvs, &dps), ("direct VS + HLSL PS", &dvs, &hps), ("HLSL VS + direct PS", &hvs, &dps)]; + for (stages, vs, ps) in pairs { let px = runner::draw(vs, ps, &layout, &verts, 24, &[], &[], 8, [9.0; 4]).unwrap(); for y in 0..8usize { for x in 0..8usize { diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 444220a59c..98c834e5cd 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -828,7 +828,7 @@ pub fn mesh_init(lw: &mut Lw, ms: &MsInterface, tid: Value, io: super::shader::R let mut vgpr = HashMap::new(); vgpr.insert(5, v5); lw.init.compute = Some(ComputeInit { sgpr, vgpr, zero }); - lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, outputs: ms.outputs.clone() }); + lw.mesh = Some(super::lower::MeshCtx { rec, vtx, prm, outputs: ms.outputs.clone(), params: ms.params.clone() }); } /// EXEC at entry: the console wave's threads (static per wave in the split form: no diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5933620518..c2424a16ab 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -65,6 +65,8 @@ pub struct MeshCtx { pub vtx: Value, pub prm: Value, pub outputs: Vec, + /// the console's output table (`MsInterface::params`) + pub params: Option>, } /// Initial register values: loaded from `io` in the entry block on first use. diff --git a/crates/xcl/src/gpu/dxil/lower_gfx.rs b/crates/xcl/src/gpu/dxil/lower_gfx.rs index 6b0a3e0848..e8fb2ae53b 100644 --- a/crates/xcl/src/gpu/dxil/lower_gfx.rs +++ b/crates/xcl/src/gpu/dxil/lower_gfx.rs @@ -14,7 +14,7 @@ use super::lower::{err, LResult, Lw}; use super::module::{Pred, Value}; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded}; -use crate::gpu::recomp::{elements_at, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, PsInterface, VsInterface}; +use crate::gpu::recomp::{out_param_elements, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, PsInterface, VsInterface}; /// An output element: its signature handle, components and the temporaries holding them. pub struct GfxOut { @@ -119,7 +119,7 @@ impl Lw { _ => SemKind::Arbitrary, }; let s = io.output(GSig::new(&e.name, e.index, kind, gct(e.component_type), n)); - outs.push((s, n, e.component_type == 3)); + outs.push((s, n, matches!(e.component_type, 3 | 6))); } // initial VGPRs: v0 = vertex id, v3 = instance id, the fetch shader's attribute VGPRs let mut vgpr = HashMap::new(); @@ -327,15 +327,22 @@ impl Lw { 32..=63 => { let vs = self.gfx().vs.clone().expect("vs"); let k = (tgt - 32) as usize; - let at = vs_param_register(&vs, k).map(|r| elements_at(&vs.outputs, true, r)).unwrap_or_default(); - for j in at { + let (at, f16) = out_param_elements(&vs.outputs, vs.params.as_deref(), k); + for (j, first) in at { let (vars, n) = { let o = &self.gfx().params[j]; (o.vars.clone(), o.comps) }; for c in 0..n as usize { - if enabled(c) { - let v = comp(self, c); + // packed float16: component c is half c & 1 of dword first + c / 2 + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let mut v = comp(self, dw); + if f16 { + let h = self.lshrc(v, 16 * (c as u32 & 1)); + let x = self.s.f16_to_f32(h); + v = self.bits(x); + } self.set_out(vars[c], v); } } diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 3332adc513..8e0bc93ba6 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -2576,13 +2576,23 @@ impl Lw { 13..=15 | 9 => {} 32..=63 => { let k = (tgt - 32) as usize; - let outputs = self.mesh.as_ref().expect("mesh").outputs.clone(); - let at = crate::gpu::recomp::param_registers(&outputs, true).get(k).map(|&r| crate::gpu::recomp::elements_at(&outputs, true, r)).unwrap_or_default(); - for j in at { + let (at, f16) = { + let m = self.mesh.as_ref().expect("mesh"); + crate::gpu::recomp::out_param_elements(&m.outputs, m.params.as_deref(), k) + }; + for (j, first) in at { for c in 0..4 { - if enabled(c) { + // packed float16: component c is half c & 1 of dword first + c / 2; the + // record keeps it as a float + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { let a = self.addc(vtx, (4 * (j + 1) + c) as u32); - let v = comp(self, c); + let mut v = comp(self, dw); + if f16 { + let h = self.lshrc(v, 16 * (c as u32 & 1)); + let x = self.s.f16_to_f32(h); + v = self.bits(x); + } st.push((a, v)); } } diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 36c64698bf..150525a6c2 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -3,7 +3,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fmt::Write as _; -use super::{elements_at, param_registers, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, vs_param_register, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; +use super::{out_param_elements, ps_attribute_f16, ps_attribute_slot, ps_f16_slot, ps_input_vgpr, ps_slot_attribute, ranked, Mode, MsInterface, Options, KERNEL_EXPORTS, KERNEL_LANES, KERNEL_SCC_SLOT, KERNEL_SGPRS, KERNEL_SPLIT_MAGIC, KERNEL_SPLIT_SGPRS, KERNEL_VGPRS, MESH_HEADER}; use super::upper_lanes::Read; use crate::gpu::dxbc::SigElement; use crate::gpu::rdna2::{self, Decoded, Encoding, Operand, Variant}; @@ -2364,18 +2364,26 @@ impl Em { // param N is a register: channel c goes to component c of every element there let k = (tgt - 32) as usize; let params = ranked(&vs.outputs, true); - let at = vs_param_register(vs, k).map(|r| elements_at(&vs.outputs, true, r)).unwrap_or_default(); + let (at, f16) = out_param_elements(&vs.outputs, vs.params.as_deref(), k); if at.is_empty() { self.line("/* param without an OSG1 element (dummy) */"); return Ok(()); } - for j in at { + for (j, first) in at { let e = params[j]; let n = out_comps(e); for c in 0..n { - if enabled(c) { - let v = Self::exp_comp(srcs, compr, c); - let v = if e.component_type == 3 { format!("asfloat({v})") } else { format!("{v}") }; + // packed float16: component c is half c & 1 of dword first + c / 2 + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let v = Self::exp_comp(srcs, compr, dw); + let v = if f16 { + format!("f16tof32({v} >> {}u)", 16 * (c & 1)) + } else if e.component_type == 3 { + format!("asfloat({v})") + } else { + format!("{v}") + }; let comp = if n == 1 { String::new() } else { format!("[{c}]") }; st.push(format!("xo.p{j}{comp} = {v};")); } @@ -2426,15 +2434,19 @@ impl Em { // param N is a register: its record slot is that of every element there (the // pass-through reads an element's slot as the whole register, as for the GS) let k = (tgt - 32) as usize; - let at = param_registers(&ms.outputs, true).get(k).map(|&r| elements_at(&ms.outputs, true, r)).unwrap_or_default(); + let (at, f16) = out_param_elements(&ms.outputs, ms.params.as_deref(), k); if at.is_empty() { self.line("/* param without an OSG1 element (dummy) */"); return Ok(()); } - for j in at { + for (j, first) in at { for c in 0..4 { - if enabled(c) { - st.push(format!("res.Store((xcl_vtx + {}u) * 4u, {});", 4 * (j + 1) + c, Self::exp_comp(srcs, compr, c))); + // packed float16 (as in the VS): the record keeps each half as a float + let dw = if f16 { first + c / 2 } else { c }; + if dw < 4 && enabled(dw) { + let v = Self::exp_comp(srcs, compr, dw); + let v = if f16 { format!("asuint(f16tof32({v} >> {}u))", 16 * (c & 1)) } else { v }; + st.push(format!("res.Store((xcl_vtx + {}u) * 4u, {v});", 4 * (j + 1) + c)); } } } diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs index 747afa1784..098a610e52 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -397,7 +397,7 @@ fn heap_windows_graphics_stages_validate() { let vs = VsInterface { inputs: vec![], outputs: vec![sig("SV_Position", 1, 0)], attr_base: 4, params: None }; let ps = PsInterface { inputs: vec![sig("SV_Position", 1, 0)], outputs: vec![sig("SV_Target", 64, 0)], input_ena: 0, attrs: None, early_depth: false }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 3, max_primitives: 1 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 3, max_primitives: 1, params: None }; let has_dxc = super::dxc::location().is_ok(); for windows in [4u32, crate::gpu::uma::MAX_HEAP_WINDOWS as u32] { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 6833182b3c..fee9d16dab 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -129,7 +129,7 @@ pub struct VsInterface { pub attr_base: u64, /// the OSG1 register of each `exp param N` from the console's table (`vs_output_table`; /// None: the N-th distinct register) - pub params: Option>, + pub params: Option>, } impl VsInterface { @@ -177,6 +177,8 @@ pub struct MsInterface { pub threads: u32, pub max_vertices: u32, pub max_primitives: u32, + /// the console's output table, as `VsInterface::params` + pub params: Option>, } /// dwords before the vertices of a mesh record: vertex count, primitive count, 2 spare @@ -251,6 +253,7 @@ impl GsInterface { threads: 64, max_vertices: (GS_PRIMS_PER_GROUP * mvc).clamp(1, 256), max_primitives: (GS_PRIMS_PER_GROUP * mvc.saturating_sub(2).max(1)).clamp(1, 256), + params: None, } } } @@ -394,6 +397,15 @@ pub struct PsAttr { pub pair: Option, } +/// One `exp param N` of the console's output table: its first OSG1 register; `f16`: float16 +/// values, two per dword (`pair`: more than one dword – a second register may follow). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OutParam { + pub register: u32, + pub f16: bool, + pub pair: bool, +} + /// The PS input table of an FSSM: SPI_PS_INPUT_ENA and, per `v_interp attrN`, the register it /// reads. 32 records of 8 bytes at +0x130 (+ the sub-version shift): kind, register, component /// mask, attribute number, 0, 0, register again, 1 flat / 2 interpolated; then the record count @@ -438,8 +450,11 @@ pub fn ps_shader_control(fssm: &[u8]) -> Option { /// of 6 bytes at +0x1D4 (+ the sub-version shift): kind (6 user, 0 position), register, param /// number, 0, 0, 0; the record count after them (+0xC0). Usually param N = the N-th output /// register, but not always (a Fortnite VS exports its SV_Position register as a param). -/// Checked on every cached VS of three titles (984, 13, 1). -pub fn vs_output_table(fssm: &[u8]) -> Option> { +/// Checked on every cached VS of three titles (984, 13, 1). The same table describes a mesh +/// (NGG) program's params. A float16 param (two values per dword) has 1 in the last byte, 3 +/// when it takes more than one dword, and then repeats its register in byte 3 (442 MS of one +/// title); the table does not name the second register of a pair (`f16_registers`). +pub fn vs_output_table(fssm: &[u8]) -> Option> { let base = 0x1D4 + fssm_shift(fssm)?; let n = fssm.get(base + 0xC0..base + 0xC4).map(|b| u32::from_le_bytes(b.try_into().unwrap()))? as usize; if n > 32 { @@ -448,10 +463,11 @@ pub fn vs_output_table(fssm: &[u8]) -> Option> { let mut out = Vec::with_capacity(n); for k in 0..n { let r = fssm.get(base + 6 * k..base + 6 * k + 6)?; - if r[2] as usize != k || r[3..6] != [0, 0, 0] { + let f16 = r[5] & 1 == 1; + if r[2] as usize != k || r[4] != 0 || !matches!(r[5], 0 | 1 | 3) || (r[3] != 0 && !(f16 && r[3] == r[1])) { return None; } - out.push(r[1] as u32); + out.push(OutParam { register: r[1] as u32, f16, pair: r[5] == 3 }); } Some(out) } @@ -475,6 +491,28 @@ pub fn f16_registers(sig: &[SigElement], first: u32, second: Option, pair: std::iter::once((first, 0)).chain(second.map(|r| (r, width.div_ceil(2)))).collect() } +/// The registers of `exp param N` with the first dword of each (`f16_registers`), and whether +/// they hold packed float16: the console's table, else the N-th distinct register. +pub fn out_param_registers(outputs: &[SigElement], params: Option<&[OutParam]>, n: usize) -> Option<(Vec<(u32, usize)>, bool)> { + match params { + Some(t) => { + let p = t.get(n)?; + if !p.f16 { + return Some((vec![(p.register, 0)], false)); + } + Some((f16_registers(outputs, p.register, None, p.pair, &|r| t.iter().any(|q| q.register == r)), true)) + } + None => param_registers(outputs, true).get(n).map(|&r| (vec![(r, 0)], false)), + } +} + +/// The elements `exp param N` writes (places in `ranked(outputs, true)`), each with the first +/// dword of its register, and whether the param holds packed float16 (`out_param_registers`). +pub fn out_param_elements(outputs: &[SigElement], params: Option<&[OutParam]>, n: usize) -> (Vec<(usize, usize)>, bool) { + let (regs, f16) = out_param_registers(outputs, params, n).unwrap_or_default(); + (regs.iter().flat_map(|&(r, first)| elements_at(outputs, true, r).into_iter().map(move |j| (j, first))).collect(), f16) +} + /// The registers of a float16-packed PS attribute with the first dword of each (None: the /// attribute is not packed). pub fn ps_attribute_f16(ps: &PsInterface, attr: usize) -> Option> { @@ -528,7 +566,7 @@ pub fn ps_slot_attribute(ps: &PsInterface, slot: usize) -> Option { /// The register `exp param N` of a VS writes: the console's table, else the N-th distinct one. pub fn vs_param_register(vs: &VsInterface, n: usize) -> Option { match &vs.params { - Some(t) => t.get(n).copied(), + Some(t) => t.get(n).map(|p| p.register), None => param_registers(&vs.outputs, true).get(n).copied(), } } @@ -579,6 +617,7 @@ pub fn interface(blob: &[u8], sh: &super::xbox::XboxShader, f: &super::xbox::Fss threads, max_vertices: (p.ms_max_vertices as u32).clamp(1, 256), max_primitives: (p.ms_max_primitives as u32).clamp(1, 256), + params: vs_output_table(&f.data), })) } _ => None, @@ -1840,6 +1879,27 @@ mod attribute_tests { assert_eq!(f16_registers(&narrow, 1, None, true, &|r| r == 1), [(1, 0), (2, 1)]); } + /// Float16 params packed the same way in a VS / MS output table (the record shapes of the + /// title's MS): the table parses, the second register of a pair is the next float16 register + /// that starts no param of its own (the record does not name it), and `exp param N` writes + /// the elements of both registers. + #[test] + fn f16_packed_params() { + let sig = f16_sig(); + let mut f = vec![0u8; 0x400]; + f[0x10] = 6; + // VS / MS output records: [6, reg, param, reg, 0, 3]; param 5 is a single float16 (1) + let outs: [[u8; 6]; 6] = [[6, 1, 0, 1, 0, 3], [6, 3, 1, 0, 0, 0], [6, 4, 2, 4, 0, 3], [6, 6, 3, 0, 0, 0], [6, 7, 4, 7, 0, 3], [6, 9, 5, 0, 0, 1]]; + f[0x1DC..0x1DC + 36].copy_from_slice(&outs.concat()); + f[0x1DC + 0xC0] = 6; + let params = vs_output_table(&f).unwrap(); + assert_eq!(params.iter().map(|p| (p.register, p.f16, p.pair)).collect::>(), [(1, true, true), (3, false, false), (4, true, true), (6, false, false), (7, true, true), (9, true, false)]); + let regs = |n: usize| out_param_registers(&sig, Some(¶ms), n); + assert_eq!([regs(0), regs(1), regs(4), regs(5), regs(6)], [Some((vec![(1, 0), (2, 2)], true)), Some((vec![(3, 0)], false)), Some((vec![(7, 0), (8, 2)], true)), Some((vec![(9, 0)], true)), None]); + // elements in `ranked` order: r7 holds two, r8 one + assert_eq!(out_param_elements(&sig, Some(¶ms), 4), (vec![(6, 0), (7, 0), (8, 2)], true)); + } + /// Minecraft's UI vertex shader: an ISG1 input the program never reads (NORMAL0, r1) gets /// no fetch-shader VGPRs – POSITION0 (r2) is read in v8, TEXCOORD0 (r3) in v12. #[test] @@ -1877,7 +1937,7 @@ mod attribute_tests { f[0x10] = 5; f[0x1D4..0x1D4 + 18].copy_from_slice(&[6, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 6, 2, 2, 0, 0, 0]); f[0x1D4 + 0xC0] = 3; - assert_eq!(vs_output_table(&f), Some(vec![0, 1, 2])); + assert_eq!(vs_output_table(&f).map(|t| t.iter().map(|p| p.register).collect::>()), Some(vec![0, 1, 2])); f[0x1D4 + 8] = 7; assert_eq!(vs_output_table(&f), None); } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 3db3df6b01..d7da2fe359 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3568,7 +3568,7 @@ fn gpu_mesh_mode_two_passes() { rw_mask: 0xF, stream: 0, }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0), sig("TEXCOORD", 0, 1)], threads: 128, max_vertices: 128, max_primitives: 128 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0), sig("TEXCOORD", 0, 1)], threads: 128, max_vertices: 128, max_primitives: 128, params: None }; let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None) }; @@ -3646,6 +3646,100 @@ fn gpu_mesh_mode_two_passes() { assert!(px16 == px, "split pass-through draws the same pixels"); } +/// A mesh (NGG) program whose param 0 packs two float16 registers, two components per dword +/// (TEXCOORD1.xy in dword 0, TEXCOORD4.xyzw in dwords 1 and 2 – a retail title's transform +/// programs): the record keeps every component as a float in its own element's slot, the +/// pass-through hands them to the pixel shader by semantic, and the float param after the +/// pair lands in its own register. Before: param 0 went raw into TEXCOORD1 alone and param 1 +/// into TEXCOORD4. +#[test] +fn gpu_mesh_f16_packed_params() { + if !gpu_ready() || !mesh_ready() { + return; + } + use super::{dxc, mesh_passthrough, MsInterface, OutParam, MESH_HEADER}; + let ms = MsInterface { + outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF), el("TEXCOORD", 1, 0, 6, 1, 0x3), el("TEXCOORD", 4, 0, 6, 2, 0xF), el("TEXCOORD", 3, 0, 3, 3, 0xF)], + threads: 128, + max_vertices: 128, + max_primitives: 128, + params: Some(vec![OutParam { register: 1, f16: true, pair: true }, OutParam { register: 3, f16: false, pair: false }]), + }; + let exp = |tgt: u64, en: u64, v: [u64; 4], done: u64| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option) { + ("EXP", "ENC_EXP", vec![("TGT", tgt), ("EN", en), ("VSRC0", v[0]), ("VSRC1", v[1]), ("VSRC2", v[2]), ("VSRC3", v[3]), ("DONE", done)], None) + }; + // as `gpu_mesh_mode_two_passes`: v20 = group, v15 = thread in the group (floats) + let mut list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ + ("S_BFE_U32", "ENC_SOP2", vec![("SDST", 0), ("SSRC0", 3), ("SSRC1", 255)], Some(0x40018)), + ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", 128)], None), + ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", V)], None), + ("V_LSHL_ADD_U32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 0), ("SRC1", 134), ("SRC2", V)], None), + ("V_READFIRSTLANE_B32", "ENC_VOP1", vec![("VDST", 1), ("SRC0", V + 5)], None), + ("S_LSHR_B32", "ENC_SOP2", vec![("SDST", 1), ("SSRC0", 1), ("SSRC1", 135)], None), + ("S_MOV_B32", "ENC_SOP1", vec![("SDST", 124), ("SSRC0", 255)], Some(1 << 12 | 3)), + ("S_SENDMSG", "ENC_SOPP", vec![("SIMM16", 9)], None), + ("S_BARRIER", "ENC_SOPP", vec![], None), + ("V_CMPX_GT_U32", "ENC_VOPC", vec![("SRC0", 131), ("VSRC1", 0)], None), + ("BUFFER_LOAD_DWORDX4", "ENC_MUBUF", vec![("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SOFFSET", 128), ("IDXEN", 1)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 20), ("SRC0", 1)], None), + ("V_ADD_F32", "ENC_VOP2", vec![("VDST", 10), ("SRC0", V + 20), ("VSRC1", 10)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 14), ("SRC0", V + 20)], None), + ("V_CVT_F32_U32", "ENC_VOP1", vec![("VDST", 15), ("SRC0", V)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 16), ("SRC0", 128)], None), + ("V_MOV_B32", "ENC_VOP1", vec![("VDST", 17), ("SRC0", 242)], None), + // halves: v22 = group, v23 = thread, v24 = 0.5, v25 = 2.0 + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 22), ("SRC0", V + 20)], None), + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 23), ("SRC0", V + 15)], None), + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 24), ("SRC0", 240)], None), + ("V_CVT_F16_F32", "ENC_VOP1", vec![("VDST", 25), ("SRC0", 244)], None), + // TEXCOORD1 = (group, thread); TEXCOORD4 = (0.5, group, thread, 2.0) + ("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", 26), ("SRC0", V + 22), ("SRC1", V + 23)], None), + ("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", 27), ("SRC0", V + 24), ("SRC1", V + 22)], None), + ("V_PACK_B32_F16", "ENC_VOP3", vec![("VDST", 28), ("SRC0", V + 23), ("SRC1", V + 25)], None), + ]; + list.push(exp(12, 0xF, [10, 11, 12, 13], 1)); + list.push(exp(32, 0x7, [26, 27, 28, 0], 0)); + list.push(exp(33, 0xF, [14, 15, 16, 17], 0)); + list.push(("S_MOV_B64", "ENC_SOP1", vec![("SDST", 126), ("SSRC0", 193)], None)); + list.push(("V_CMPX_EQ_U32", "ENC_VOPC", vec![("SRC0", 128), ("VSRC1", 0)], None)); + list.push(("V_MOV_B32", "ENC_VOP1", vec![("VDST", 21), ("SRC0", 255)], Some(1 << 10 | 2 << 20))); + list.push(exp(20, 1, [21, 0, 0, 0], 1)); + let refs: Vec<(&str, &str, &[(&str, u64)], Option)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect(); + let code = prog(&refs); + let opt = on_gpu(Options { mode: Mode::Mesh(ms.clone()), wave64: true, ..Default::default() }); + let t = translate(&code, &opt).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let cs = direct_or(&code, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl))); + let pass = mesh_passthrough(&ms); + let msb = dxc::compile(&pass, "main", "ms_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{pass}")); + let ps_src = "struct V { float4 pos : SV_Position; float4 a : TEXCOORD1; float4 b : TEXCOORD4; float4 c : TEXCOORD3; };\nfloat4 main(V v) : SV_Target0 { return float4(v.a.x, v.b.x, v.b.w, v.c.w); }\n"; + let ps = dxc::compile(ps_src, "main", "ps_6_6", &[]).unwrap(); + let mut mem = vec![0u32; 256]; + for (i, (x, y)) in [(-1.0f32, -1.0f32), (-1.0, 1.0), (0.0, -1.0)].iter().enumerate() { + mem[0x40 + 4 * i..0x40 + 4 * i + 4].copy_from_slice(&[f(*x), f(*y), f(0.0), f(1.0)]); + } + let mut sg = vec![0u32; 128]; + sg[16..20].copy_from_slice(&[0x100, 16 << 16, 3, 0]); + let (px, rec) = runner::mesh_draw(&cs, &msb, &ps, 2, ms.record_dwords(), &sg, &mem, 32, [-1.0; 4]).unwrap(); + let (rd, vd) = (ms.record_dwords(), ms.vert_dwords()); + for g in 0..2usize { + let r = &rec[g * rd..(g + 1) * rd]; + assert_eq!((r[0], r[1]), (3, 1), "group {g}: GS_ALLOC_REQ counts"); + for v in 0..3usize { + let b = MESH_HEADER + v * vd; + let at = |k: usize| f32::from_bits(r[b + k]); + let (gf, vf) = (g as f32, v as f32); + assert_eq!([at(4), at(5)], [gf, vf], "group {g} vertex {v}: TEXCOORD1.xy"); + assert_eq!([at(8), at(9), at(10), at(11)], [0.5, gf, vf, 2.0], "group {g} vertex {v}: TEXCOORD4"); + assert_eq!([at(12), at(13), at(14), at(15)], [gf, vf, 0.0, 1.0], "group {g} vertex {v}: TEXCOORD3 (param 1)"); + } + } + let at = |x: usize, y: usize| px[y * 32 + x]; + assert_eq!(at(3, 29), [0.0, 0.5, 2.0, 1.0], "group 0 triangle (left)"); + assert_eq!(at(19, 29), [1.0, 0.5, 2.0, 1.0], "group 1 triangle (right)"); + assert_eq!(at(29, 3), [-1.0; 4], "outside both triangles"); +} + #[test] fn mesh_passthrough_strips_rdna2_edge_flag_bits() { use super::{mesh_passthrough, MsInterface}; @@ -3664,6 +3758,7 @@ fn mesh_passthrough_strips_rdna2_edge_flag_bits() { threads: 128, max_vertices: 128, max_primitives: 128, + params: None, }; let unsplit = mesh_passthrough(&ms); assert!(unsplit.contains("uint3(p & 0x1FFu, (p >> 10) & 0x1FFu, (p >> 20) & 0x1FFu)"), "{unsplit}"); @@ -3705,7 +3800,7 @@ fn mesh_split_accounts_vertex_chunks() { outputs.push(sig("TEXCOORD", 0, k + 1, k)); } outputs.push(sig("SV_ClipDistance", 2, 21, 0)); - let ms = MsInterface { outputs, threads: 128, max_vertices: 128, max_primitives: 128 }; + let ms = MsInterface { outputs, threads: 128, max_vertices: 128, max_primitives: 128, params: None }; let elems = passthrough_elements(&ms, None); assert_eq!(elems, 21); // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit (96 would be 33792 B), so at @@ -3762,7 +3857,7 @@ fn mesh_layout_independent_of_group_count() { } outputs.push(sig("SV_ClipDistance", 2, 21, 0)); // 22 rows * 16 B = 352 B/vertex: 64 accounted vertices fit; 80 declared do not - let ms = MsInterface { outputs, threads: 128, max_vertices: 80, max_primitives: 1 }; + let ms = MsInterface { outputs, threads: 128, max_vertices: 80, max_primitives: 1, params: None }; let elems = passthrough_elements(&ms, None); assert_eq!(elems, 21); // one triangle: its 3 copies fit one compact group, so the dispatch count is 1 @@ -4018,7 +4113,7 @@ fn gpu_mesh_mode_reads_memory_windows() { rw_mask: 0xF, stream: 0, }; - let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 64, max_primitives: 64 }; + let ms = MsInterface { outputs: vec![sig("SV_Position", 1, 0)], threads: 64, max_vertices: 64, max_primitives: 64, params: None }; let list: Vec<(&str, &str, Vec<(&str, u64)>, Option)> = vec![ ("V_MBCNT_LO_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", 128)], None), ("V_MBCNT_HI_U32_B32", "ENC_VOP3", vec![("VDST", 0), ("SRC0", 193), ("SRC1", V)], None), // thread @@ -6998,7 +7093,7 @@ fn far_jumps_are_direct_branches() { /// programs with cross-half operations included; native wave64 and wave32 programs unchanged. #[test] fn mesh_split_wave64_form() { - let ms = super::MsInterface { threads: 128, max_vertices: 64, max_primitives: 64, outputs: vec![] }; + let ms = super::MsInterface { threads: 128, max_vertices: 64, max_primitives: 64, outputs: vec![], params: None }; let lane = prog(&[("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 0), ("SRC0", V)], None)]); let branch = prog(&[("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)], None)]); for code in [&lane, &branch] { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 594a1a8cdc..e050eb2900 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6957,7 +6957,7 @@ pub(super) fn register_two_pass_for_test(pso: usize, kind: &'static str) { compute: 0, compute_rs: 0, mesh_rs: 0, - record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 64, max_vertices: 64, max_primitives: 64 }, + record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 64, max_vertices: 64, max_primitives: 64, params: None }, mesh_groups_per_record: 1, kind, }), @@ -9937,7 +9937,7 @@ mod mesh_stream_tests { let make_tp = || crate::gpu::recomp::pso::TwoPass { cs: vec![0; 16], ms: vec![0; 16], - record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1 }, + record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1, params: None }, mesh_groups_per_record: 1, samplers: vec![sampler], }; From b67375b6a1a647aa0f1d04f7e1fb697651b6a1d3 Mon Sep 17 00:00:00 2001 From: Lino Emmenegger Date: Wed, 25 Nov 2026 22:03:47 +0100 Subject: [PATCH 156/258] Recompiler: scratch SADDR 0x7F addresses the offset alone (ST form) RDNA2 scratch_* has three address forms, chosen by SADDR alone: an SGPR is SS (SGPR + offset), NULL (0x7D) is SV (VADDR + offset) and 0x7F (EXEC_HI) is ST (the offset alone). There is no SGPR + VGPR form and no SVE bit on RDNA2; both came with GFX11 / GFX940. This is how LLVM encodes GFX10 scratch (FLAT_Real_gfx10 sets Inst{54-48} to EXEC_HI for a scratch op without vaddr and to SGPR_NULL otherwise, and Inst{55} to 0), and its gfx1030 MC tests encode `scratch_load_dword v1, off, off` with byte 6 = 0x7f. Both lowerings (direct DXIL lower_mem.rs and the HLSL emitter) took 0x7F for the SV form and added ADDR's VGPR, so an ST access went to a per-lane address that its value happened to hold. They now use 0 as the base for 0x7F, so ADDR is read only for 0x7D. Issue #2400 proposed checking an SVE bit and adding SGPR + VGPR. The RDNA2 ENC_FLAT_SCRATCH spec has no SVE field (bit 55 is not decoded), so that half does not apply; the ST case it describes is real and is the one fixed here. Tests: an HLSL text check of the three forms and a direct DXIL check that ST and SS containers do not change with ADDR while SV ones do (both fail without the fix), a GPU test of the three forms, and the existing scratch GPU test now encodes the SV form it describes. Fixes #2400 Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/core_tests.rs | 22 +++++++++ crates/xcl/src/gpu/dxil/lower_mem.rs | 9 +++- crates/xcl/src/gpu/recomp/emit.rs | 11 +++-- crates/xcl/src/gpu/recomp/tests.rs | 71 +++++++++++++++++++++++++-- 4 files changed, 104 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index fdb27fbf29..8ee7fd4cea 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -1087,3 +1087,25 @@ fn raw_loads_in_root_windows_respect_exec_and_bounds() { } } } + +/// scratch_* on RDNA2: SADDR 0x7F (EXEC_HI) is the ST form (the offset alone) and an SGPR the +/// SS form, neither reads ADDR; NULL (0x7D) is SV, VADDR + offset. A program differing only +/// in ADDR translates to the same container exactly when ADDR is not read. +#[test] +fn scratch_reads_addr_only_in_the_sv_form() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let kernel = |saddr: u64, addr: u64| { + let code = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 135)], None), // v2 = 7 + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 3), ("SRC0", 137)], None), // v3 = 9 + ("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", addr), ("DATA", 0), ("SADDR", saddr), ("OFFSET", 16)], None), + ("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 4), ("ADDR", addr), ("SADDR", saddr), ("OFFSET", 20)], None), + ]); + translate(&code, ko).unwrap_or_else(|e| panic!("SADDR {saddr:#x} ADDR v{addr}: {e}")) + }; + for (saddr, form) in [(0x7F, "ST"), (4, "SS")] { + assert!(kernel(saddr, 2) == kernel(saddr, 3), "{form} (SADDR {saddr:#x}) must not read ADDR"); + } + assert!(kernel(0x7D, 2) != kernel(0x7D, 3), "SV (SADDR 0x7d) addresses VADDR + offset"); + assert!(kernel(0x7F, 2) != kernel(0x7D, 2), "ST is not the SV form"); +} diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 8e0bc93ba6..950d327a75 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -2466,8 +2466,13 @@ impl Lw { } fn scratch(&mut self, d: &Decoded, op: &str) -> LResult<()> { - let saddr = Self::fv(d, "SADDR"); - let base = if saddr != 0x7D && saddr != 0x7F { self.sreg(saddr) } else { self.vreg(Self::fv(d, "ADDR")) }; + // RDNA2 has no SGPR + VGPR form (no SVE bit): SADDR 0x7F (EXEC_HI) is the ST form, + // the offset alone; NULL (0x7D) is SV, VADDR + offset; an SGPR is SS, SGPR + offset + let base = match Self::fv(d, "SADDR") { + 0x7F => self.c(0), + 0x7D => self.vreg(Self::fv(d, "ADDR")), + s => self.sreg(s), + }; let raw = Self::fv(d, "OFFSET") as u32; let off = (((raw << 20) as i32) >> 20) as u32; let a = self.addc(base, off); diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 150525a6c2..f80146e78e 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -4491,12 +4491,17 @@ impl Em { Ok(()) } - /// scratch_*: per-lane private memory (`xcl_scratch`); address = SADDR or VADDR + offset. + /// scratch_*: per-lane private memory (`xcl_scratch`); address = SADDR, VADDR or 0, + offset. fn scratch(&mut self, d: &Decoded, op: &str) -> Result<(), &'static str> { let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0); self.uses_scratch = true; - let saddr = f("SADDR"); - let base = if saddr != 0x7D && saddr != 0x7F { self.sreg(saddr) } else { self.vreg(f("ADDR")) }; + // RDNA2 has no SGPR + VGPR form (no SVE bit): SADDR 0x7F (EXEC_HI) is the ST form, + // the offset alone; NULL (0x7D) is SV, VADDR + offset; an SGPR is SS, SGPR + offset + let base = match f("SADDR") { + 0x7F => "0u".to_string(), + 0x7D => self.vreg(f("ADDR")), + s => self.sreg(s), + }; let raw = f("OFFSET") as u32; let off = (((raw << 20) as i32) >> 20) as u32; let t = self.t(); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index d7da2fe359..b0ef053ff8 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3302,6 +3302,69 @@ fn global_dword_addtid_address_is_saddr_plus_4_per_lane() { } } +/// scratch_* (ENC_FLAT_SCRATCH) has three address forms on RDNA2 and no SGPR + VGPR one: +/// SADDR 0x7F (EXEC_HI) is ST, the offset alone; NULL (0x7D) is SV, VADDR + offset; an SGPR +/// is SS, SGPR + offset. ADDR is read only in the SV form. +#[test] +fn scratch_address_forms_follow_saddr() { + let scr = |n: &'static str, f: &[(&str, u64)]| encode(n, "ENC_FLAT_SCRATCH", f, None).unwrap(); + let mut code = Vec::new(); + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 5), ("SADDR", 0x7F), ("OFFSET", 16)])); + code.extend(scr("SCRATCH_LOAD_DWORD", &[("VDST", 7), ("ADDR", 2), ("SADDR", 0x7D), ("OFFSET", 0xFFC)])); + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 5), ("SADDR", 4), ("OFFSET", 8)])); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let t = translate(&code, &Options::default()).unwrap(); + assert!(t.complete(), "{:?}\n{}", t.unsupported_why, t.hlsl); + assert!(t.hlsl.contains("uint t1_a = 0u + 0x00000010u;"), "ST: the offset alone\n{}", t.hlsl); + assert!(t.hlsl.contains("uint t2_a = v2 + 0xFFFFFFFCu;"), "SV: VADDR + the signed offset\n{}", t.hlsl); + assert!(t.hlsl.contains("uint t3_a = s4 + 0x00000008u;"), "SS: the SGPR + offset\n{}", t.hlsl); + if super::dxc::location().is_ok() { + super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl)); + direct_check(&code, &Options::default()); + } +} + +/// On hardware: the ST scratch form addresses the offset alone whatever ADDR holds, SS the +/// SGPR + offset, and SV the lane's VADDR + offset. +#[test] +fn gpu_scratch_address_forms() { + if !gpu_ready() { + return; + } + let scr = |n: &'static str, f: &[(&str, u64)]| encode(n, "ENC_FLAT_SCRATCH", f, None).unwrap_or_else(|x| panic!("{n}: {x}")); + let mut code = Vec::new(); + // [16] = 0x55 (SV, v3 = 0), then ST writes [16] (ADDR = v2 is not read), SV reads it back + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 3), ("DATA", 9), ("SADDR", 0x7D), ("OFFSET", 16)])); + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 5), ("SADDR", 0x7F), ("OFFSET", 16)])); + code.extend(scr("SCRATCH_LOAD_DWORD", &[("VDST", 20), ("ADDR", 3), ("SADDR", 0x7D), ("OFFSET", 16)])); + // SS: s4 (8) + 32 = [40], read back through SV + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 6), ("SADDR", 4), ("OFFSET", 32)])); + code.extend(scr("SCRATCH_LOAD_DWORD", &[("VDST", 21), ("ADDR", 3), ("SADDR", 0x7D), ("OFFSET", 40)])); + // [0x100] = 0x55 (ST), SV writes [0x100 + v2], ST reads [0x100]: lanes with v2 = 0 see the SV store + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 9), ("SADDR", 0x7F), ("OFFSET", 0x100)])); + code.extend(scr("SCRATCH_STORE_DWORD", &[("ADDR", 2), ("DATA", 7), ("SADDR", 0x7D), ("OFFSET", 0x100)])); + code.extend(scr("SCRATCH_LOAD_DWORD", &[("VDST", 22), ("ADDR", 2), ("SADDR", 0x7F), ("OFFSET", 0x100)])); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut st = KernelState::default(); + st.sgpr[4] = 8; + for (l, r) in st.vgpr.iter_mut().enumerate() { + let l32 = l as u32; + r[2] = 4 * (l32 % 4); + r[3] = 0; + r[5] = 0xA0 + l32; + r[6] = 0xB0 + l32; + r[7] = 0xC0 + l32; + r[9] = 0x55; + } + let r = runner::run_code(&code, &st, &[0u32; 16]).unwrap(); + for (l, v) in r.vgpr.iter().enumerate().take(64) { + let l32 = l as u32; + assert_eq!(v[20], 0xA0 + l32, "lane {l}: ST store at the offset alone"); + assert_eq!(v[21], 0xB0 + l32, "lane {l}: SS store at s4 + offset"); + assert_eq!(v[22], if l % 4 == 0 { 0xC0 + l32 } else { 0x55 }, "lane {l}: SV store at v2 + offset, ST load at the offset"); + } +} + /// On hardware: every lane touches its own dword (EA = SADDR + 4·lane + OFFSET), the /// "off" SADDR sentinel gives a zero base and the signed offset can point below the base. #[test] @@ -5839,10 +5902,10 @@ fn gpu_more_atomics_sub_dword_scratch_valu() { code.extend(glbl("GLOBAL_STORE_SHORT_D16_HI", &[("ADDR", 2), ("DATA", 62), ("SADDR", 2), ("OFFSET", 0x100)])); code.extend(glbl("GLOBAL_LOAD_USHORT", &[("VDST", 63), ("ADDR", 2), ("SADDR", 2), ("OFFSET", 0x100)])); // scratch (per lane): a dword at 2 · lane + 16, a byte at 2 · lane + 40 - code.extend(enc("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 11), ("SADDR", 0x7F), ("OFFSET", 16)])); - code.extend(enc("SCRATCH_STORE_BYTE", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 36), ("SADDR", 0x7F), ("OFFSET", 40)])); - code.extend(enc("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 64), ("ADDR", 2), ("SADDR", 0x7F), ("OFFSET", 16)])); - code.extend(enc("SCRATCH_LOAD_UBYTE", "ENC_FLAT_SCRATCH", &[("VDST", 65), ("ADDR", 2), ("SADDR", 0x7F), ("OFFSET", 40)])); + code.extend(enc("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 11), ("SADDR", 0x7D), ("OFFSET", 16)])); + code.extend(enc("SCRATCH_STORE_BYTE", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 36), ("SADDR", 0x7D), ("OFFSET", 40)])); + code.extend(enc("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 64), ("ADDR", 2), ("SADDR", 0x7D), ("OFFSET", 16)])); + code.extend(enc("SCRATCH_LOAD_UBYTE", "ENC_FLAT_SCRATCH", &[("VDST", 65), ("ADDR", 2), ("SADDR", 0x7D), ("OFFSET", 40)])); // VALU let vv = |n: u64| V + n; code.extend(vop3("V_SAD_U8", &[("VDST", 66), ("SRC0", vv(22)), ("SRC1", vv(23)), ("SRC2", vv(24))])); From 4ae5668f910e766ef4e2e7bd18ce3238cc9cf30c Mon Sep 17 00:00:00 2001 From: Ramon Victor Cardoso Date: Wed, 25 Nov 2026 20:00:54 -0300 Subject: [PATCH 157/258] Recompiler: lower 32-bit VALU add/sub with carry without i64 in direct DXIL --- crates/xcl/src/gpu/dxil/lower_valu.rs | 126 ++++++++++++++++++++++++-- 1 file changed, 118 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index 9030698381..c57ccb28c4 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -1041,16 +1041,19 @@ impl Lw { let cb = self.lane_of(l, h); let cin = self.u(cb); let (x, y) = if name == "v_subrev_co_ci_u32" { (b, a) } else { (a, b) }; - let (x6, y6, c6) = (self.zext64(x), self.zext64(y), self.zext64(cin)); - let w = if name == "v_add_co_ci_u32" { - let s = self.add(x6, y6); - self.add(s, c6) + let (t, carry) = if name == "v_add_co_ci_u32" { + let t0 = self.add(x, y); + let t = self.add(t0, cin); + let c0 = self.cmp(Pred::ULt, t0, x); + let c1 = self.cmp(Pred::ULt, t, t0); + (t, self.lor(c0, c1)) } else { - let s = self.sub(x6, y6); - self.sub(s, c6) + let t0 = self.sub(x, y); + let t = self.sub(t0, cin); + let c0 = self.cmp(Pred::ULt, x, y); + let c1 = self.cmp(Pred::ULt, t0, cin); + (t, self.lor(c0, c1)) }; - let (t, hi) = self.unpack64(w); - let carry = self.nz(hi); let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); self.write_mask(&sdst, carry); self.vwrite(d, &dst, t); @@ -1482,3 +1485,110 @@ impl Lw { } } } + +#[cfg(test)] +mod valu_carry_tests { + use super::super::kernel::{self, KernelOptions}; + use super::super::validate; + use crate::gpu::rdna2::encode; + use crate::gpu::recomp::runner; + + #[test] + fn valu_carry_ops_avoid_i64_and_match_gpu() { + let mut code = Vec::new(); + for &(name, enc, fields) in &[ + // v2 = v0 + v1 + cin(s0), carry -> s2 + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2u64), ("SDST", 2), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)][..]), + // v3 = v0 - v1 - cin(s0), borrow -> s4 + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 3), ("SDST", 4), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)]), + // v4 = v1 - v0 - cin(s0), borrow -> s6 + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 6), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)]), + ] { + code.extend(encode(name, enc, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let dxil = kernel::translate(&code, ko).expect("translate valu carry ops"); + validate::validate(&dxil).expect("validate valu carry ops"); + let dis = validate::disassemble(&dxil).expect("disasm valu carry ops"); + assert!(!dis.contains("64-Bit integer"), "32-bit VALU carry ops must not require Int64Ops:\n{dis}"); + assert!(!dis.contains("zext i32"), "32-bit VALU carry ops must not widen to i64:\n{dis}"); + + if !matches!(runner::wave32_supported(), Ok(true)) { + runner::skip_test("no wave32"); + return; + } + // Boundary triples (x, y, cin) covering overflow/underflow with and without carry/borrow-in. + let cases: [(u32, u32, bool); 32] = [ + (0, 0, false), + (0, 0, true), + (0, 1, false), + (0, 1, true), + (1, 0, false), + (1, 0, true), + (1, 1, false), + (1, 1, true), + (u32::MAX, 0, false), + (u32::MAX, 0, true), + (u32::MAX, 1, false), + (u32::MAX, 1, true), + (0, u32::MAX, false), + (0, u32::MAX, true), + (u32::MAX, u32::MAX, false), + (u32::MAX, u32::MAX, true), + (u32::MAX - 1, 1, false), + (u32::MAX - 1, 1, true), + (0x7FFF_FFFF, 0x8000_0000, false), + (0x7FFF_FFFF, 0x8000_0000, true), + (0x8000_0000, 0x8000_0000, false), + (0x8000_0000, 0x8000_0000, true), + (0x8000_0000, 0x7FFF_FFFF, false), + (0x8000_0000, 0x7FFF_FFFF, true), + (2, 1, false), + (2, 1, true), + (1, 2, false), + (1, 2, true), + (0x1234_5678, 0xEDCB_A987, false), + (0x1234_5678, 0xEDCB_A987, true), + (0x1234_5678, 0xEDCB_A988, false), + (0x1234_5678, 0xEDCB_A988, true), + ]; + let mut st = runner::KernelState::default(); + let mut cin_mask = 0u32; + for (l, &(x, y, cin)) in cases.iter().enumerate() { + st.vgpr[l][0] = x; + st.vgpr[l][1] = y; + if cin { + cin_mask |= 1u32 << l; + } + } + st.sgpr[0] = cin_mask; + let r = runner::run(&dxil, &st, &[]).expect("GPU run valu carry ops"); + + let mut want_add_c = 0u32; + let mut want_sub_b = 0u32; + let mut want_subrev_b = 0u32; + for (l, &(x, y, cin)) in cases.iter().enumerate() { + let c = cin as u64; + let add64 = x as u64 + y as u64 + c; + assert_eq!(r.vgpr[l][2], add64 as u32, "add_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (add64 >> 32) != 0 { + want_add_c |= 1u32 << l; + } + let sub64 = (x as u64).wrapping_sub(y as u64).wrapping_sub(c); + assert_eq!(r.vgpr[l][3], sub64 as u32, "sub_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (sub64 >> 32) != 0 { + want_sub_b |= 1u32 << l; + } + let subrev64 = (y as u64).wrapping_sub(x as u64).wrapping_sub(c); + assert_eq!(r.vgpr[l][4], subrev64 as u32, "subrev_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (subrev64 >> 32) != 0 { + want_subrev_b |= 1u32 << l; + } + } + assert_eq!(r.sgpr[2], want_add_c, "add_co_ci carry-out mask"); + assert_eq!(r.sgpr[4], want_sub_b, "sub_co_ci borrow-out mask"); + assert_eq!(r.sgpr[6], want_subrev_b, "subrev_co_ci borrow-out mask"); + } +} From 71fccb19cb42623e6422cc8c7f41833693d9176d Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:42:54 +0100 Subject: [PATCH 158/258] DXIL: narrow post-DCE rawBufferLoad masks to highest extracted component After DCE removes unused components from a multi-dword rawBufferLoad (e.g. a 4-dword load whose y/z/w extracts were dead), narrowing the contiguous DXIL mask (15/7/3 -> 1/3/7) based on the highest live ExtractValue index (< 4, never touching loads whose residency status index 4 or whole struct escapes) reduces memory traffic and avoids trailing OOB byte reads. Also supplies early_depth: false in the cherry-picked #2513 f16 PS interface test initializer. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/dxil/core_tests.rs | 1 + crates/xcl/src/gpu/dxil/module/opt.rs | 78 +++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 8ee7fd4cea..9f7d5f220a 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -213,6 +213,7 @@ fn f16_packed_attributes_interpolate_per_half() { PsAttr { kind: 6, register: 1, mask: 3, flat: false, f16: true, pair: Some(2) }, PsAttr { kind: 6, register: 3, mask: 0xF, flat: false, f16: false, pair: None }, ]), + early_depth: false, }; // a PS returning four values: Some((dword, high)) of attribute 0, None: attr1[k] as f32 let ps_code = |sel: [Option<(u64, u64)>; 4]| { diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 37e39f8160..1603f8b5ff 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -791,6 +791,56 @@ impl Module { changed } + /// Post-DCE narrowing of `dx.op.rawBufferLoad.*` component masks: if all surviving uses of a + /// load are `ExtractValue` on components `0..=max_c` (never residency status index `4` and + /// never passed whole), narrow its contiguous DXIL mask (`15`/`7`/`3`) to `(1 << (max_c + 1)) - 1`. + fn narrow_raw_buffer_loads(&mut self, order: &[u32]) -> bool { + let mut max_comp = vec![-1i8; self.insts.len()]; + for &b in order { + for &i in &self.blocks[b as usize] { + match &self.insts[i as usize].op { + Op::Extract(Value::Inst(j), idx) if *idx < 4 => { + let slot = &mut max_comp[*j as usize]; + if *slot < 99 { + *slot = (*slot).max(*idx as i8); + } + } + other => other.for_each_operand(|v| { + if let Value::Inst(j) = v { + max_comp[j as usize] = 99; + } + }), + } + } + } + let mut changed = false; + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k] as usize; + let mc = max_comp[i]; + if !(0..4).contains(&mc) { + continue; + } + let (mask_ty, cur_mask) = match &self.insts[i].op { + Op::Call(f, args) if args.len() == 6 && self.funcs[*f as usize].name.starts_with("dx.op.rawBufferLoad.") => { + let Some(m) = self.const_u64(args[4]) else { continue }; + (self.value_ty(args[4]), m) + } + _ => continue, + }; + let new_mask = (1u64 << (mc as u32 + 1)) - 1; + if matches!(cur_mask, 3 | 7 | 15) && new_mask < cur_mask { + let c = self.const_int(mask_ty, new_mask); + if let Op::Call(_, args) = &mut self.insts[i].op { + args[4] = c; + changed = true; + } + } + } + } + changed + } + /// Removes immediately redundant `dx.op.barrier` calls within a basic block when no /// memory-visible side effect occurred since an equally-strong or stronger barrier. fn elim_redundant_barriers(&mut self, order: &[u32]) -> bool { @@ -1227,6 +1277,10 @@ impl Module { b.retain(|&i| live[i as usize]); } + if !skip("mask") && self.narrow_raw_buffer_loads(&order) { + iter_changed = true; + } + if !skip("merge") && self.simplify_cfg() { iter_changed = true; } @@ -2215,4 +2269,28 @@ mod tests { .count(); assert_eq!(barriers, 1, "adjacent covered barriers must collapse to one"); } + + #[test] + fn raw_buffer_load_mask_narrowed_to_highest_extracted_component() { + use crate::gpu::dxil::container::Stage; + use crate::gpu::dxil::shader::Shader; + let mut s = Shader::new(Stage::Compute, (6, 6)); + let z = s.m.i32c(0); + let uav = s.heap_raw_buffer_uav(z, false); + let vals = s.raw_load(uav, z, 15); + // Only component 0 is used; components 1..3 are dead -> mask must narrow from 15 to 1. + s.raw_store(uav, z, &[vals[0]]); + s.m.ret(); + + s.m.optimize(); + + let load_masks: Vec = s.m.blocks[0] + .iter() + .filter_map(|&i| match &s.m.insts[i as usize].op { + Op::Call(f, args) if s.m.funcs[*f as usize].name.starts_with("dx.op.rawBufferLoad.") => s.m.const_u64(args[4]), + _ => None, + }) + .collect(); + assert_eq!(load_masks, vec![1], "rawBufferLoad mask 15 must narrow to 1 when only x is live"); + } } From bf02341f609f497d87ac1938b052077c74f9dc0f Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:45:09 +0100 Subject: [PATCH 159/258] D3D12.X: create sparse readback jobs with DIRECT list type to match sparse queue sparse::State::queue is created as D3D12_COMMAND_LIST_TYPE_DIRECT, but take_readback_job created its pooled command allocator and command list as D3D12_COMMAND_LIST_TYPE_COPY. Submitting a COPY list to a DIRECT queue removed the device immediately with DXGI_ERROR_INVALID_CALL (0x887a0001). Match s.queue by creating ReadbackJob allocators and lists as D3D12_COMMAND_LIST_TYPE_DIRECT. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/sparse.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 820f820b8b..ef0ad8d73c 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1396,8 +1396,8 @@ unsafe fn take_readback_job(dev: &ID3D12Device, need: usize) -> Option Date: Thu, 26 Nov 2026 00:46:19 +0100 Subject: [PATCH 160/258] d3d12x: create ReadbackJob command list as DIRECT to match sparse queue sparse::State::queue is a D3D12_COMMAND_LIST_TYPE_DIRECT queue, but take_readback_job created its pooled allocator and command list as D3D12_COMMAND_LIST_TYPE_COPY. Submitting a COPY command list to a DIRECT queue immediately triggers DXGI_ERROR_INVALID_CALL (0x887a0001). Create ReadbackJob allocators/lists as D3D12_COMMAND_LIST_TYPE_DIRECT matching State::queue, and skip returning/resetting a ReadbackJob if its fence wait times out so an in-flight allocator is never reused early. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/sparse.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index ef0ad8d73c..638aaaa6bc 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1510,6 +1510,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { let mut idx = 0usize; let mut sub_off = 0usize; let mut pending: Vec<(usize, usize, usize)> = Vec::new(); + let mut job_idle = true; while idx < spans.len() { let mut used = 0usize; pending.clear(); @@ -1553,6 +1554,8 @@ pub unsafe fn readback_now(va: usize, len: usize) { wait_target.1, wait_target.0.GetCompletedValue() ); + job_idle = false; + break; } } // 3. Copy only still-committed non-hole bytes into host memory and sync `sent` hashes. @@ -1578,7 +1581,9 @@ pub unsafe fn readback_now(va: usize, len: usize) { } s.reclaim_ring(); } - return_readback_job(job); + if job_idle { + return_readback_job(job); + } } /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that From 02ca14f36a468f3232a28e6c85a487ec7249473c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:54:19 +0100 Subject: [PATCH 161/258] d3d12x: indirect draw caps, sharded bind state, stack io, and bitset sync Implement indirect Draw/DrawIndexed safety caps (#408) and eliminate per-draw CPU lock contention and heap allocations across command-list recording and descriptor lookups (#395): - Indirect draw caps (device_x.rs, bind.rs): track Draw/DrawIndexed command signatures in DRAW_SIGS (RwLock) and guard indirect draw argument buffers via hoisted PRELUDE_DRAW_GUARD_* (or inline GUARD_DRAW_ARGS_* when prelude hoisting is blocked), zeroing any record with verts == 0, instances == 0, verts >= 2^23 (8,388,608), or verts * instances > 2^26 (67,108,864) using overflow-safe u32 arithmetic. Opt-out via XCL_INDIRECT_DRAW_GUARD=0 or XCL_INDIRECT_GUARD=0. Indirect dispatch guards already enforce <= 2^22 total groups with X > 65,535 folding into Y. - Lock contention & per-stage bind cache (bind.rs, list_x.rs): - Shard bind::STATES across 64 Mutex shards and switch command signature tables (ROOT_SIGNATURES, DISPATCH_SIGNATURES, DISPATCH_ONLY, DISPATCH_MESH_SIGS, DRAW_SIGS) and list_x::MIRRORS to RwLock so parallel recording threads do not serialize. - Zero-allocation stack [u32; KERNEL_SGPRS] io builders (fill_io_gfx, fill_io_compute, fill_io_two_pass), zero-allocation little-endian Set*Root32BitConstants, reusable dummy_table_p when all root args fit inline, and idempotent Set*RootSignature preserving io_cache and Vec capacity. - Cache per-list heaps_ensured, lazily cached vram_io_dev, and pso_abi_cache (skipping repeated pso_async/real/list_x/GLOBAL lookups on consecutive draws with the same PSO). - Fix list_x::skip_redundant_pso_bind so bind_abi re-binding an already-active resolved PC PSO hits the cache instead of re-emitting SetPipelineState + DRED markers on every async PSO. - Reusable dirty-page bitset & descriptor lookup (list_x.rs, console_heap.rs, real.rs): - Replace per-draw Vec in list_x::copy_written with a reusable thread-local Vec bitset and word-wise run scanning. - Keep console_heap::HEAPS sorted for O(log N) partition_point lookups, add single-lock slot_pair for copy_console_slots, zero-refcount global_*_heap_raw accessors, and smallest_failed allocation short-circuiting on full shared heaps. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 981 ++++++++++++++++++---- crates/xcl/src/hle/d3d12x/console_heap.rs | 109 ++- crates/xcl/src/hle/d3d12x/device_x.rs | 12 + crates/xcl/src/hle/d3d12x/list_x.rs | 197 +++-- crates/xcl/src/hle/d3d12x/real.rs | 4 +- 5 files changed, 1052 insertions(+), 251 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 968ca2c73b..4ddeeaa67c 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -11,7 +11,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -116,6 +116,35 @@ struct PreludeScaleJob { cnt_off: u32, } +#[derive(Clone, Copy, Debug)] +struct PreludeDrawJob { + buf_idx: usize, + dst_off: u32, + count: u32, + stride: u32, + draw_offset: u32, + src_win: u32, + src_off: u32, +} + +/// Cached free-threaded `ID3D12Device` wrapper for `State::vram_io_dev`. +#[derive(Clone)] +struct CachedIoDev(ID3D12Device); + +unsafe impl Send for CachedIoDev {} + +/// Cached resolved ABI metadata for the currently bound translated pipeline on a command list, +/// avoiding repeated global `pso_async`/`real` map lookups across consecutive draws/dispatches +/// using the same pipeline. +#[derive(Clone, Copy, Debug)] +struct CachedPsoAbi { + query_pso: usize, + real_pso: usize, + rs_raw: usize, + user_sgprs: Option, + is_gfx: bool, +} + type PreludeEntry = (ID3D12CommandAllocator, ID3D12GraphicsCommandList, usize, i32); /// Paired persistently-mapped `UPLOAD` slab and L1 VRAM `DEFAULT` (`ALLOW_UNORDERED_ACCESS`) slab @@ -180,6 +209,7 @@ struct State { prelude_bufs: Vec, prelude_guards: Vec, prelude_scales: Vec, + prelude_draws: Vec, prelude_owned: Option, prelude_built: Option, /// true after an `INDIRECT_ARGUMENT` transition has ordered prior writes on this list and @@ -190,6 +220,16 @@ struct State { uma_windows: Option>, /// reusable zeroed 256-byte `u1` (`res`) slot in this recording's UMA arena dummy_res_va: u64, + /// reusable 16-byte UMA root-argument table slot for draws/dispatches whose arguments fit + /// completely inline in user SGPRs (`tail.is_empty()`) + dummy_table_p: usize, + /// true once `list_x::ensure_view_heap` confirmed all required shared heaps are bound on this + /// list (invalidated on `Reset`, `ClearState`, split, `SetDescriptorHeaps`, or internal pass) + heaps_ensured: bool, + /// cached resolved ABI metadata for the active translated PSO on this list + pso_abi_cache: Option, + /// lazily cached `vram_io_device(this)` result for this recording + vram_io_dev: Option>, /// tracked PC ABI root bindings for state-diffing pc_abi_gfx: AbiBound, pc_abi_cs: AbiBound, @@ -440,7 +480,15 @@ unsafe fn alloc_vram_io_in(io_blocks: &mut Vec, allocator: usize, prelu Some(va) } -static STATES: Mutex>> = Mutex::new(None); +/// 64-way sharded per-list bind state map so parallel recording threads do not contend on a +/// single global mutex across every root-argument update, draw, and dispatch. +const STATE_SHARDS: usize = 64; +static STATES: [Mutex>>; STATE_SHARDS] = [const { Mutex::new(None) }; STATE_SHARDS]; + +#[inline] +fn state_shard(list: usize) -> usize { + ((list >> 6) ^ (list >> 16)) & (STATE_SHARDS - 1) +} /// draws / dispatches of console code: with a translated pipeline, skipped, with a PC one static COUNTS: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; @@ -470,7 +518,8 @@ fn count(k: usize) { } fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { - f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default()) + let key = list as usize; + f(STATES[state_shard(key)].lock().unwrap().get_or_insert_with(HashMap::new).entry(key).or_default()) } /// Note that the active recording segment issued a GPU buffer write or cross-queue fence wait: @@ -537,6 +586,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.prelude_bufs.clear(); s.prelude_guards.clear(); s.prelude_scales.clear(); + s.prelude_draws.clear(); let prelude = s.prelude_owned.take(); s.prelude_built = None; s.inline_guard = None; @@ -545,6 +595,10 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.arg_order_clean = false; s.uma_windows = None; s.dummy_res_va = 0; + s.dummy_table_p = 0; + s.heaps_ensured = false; + s.pso_abi_cache = None; + s.vram_io_dev = None; s.pc_abi_gfx = AbiBound::default(); s.pc_abi_cs = AbiBound::default(); s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); @@ -579,6 +633,8 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { s.rs_gfx = 0; s.heaps = [0; 2]; s.rs_cs = 0; + s.heaps_ensured = false; + s.pso_abi_cache = None; s.pc_abi_gfx = AbiBound::default(); s.pc_abi_cs = AbiBound::default(); s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); @@ -608,10 +664,12 @@ pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { s.prelude_bufs.clear(); s.prelude_guards.clear(); s.prelude_scales.clear(); + s.prelude_draws.clear(); let prelude = s.prelude_owned.take(); s.prelude_built = None; s.inline_guard = None; s.dummy_res_va = 0; + s.dummy_table_p = 0; s.io_cache_gfx = None; s.io_cache_cs = None; s.io_cache_tp_cs = None; @@ -659,6 +717,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.prelude_bufs.clear(); s.prelude_guards.clear(); s.prelude_scales.clear(); + s.prelude_draws.clear(); let prelude = s.prelude_owned.take(); s.prelude_built = None; s.inline_guard = None; @@ -667,6 +726,10 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.arg_order_clean = false; s.uma_windows = None; s.dummy_res_va = 0; + s.dummy_table_p = 0; + s.heaps_ensured = false; + s.pso_abi_cache = None; + s.vram_io_dev = None; s.pc_abi_gfx = AbiBound::default(); s.pc_abi_cs = AbiBound::default(); s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); @@ -708,7 +771,8 @@ pub(super) fn pass_arena(from: *mut c_void, to: *mut c_void) { /// The list is gone. pub(super) fn forget(list: *mut c_void) { - if let Some(mut s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { + let key = list as usize; + if let Some(mut s) = STATES[state_shard(key)].lock().unwrap().as_mut().and_then(|m| m.remove(&key)) { console_list::hold_until_reset(s.allocator, s.uma); if let Some(b) = s.res_buf.take() { s.res_retired.push(b); @@ -724,6 +788,7 @@ pub(crate) fn seed_reset_state_for_test(list: *mut c_void, allocator: usize, pso with(list, |s| { s.allocator = allocator; s.pso = pso; + s.pso_abi_cache = None; s.layout = Some(Arc::new(Layout::default())); s.args = vec![1, 2, 3, 4]; s.layout_gfx = Some(Arc::new(Layout::default())); @@ -739,7 +804,8 @@ pub(crate) fn reset_state_for_test(list: *mut c_void) -> (usize, usize, Vec, #[cfg(test)] pub(crate) fn remove_state_for_test(list: *mut c_void) { - STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))); + let key = list as usize; + STATES[state_shard(key)].lock().unwrap().as_mut().and_then(|m| m.remove(&key)); } /// SetDescriptorHeaps: the console addresses of `heaps`, for shaders that index them themselves @@ -750,6 +816,7 @@ pub(super) fn set_heaps(list: *mut c_void, heaps: &[usize]) { bases[sampler as usize] = base; } with(list, |s| { + s.heaps_ensured = false; if s.heaps != bases { s.heaps = bases; s.args_gen_gfx = s.args_gen_gfx.wrapping_add(1); @@ -799,8 +866,14 @@ pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_vo with(this, |s| { // the same root signature again keeps the bound arguments (D3D12: only a different // one invalidates them) - if !console_list::same_layout(&s.layout_gfx, &layout) { - s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + let same = console_list::same_layout(&s.layout_gfx, &layout); + if same && s.rs_gfx == rs as usize { + return; + } + if !same { + let size = layout.as_ref().map_or(0, |l| l.size as usize); + s.args_gfx.clear(); + s.args_gfx.resize(size, 0); } s.layout_gfx = layout; s.rs_gfx = rs as usize; @@ -823,9 +896,14 @@ pub(super) unsafe extern "system" fn set_graphics_root_constant(this: *mut c_voi /// #40 SetGraphicsRoot32BitConstants (PC #36) pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { - if !data.is_null() { - let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); - put_in(this, true, i, offset, &bytes); + if !data.is_null() && n > 0 { + #[cfg(target_endian = "little")] + let bytes = std::slice::from_raw_parts(data.cast::(), (n as usize).saturating_mul(4)); + #[cfg(not(target_endian = "little"))] + let bytes_vec: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); + #[cfg(not(target_endian = "little"))] + let bytes = bytes_vec.as_slice(); + put_in(this, true, i, offset, bytes); } } @@ -890,7 +968,7 @@ fn note_address(va: u64) { } /// command signatures that change root arguments (they need the title's root signature) -static ROOT_SIGNATURES: Mutex>> = Mutex::new(None); +static ROOT_SIGNATURES: RwLock>> = RwLock::new(None); #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct DispatchMeshSig { @@ -899,11 +977,19 @@ struct DispatchMeshSig { mesh_offset: u32, } -static DISPATCH_MESH_SIGS: Mutex>> = Mutex::new(None); +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DrawSig { + byte_stride: u32, + draw_offset: u32, + indexed: bool, +} + +static DISPATCH_MESH_SIGS: RwLock>> = RwLock::new(None); +static DRAW_SIGS: RwLock>> = RwLock::new(None); /// noted at every creation, so a signature made at a freed one's address does not keep its kind pub(super) fn note_root_changing_signature(sig: usize, changes: bool) { - let mut s = ROOT_SIGNATURES.lock().unwrap(); + let mut s = ROOT_SIGNATURES.write().unwrap(); let s = s.get_or_insert_with(Default::default); if changes { s.insert(sig); @@ -914,10 +1000,10 @@ pub(super) fn note_root_changing_signature(sig: usize, changes: bool) { /// command signatures with a Dispatch argument (noted at every creation, so a signature made /// at a freed one's address does not keep its kind) -static DISPATCH_SIGNATURES: Mutex>> = Mutex::new(None); +static DISPATCH_SIGNATURES: RwLock>> = RwLock::new(None); pub(super) fn note_signature_dispatches(sig: usize, dispatches: bool) { - let mut s = DISPATCH_SIGNATURES.lock().unwrap(); + let mut s = DISPATCH_SIGNATURES.write().unwrap(); let s = s.get_or_insert_with(Default::default); if dispatches { s.insert(sig); @@ -927,15 +1013,15 @@ pub(super) fn note_signature_dispatches(sig: usize, dispatches: bool) { } fn signature_dispatches(sig: usize) -> bool { - DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) + DISPATCH_SIGNATURES.read().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } /// command signatures of one Dispatch argument → their stride (a split program runs them as its /// chain, `chained_indirect`) -static DISPATCH_ONLY: Mutex>> = Mutex::new(None); +static DISPATCH_ONLY: RwLock>> = RwLock::new(None); pub(super) fn note_dispatch_only_signature(sig: usize, stride: Option) { - let mut s = DISPATCH_ONLY.lock().unwrap(); + let mut s = DISPATCH_ONLY.write().unwrap(); let s = s.get_or_insert_with(Default::default); match stride { Some(n) => { @@ -949,14 +1035,33 @@ pub(super) fn note_dispatch_only_signature(sig: usize, stride: Option) { pub(super) fn note_dispatch_mesh_signature(sig: usize, companion_dispatch: usize, byte_stride: u32, mesh_offset: u32) { DISPATCH_MESH_SIGS - .lock() + .write() .unwrap() .get_or_insert_with(HashMap::new) .insert(sig, DispatchMeshSig { companion_dispatch, byte_stride, mesh_offset }); } fn dispatch_mesh_sig_of(sig: usize) -> Option { - DISPATCH_MESH_SIGS.lock().unwrap().as_ref()?.get(&sig).copied() + DISPATCH_MESH_SIGS.read().unwrap().as_ref()?.get(&sig).copied() +} + +/// noted at every creation, so a non-draw signature made at a freed draw signature's address does +/// not inherit stale draw-guard metadata +pub(super) fn note_draw_signature(sig: usize, info: Option<(u32, u32, bool)>) { + let mut s = DRAW_SIGS.write().unwrap(); + let s = s.get_or_insert_with(HashMap::new); + match info { + Some((byte_stride, draw_offset, indexed)) => { + s.insert(sig, DrawSig { byte_stride, draw_offset, indexed }); + } + None => { + s.remove(&sig); + } + } +} + +fn draw_sig_of(sig: usize) -> Option { + DRAW_SIGS.read().unwrap().as_ref()?.get(&sig).copied() } unsafe fn emit_uav_barrier(list: &ID3D12GraphicsCommandList, res: Option<&ID3D12Resource>) { @@ -1111,7 +1216,14 @@ pub(super) fn note_records_queue(queue: usize, lists: &[*mut c_void]) { if RECORDS_QUEUES_DIFFER.load(Ordering::Relaxed) { return; } - let used = STATES.lock().unwrap().as_ref().is_some_and(|m| lists.iter().any(|&l| m.get(&(l as usize)).is_some_and(|s| s.shared_records))); + let used = lists.iter().any(|&l| { + let key = l as usize; + STATES[state_shard(key)] + .lock() + .unwrap() + .as_ref() + .is_some_and(|m| m.get(&key).is_some_and(|s| s.shared_records)) + }); if used && !same_records_queue(&RECORDS_QUEUE, queue) { RECORDS_QUEUES_DIFFER.store(true, Ordering::Relaxed); crate::xlog_warn!("D3D12.X: two-pass draws go to a second queue ({queue:#x}): the record buffers are the lists' own from here"); @@ -1183,28 +1295,137 @@ unsafe fn ensure_res_buffer(this: *mut c_void, need_bytes: u64) -> Result<(ID3D1 Ok((buf, va, cap)) } -/// The `io` block of a two-pass stage: its user SGPRs (`compute_pass`: the MS layout) with the -/// argument table at `table_at`, and the high dword of unified memory's base, as the other binds -/// write it (the translated pair picks each access's memory window from it). The compute pass -/// runs the console MS: when its layout says the shaders index the heaps themselves, the heaps' -/// addresses (`State::heaps`) follow the mesh root arguments, as `bind_abi` places them. -fn two_pass_io(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize, heaps: [u32; 2]) -> Vec { - let mut io = match layout { - Some(l) if compute_pass => console_list::with_heaps(l, None, console_list::user_data_ms(l, args, table_at), heaps), - Some(l) => console_list::user_data_gfx(l, args, table_at), - None if compute_pass => { - let mut v = vec![0u32; 16]; - v[8] = table_at as u32; - v[9] = (table_at >> 32) as u32; - v - } - None => vec![table_at as u32, (table_at >> 32) as u32], - }; - io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); +/// Write packed inline root arguments from `args` into `dst[first..]` as little-endian dwords, +/// returning the next free SGPR index (zero heap allocation). +fn write_inline_words(dst: &mut [u32], first: usize, inline_bytes: u32, args: &[u8]) -> usize { + let inline = &args[..(inline_bytes as usize).min(args.len())]; + let mut len = first; + for chunk in inline.chunks(4) { + let mut w = [0u8; 4]; + w[..chunk.len()].copy_from_slice(chunk); + if len < dst.len() { + dst[len] = u32::from_le_bytes(w); + } + len += 1; + } + len +} + +/// Append heap base addresses requested by `l.heaps` into `dst[len..]`, respecting `user_sgprs`. +fn append_heap_words(dst: &mut [u32], mut len: usize, l: &Layout, user_sgprs: Option, heaps: [u32; 2]) { + for (_, base) in l.heaps.iter().zip(heaps).filter(|(&used, _)| used) { + if user_sgprs.is_some_and(|n| len as u32 >= n) { + break; + } + if len < dst.len() { + dst[len] = base; + } + len += 1; + } +} + +/// Zero-allocation stack builder for graphics `io` (`u0`) user SGPRs (`KERNEL_SGPRS` dwords). +fn fill_io_gfx(layout: Option<&Layout>, args: &[u8], table_at: u64, heaps: [u32; 2], uma_base: usize) -> [u32; crate::gpu::recomp::KERNEL_SGPRS] { + let mut io = [0u32; crate::gpu::recomp::KERNEL_SGPRS]; + io[0] = table_at as u32; + io[1] = (table_at >> 32) as u32; + if let Some(l) = layout { + let len = write_inline_words(&mut io, 8, l.inline_gfx, args); + append_heap_words(&mut io, len, l, None, heaps); + } + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + io +} + +/// Zero-allocation stack builder for compute `io` (`u0`) user SGPRs (`KERNEL_SGPRS` dwords). +fn fill_io_compute(layout: Option<&Layout>, user_sgprs: Option, args: &[u8], table_at: u64, heaps: [u32; 2], uma_base: usize, group_limit: u32) -> [u32; crate::gpu::recomp::KERNEL_SGPRS] { + let mut io = [0u32; crate::gpu::recomp::KERNEL_SGPRS]; + io[0] = table_at as u32; + io[1] = (table_at >> 32) as u32; + if let Some(l) = layout { + let inline = console_list::inline_for(l, user_sgprs); + let len = write_inline_words(&mut io, 4, inline, args); + append_heap_words(&mut io, len, l, user_sgprs, heaps); + } io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + io[crate::gpu::recomp::IO_GROUP_LIMIT] = group_limit; io } +/// Zero-allocation stack builder for two-pass stage `io` (`u0`) user SGPRs. +fn fill_io_two_pass(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize, heaps: [u32; 2]) -> [u32; crate::gpu::recomp::KERNEL_SGPRS] { + let mut io = [0u32; crate::gpu::recomp::KERNEL_SGPRS]; + if compute_pass { + io[8] = table_at as u32; + io[9] = (table_at >> 32) as u32; + if let Some(l) = layout { + let len = write_inline_words(&mut io, 16, l.inline_ms, args); + append_heap_words(&mut io, len, l, None, heaps); + } + } else { + io[0] = table_at as u32; + io[1] = (table_at >> 32) as u32; + if let Some(l) = layout { + write_inline_words(&mut io, 8, l.inline_gfx, args); + } + } + io[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + io +} + +/// The `io` block of a two-pass stage (test helper wrapping `fill_io_two_pass`). +#[cfg(test)] +fn two_pass_io(layout: Option<&Layout>, args: &[u8], table_at: u64, compute_pass: bool, uma_base: usize, heaps: [u32; 2]) -> Vec { + fill_io_two_pass(layout, args, table_at, compute_pass, uma_base, heaps).to_vec() +} + +/// Ensure shared shader-visible descriptor heaps are bound on `this`, skipping global locks when +/// already verified on this recording (`State::heaps_ensured`). +unsafe fn ensure_heaps_cached(this: *mut c_void) { + if with(this, |s| s.heaps_ensured) { + return; + } + if super::list_x::ensure_view_heap(this) { + with(this, |s| s.heaps_ensured = true); + } +} + +/// Lazily resolve and cache `vram_io_device(this)` outside `STATES`, avoiding 3 global locks + +/// COM AddRef/Release on every draw/dispatch. +unsafe fn ensure_vram_io_dev(this: *mut c_void) -> Option { + if let Some(cached) = with(this, |s| s.vram_io_dev.as_ref().map(|o| o.as_ref().map(|d| d.0.clone()))) { + return cached; + } + let dev = vram_io_device(this); + with(this, |s| { + s.vram_io_dev = Some(dev.as_ref().map(|d| CachedIoDev(d.clone()))); + }); + dev +} + +/// Copy `tail` of root arguments into UMA arena, reusing a single 16-byte dummy slot when `tail` +/// is empty (all root arguments fit inline in user SGPRs). Takes disjoint `State` fields so +/// callers can hold an immutable borrow of `s.uma_windows` across the call. +unsafe fn upload_arg_table( + u: &crate::gpu::uma::Uma, + arena: &mut crate::gpu::uma::Arena, + uma: &mut Vec, + dummy_table_p: &mut usize, + tail: &[u8], +) -> Result { + if tail.is_empty() { + if *dummy_table_p == 0 { + let p = arena.take(u, 16, 256, uma).ok_or("unified memory is full")?; + std::ptr::write_bytes(p, 0, 16); + *dummy_table_p = p as usize; + } + return Ok(*dummy_table_p as u64); + } + let table_p = arena.take(u, tail.len().max(16), 256, uma).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); + Ok(table_p as u64) +} + unsafe fn bind_two_pass_stage( this: *mut c_void, list: &ID3D12GraphicsCommandList, @@ -1214,7 +1435,7 @@ unsafe fn bind_two_pass_stage( compute_pass: bool, ) -> Result<(), String> { // the pair is translated with heap windows when they are on (`pso::mem_windows`): as `bind_abi` - super::list_x::ensure_view_heap(this); + ensure_heaps_cached(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; let rs_usize = if compute_pass { tp.compute_rs } else { tp.mesh_rs }; let rs_raw = rs_usize as *mut c_void; @@ -1222,7 +1443,18 @@ unsafe fn bind_two_pass_stage( let pso_raw = if compute_pass { tp.compute } else { real_mesh_pso } as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&pso_raw).ok_or(if compute_pass { "two-pass compute pipeline" } else { "two-pass mesh pipeline" })?; - let io_dev = vram_io_device(this); + let need_io_dev = with(this, |s| { + let hit = if compute_pass { + s.io_cache_tp_cs.is_some_and(|(gen, _)| gen == s.args_gen_gfx) + } else { + s.io_cache_tp_ms.is_some_and(|(gen, _)| gen == s.args_gen_gfx) + }; + !hit && s.vram_io_dev.is_none() + }); + if need_io_dev { + let _ = ensure_vram_io_dev(this); + } + let (set_rs, uav_mask, views) = with(this, |s| -> Result<(bool, u8, [u64; 6]), String> { if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { let w = super::real::uma_window_vas(); @@ -1248,20 +1480,14 @@ unsafe fn bind_two_pass_stage( let io_va = if let Some(va) = cached_io { va } else { - let layout = s.layout_gfx.as_deref(); - let args = s.args_gfx.as_slice(); - let inline = layout + let inline = s.layout_gfx.as_deref() .map_or(0, |l| if compute_pass { l.inline_ms } else { l.inline_gfx } as usize) - .min(args.len()); - let tail = &args[inline..]; - let table_p = s.arena.take(u, tail.len().max(16), 256, &mut s.uma).ok_or("unified memory is full")?; - if !tail.is_empty() { - std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); - } - let io = two_pass_io(layout, args, table_p as u64, compute_pass, u.base(), s.heaps); - let io_bytes = io.len() * 4; + .min(s.args_gfx.len()); + let table_at = upload_arg_table(u, &mut s.arena, &mut s.uma, &mut s.dummy_table_p, &s.args_gfx[inline..])?; + let io = fill_io_two_pass(s.layout_gfx.as_deref(), s.args_gfx.as_slice(), table_at, compute_pass, u.base(), s.heaps); + let io_bytes = std::mem::size_of_val(&io); let io_slice = std::slice::from_raw_parts(io.as_ptr().cast::(), io_bytes); - let va = match io_dev.as_ref().and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), dev, io_slice)) { + let va = match s.vram_io_dev.as_ref().and_then(|o| o.as_ref()).and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), &dev.0, io_slice)) { Some(va) => va, None => { let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; @@ -1370,6 +1596,139 @@ const GUARD_ARGS_DRED_LABEL: &str = "xcl guard_dispatch_args"; const SCALE_ARGS_DRED_LABEL: &str = "xcl make_scaled_args_buffer"; const PRELUDE_GUARD_DRED_LABEL: &str = "xcl prelude_guard_dispatch_args"; const PRELUDE_SCALE_DRED_LABEL: &str = "xcl prelude_scale_mesh_args"; +const GUARD_DRAW_DRED_LABEL: &str = "xcl guard_draw_args"; +const PRELUDE_DRAW_DRED_LABEL: &str = "xcl prelude_guard_draw_args"; + +/// Exclusive upper bound on vertices/indices per instance in indirect Draw/DrawIndexed (`2^23` = +/// `8,388,608`): any record with `verts >= 2^23` is zeroed to prevent garbage indirect-draw hangs. +const DRAW_VERTS_PER_INST_LIMIT: u32 = 1 << 23; +/// Inclusive upper bound on total vertices (`verts_per_inst * instances`, `2^26` = `67,108,864`): +/// any record with `verts * instances > 2^26` is zeroed. +const DRAW_TOTAL_VERTS_MAX: u32 = 1 << 26; + +/// Pure check matching `GUARD_DRAW_ARGS_*` / `PRELUDE_DRAW_GUARD_*`: true when an indirect +/// Draw/DrawIndexed record should be zeroed (`verts == 0`, `insts == 0`, `verts >= 2^23`, or +/// `verts * insts > 2^26`). +#[cfg(test)] +fn draw_record_rejected(verts: u32, insts: u32) -> bool { + verts == 0 || insts == 0 || verts >= DRAW_VERTS_PER_INST_LIMIT || insts > DRAW_TOTAL_VERTS_MAX / verts +} + +/// Inline indirect Draw/DrawIndexed argument guard (`u0` = `[count, stride, draw_offset, src_off]`, +/// `u2` = source UMA window, `u3` = destination scratch): copies each command and zeroes +/// `(verts, insts)` whenever `verts == 0 || insts == 0 || verts >= 2^23 || verts * insts > 2^26`. +pub(super) const GUARD_DRAW_ARGS_HLSL: &str = r#"RWByteAddressBuffer io : register(u0); +RWByteAddressBuffer src : register(u2); +RWByteAddressBuffer dst : register(u3); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + uint count = io.Load(0), stride = io.Load(4), draw_off = io.Load(8), src_off = io.Load(12); + if (tid >= count) return; + uint s = src_off + tid * stride; + uint d = tid * stride; + for (uint i = 0u; i < stride; i += 4u) { + dst.Store(d + i, src.Load(s + i)); + } + uint verts = src.Load(s + draw_off); + uint insts = src.Load(s + draw_off + 4u); + if (verts == 0u || insts == 0u || verts >= 8388608u || insts > 67108864u / verts) { + dst.Store(d + draw_off, 0u); + dst.Store(d + draw_off + 4u, 0u); + } +} +"#; + +/// Descriptor-heap + inline root-constants form of `GUARD_DRAW_ARGS_HLSL`. +pub(super) const GUARD_DRAW_ARGS_HEAP_HLSL: &str = r#"cbuffer Args : register(b0) { + uint count, stride, draw_off, src_slot, src_off; +}; +RWByteAddressBuffer dst : register(u0); +[numthreads(64, 1, 1)] +void main(uint tid : SV_DispatchThreadID) { + if (tid >= count) return; + RWByteAddressBuffer src = ResourceDescriptorHeap[src_slot]; + uint s = src_off + tid * stride; + uint d = tid * stride; + for (uint i = 0u; i < stride; i += 4u) { + dst.Store(d + i, src.Load(s + i)); + } + uint verts = src.Load(s + draw_off); + uint insts = src.Load(s + draw_off + 4u); + if (verts == 0u || insts == 0u || verts >= 8388608u || insts > 67108864u / verts) { + dst.Store(d + draw_off, 0u); + dst.Store(d + draw_off + 4u, 0u); + } +} +"#; + +/// Batched prelude pass guarding all hoisted indirect Draw/DrawIndexed buffers in one +/// `Dispatch(num_jobs, 1, 1)` (`jobs` u0: 32-byte records +/// `[count, stride, draw_off, src_win, src_off, dst_off, 0, 0]`). +pub(super) const PRELUDE_DRAW_GUARD_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +RWByteAddressBuffer w0 : register(u2); +RWByteAddressBuffer w1 : register(u3); +RWByteAddressBuffer w2 : register(u4); +RWByteAddressBuffer w3 : register(u5); +uint load_u32(uint win, uint off) { + if (win == 0u) return w0.Load(off); + if (win == 1u) return w1.Load(off); + if (win == 2u) return w2.Load(off); + return w3.Load(off); +} +[numthreads(64, 1, 1)] +void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { + uint b = gid.x * 32u; + uint count = jobs.Load(b); + uint stride = jobs.Load(b + 4u); + uint draw_off = jobs.Load(b + 8u); + uint src_win = jobs.Load(b + 12u); + uint src_off = jobs.Load(b + 16u); + uint dst_off = jobs.Load(b + 20u); + for (uint tid = gtid.x; tid < count; tid += 64u) { + uint s = src_off + tid * stride; + uint d = dst_off + tid * stride; + for (uint i = 0u; i < stride; i += 4u) { + dst.Store(d + i, load_u32(src_win, s + i)); + } + uint verts = load_u32(src_win, s + draw_off); + uint insts = load_u32(src_win, s + draw_off + 4u); + if (verts == 0u || insts == 0u || verts >= 8388608u || insts > 67108864u / verts) { + dst.Store(d + draw_off, 0u); + dst.Store(d + draw_off + 4u, 0u); + } + } +} +"#; + +/// Descriptor-heap form of `PRELUDE_DRAW_GUARD_HLSL`. +pub(super) const PRELUDE_DRAW_GUARD_HEAP_HLSL: &str = r#"RWByteAddressBuffer jobs : register(u0); +RWByteAddressBuffer dst : register(u1); +[numthreads(64, 1, 1)] +void main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID) { + uint b = gid.x * 32u; + uint count = jobs.Load(b); + uint stride = jobs.Load(b + 4u); + uint draw_off = jobs.Load(b + 8u); + uint src_win = jobs.Load(b + 12u); + uint src_off = jobs.Load(b + 16u); + uint dst_off = jobs.Load(b + 20u); + RWByteAddressBuffer src = ResourceDescriptorHeap[NonUniformResourceIndex(4u + src_win)]; + for (uint tid = gtid.x; tid < count; tid += 64u) { + uint s = src_off + tid * stride; + uint d = dst_off + tid * stride; + for (uint i = 0u; i < stride; i += 4u) { + dst.Store(d + i, src.Load(s + i)); + } + uint verts = src.Load(s + draw_off); + uint insts = src.Load(s + draw_off + 4u); + if (verts == 0u || insts == 0u || verts >= 8388608u || insts > 67108864u / verts) { + dst.Store(d + draw_off, 0u); + dst.Store(d + draw_off + 4u, 0u); + } + } +} +"#; /// Batched prelude pass clamping & >65,535-folding all hoisted indirect compute dispatches of a /// command list in a single Dispatch(ceil(N / 64), 1, 1) before the list runs. @@ -1779,6 +2138,11 @@ unsafe fn prelude_scale_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignat prelude_pipeline(dev, PRELUDE_SCALE_HLSL, PRELUDE_SCALE_DRED_LABEL, &CACHE) } +unsafe fn prelude_draw_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_pipeline(dev, PRELUDE_DRAW_GUARD_HLSL, PRELUDE_DRAW_DRED_LABEL, &CACHE) +} + unsafe fn prelude_heap_root_signature(dev: &ID3D12Device) -> Result { let params: [D3D12_ROOT_PARAMETER1; 2] = std::array::from_fn(|reg| D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, @@ -1841,6 +2205,27 @@ unsafe fn prelude_scale_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootS prelude_heap_pipeline(dev, PRELUDE_SCALE_HEAP_HLSL, PRELUDE_SCALE_DRED_LABEL, &CACHE) } +unsafe fn prelude_draw_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + prelude_heap_pipeline(dev, PRELUDE_DRAW_GUARD_HEAP_HLSL, PRELUDE_DRAW_DRED_LABEL, &CACHE) +} + +unsafe fn guard_draw_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + args_pipeline(dev, GUARD_DRAW_ARGS_HLSL, GUARD_DRAW_DRED_LABEL, false, &CACHE) +} + +unsafe fn guard_draw_heap_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static CACHE: ArgsPipelines = Mutex::new(None); + heap_args_pipeline(dev, GUARD_DRAW_ARGS_HEAP_HLSL, GUARD_DRAW_DRED_LABEL, 5, &[0], &CACHE) +} + +/// `XCL_INDIRECT_DRAW_GUARD=0`: skip indirect Draw/DrawIndexed vertex-count clamping. +fn indirect_draw_guard() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_INDIRECT_DRAW_GUARD").map_or(true, |v| v.trim() != "0")) +} + /// Allocate `bytes` in `State::prelude_scratch` (disjoint from inline ping-pong scratch so the /// prelude leaves these buffers in `INDIRECT_ARGUMENT` for the entire main segment). unsafe fn alloc_prelude_scratch(this: *mut c_void, dev: &ID3D12Device, bytes: u64) -> Result<(ID3D12Resource, u64, usize), String> { @@ -1890,9 +2275,9 @@ unsafe fn alloc_prelude_scratch(this: *mut c_void, dev: &ID3D12Device, bytes: u6 /// `io` (`u0`) uploads and hoisted indirect-argument clamp/scale jobs for `seg` before `seg` /// executes on the queue. pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { - let (already, io_copies, bufs, guards, scales) = with(seg, |s| { + let (already, io_copies, bufs, guards, scales, draws) = with(seg, |s| { if let Some(ref built) = s.prelude_built { - return (Some(built.as_raw()), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + return (Some(built.as_raw()), Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); } let io_copies: Vec<(ID3D12Resource, ID3D12Resource, u64)> = s .io_blocks @@ -1900,15 +2285,15 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { .filter(|b| b.used > 0) .map(|b| (b.vram.clone(), b.upload.clone(), b.used)) .collect(); - if io_copies.is_empty() && s.prelude_guards.is_empty() && s.prelude_scales.is_empty() { - return (None, Vec::new(), Vec::new(), Vec::new(), Vec::new()); + if io_copies.is_empty() && s.prelude_guards.is_empty() && s.prelude_scales.is_empty() && s.prelude_draws.is_empty() { + return (None, Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); } - (None, io_copies, s.prelude_bufs.clone(), s.prelude_guards.clone(), s.prelude_scales.clone()) + (None, io_copies, s.prelude_bufs.clone(), s.prelude_guards.clone(), s.prelude_scales.clone(), s.prelude_draws.clone()) }); if let Some(p) = already { return Some(p); } - if io_copies.is_empty() && guards.is_empty() && scales.is_empty() { + if io_copies.is_empty() && guards.is_empty() && scales.is_empty() && draws.is_empty() { return None; } let run = (|| -> Result { @@ -1979,7 +2364,7 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { } } - if !guards.is_empty() || !scales.is_empty() { + if !guards.is_empty() || !scales.is_empty() || !draws.is_empty() { let u = crate::gpu::uma::get().ok_or("no unified memory")?; let win_vas = with(seg, |s| -> Result<[u64; 4], String> { if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { @@ -2103,6 +2488,33 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { } } + // 3b. Emit batched indirect draw-guard dispatches grouped by prelude scratch buffer. + if !draws.is_empty() { + let (rs, pso) = if shared_heap.is_some() { prelude_draw_heap_pipeline(&dev)? } else { prelude_draw_pipeline(&dev)? }; + list.SetComputeRootSignature(&rs); + if shared_heap.is_none() { + bind_windows(&list); + } + list.SetPipelineState(&pso); + for (buf_idx, buf) in bufs.iter().enumerate() { + let batch: Vec<&PreludeDrawJob> = draws.iter().filter(|j| j.buf_idx == buf_idx).collect(); + if batch.is_empty() { + continue; + } + let dst_va = buf.GetGPUVirtualAddress(); + list.SetComputeRootUnorderedAccessView(1, dst_va); + for chunk in batch.chunks(65_535) { + let mut words = Vec::with_capacity(chunk.len() * 8); + for j in chunk { + words.extend_from_slice(&[j.count, j.stride, j.draw_offset, j.src_win, j.src_off, j.dst_off, 0, 0]); + } + let jobs_va = upload_words(&words)?; + list.SetComputeRootUnorderedAccessView(0, jobs_va); + list.Dispatch(chunk.len() as u32, 1, 1); + } + } + } + // 4. Transition all prelude scratch buffers UAV -> GUARDED_ARGS_STATE (plus global UAV // barrier if any guard jobs wrote `IO_GROUP_LIMIT` into UMA). let mut post_barriers: Vec = Vec::with_capacity(bufs.len() + usize::from(!guards.is_empty())); @@ -2140,14 +2552,14 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { s.prelude_owned = Some((alloc, list.clone(), dev_key, ty.0)); s.prelude_built = Some(list.clone()); }); - if !guards.is_empty() || !scales.is_empty() { + if !guards.is_empty() || !scales.is_empty() || !draws.is_empty() { static BATCHES: AtomicU64 = AtomicU64::new(0); static TOTAL_JOBS: AtomicU64 = AtomicU64::new(0); - let n_jobs = (guards.len() + scales.len()) as u64; + let n_jobs = (guards.len() + scales.len() + draws.len()) as u64; let b = BATCHES.fetch_add(1, Ordering::Relaxed) + 1; let tot = TOTAL_JOBS.fetch_add(n_jobs, Ordering::Relaxed) + n_jobs; if b == 1 || (b.is_power_of_two() && b >= 16) { - crate::xlog_info!("D3D12.X: indirect prelude batch #{b} ({} guard + {} scale jobs, {tot} hoisted total)", guards.len(), scales.len()); + crate::xlog_info!("D3D12.X: indirect prelude batch #{b} ({} guard + {} scale + {} draw jobs, {tot} hoisted total)", guards.len(), scales.len(), draws.len()); } } if !io_copies.is_empty() { @@ -2326,7 +2738,7 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis std::ptr::copy_nonoverlapping(hdr.as_ptr(), jobs_p as *mut u32, hdr.len()); std::ptr::copy_nonoverlapping(rec0.as_ptr(), (jobs_p as usize + 16) as *mut u32, rec0.len()); let (rs, pso) = if use_heap { - super::list_x::ensure_view_heap(this); + ensure_heaps_cached(this); prelude_guard_heap_pipeline(&dev)? } else { prelude_guard_pipeline(&dev)? @@ -2369,7 +2781,7 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, 12) { let (rs, pso) = guard_indirect_heap_pipeline(&dev)?; let consts = [src_slot, src_off, most_groups(), lim_off]; - super::list_x::ensure_view_heap(this); + ensure_heaps_cached(this); // the title's writes of the arguments before this (`fresh_indirect_arguments`) emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); @@ -2414,6 +2826,101 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis Ok((dst, dst_off)) } +/// Guard `max` indirect Draw/DrawIndexed command records at UMA address `src` (`stride` bytes +/// each, draw arguments at `draw_offset`), zeroing any record with `>= 2^23` vertices per +/// instance or `> 2^26` total vertices. Hoists into the batched prelude list when safe, else +/// executes inline into ping-pong scratch. +unsafe fn guard_draw_args( + this: *mut c_void, + list: &ID3D12GraphicsCommandList, + src: usize, + max: u32, + stride: u32, + draw_offset: u32, +) -> Result<(ID3D12Resource, u64), String> { + if super::list_x::tracked_list_type(this) == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) { + return Err("command bundles cannot record indirect argument barriers".into()); + } + if max == 0 || stride == 0 || stride % 4 != 0 || draw_offset % 4 != 0 || draw_offset.checked_add(16).is_none_or(|e| e > stride) { + return Err(format!("invalid indirect draw layout (max {max}, stride {stride}, offset {draw_offset})")); + } + let commands = (max as u64).checked_mul(stride as u64).ok_or("indirect draw command span overflow")?; + if commands > u32::MAX as u64 { + return Err("indirect draw command buffer exceeds 32-bit offsets".into()); + } + let dev = super::real::list_device(this).ok_or("no device")?; + let u = crate::gpu::uma::get().ok_or("no unified memory")?; + super::real::uma_window_buffer(src, commands as usize).ok_or("the indirect draw arguments are not in one memory window")?; + if can_hoist_prelude(this) { + if let Some((src_win, src_off)) = uma_win_off(u, src, commands as usize) { + let (dst, dst_off, buf_idx) = alloc_prelude_scratch(this, &dev, commands)?; + if let Ok(dst_off32) = u32::try_from(dst_off) { + if dst_off32.checked_add(commands as u32).is_some() { + with(this, |s| { + s.prelude_draws.push(PreludeDrawJob { + buf_idx, + dst_off: dst_off32, + count: max, + stride, + draw_offset, + src_win, + src_off, + }); + }); + return Ok((dst, dst_off)); + } + } + } + } + with(this, |s| s.inline_guard = None); + let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, commands)?; + let dst_va = dst.GetGPUVirtualAddress() + dst_off; + if super::console_heap::window_views_ready() { + if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, commands as usize) { + let (rs, pso) = guard_draw_heap_pipeline(&dev)?; + let consts = [max, stride, draw_offset, src_slot, src_off]; + ensure_heaps_cached(this); + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, consts.len() as u32, consts.as_ptr() as *const c_void, 0); + list.SetComputeRootUnorderedAccessView(1, dst_va); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); + with(this, |s| { + s.scratch[slot].state = GUARDED_ARGS_STATE; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + return Ok((dst, dst_off)); + } + } + let (rs, pso) = guard_draw_pipeline(&dev)?; + let src_va = super::real::uma_va_of(src).ok_or("unified memory is not open on the GPU")?; + let (src_base, src_off) = align_root_uav(src_va)?; + if (src_off as u64).checked_add(commands).is_none_or(|end| end > u32::MAX as u64) { + return Err("indirect draw command range exceeds 32-bit shader offsets".into()); + } + let consts = [max, stride, draw_offset, src_off]; + let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; + std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); + let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, consts_va); + list.SetComputeRootUnorderedAccessView(1, src_base); + list.SetComputeRootUnorderedAccessView(2, dst_va); + list.Dispatch(max.div_ceil(64), 1, 1); + emit_transition(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); + with(this, |s| { + s.scratch[slot].state = GUARDED_ARGS_STATE; + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = true; + }); + Ok((dst, dst_off)) +} + unsafe fn scale_indirect_pipeline(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { static CACHE: Mutex>> = Mutex::new(None); args_pipeline(dev, SCALE_ARGS_HLSL, SCALE_ARGS_DRED_LABEL, true, &CACHE) @@ -2697,7 +3204,7 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman if let Some((has_cnt, cnt_slot, cnt_off)) = cnt_loc { let (rs, pso) = scale_indirect_heap_pipeline(&dev)?; let consts = [max, stride, mesh_offset, split, cap, src_slot, src_off, has_cnt, cnt_slot, cnt_off]; - super::list_x::ensure_view_heap(this); + ensure_heaps_cached(this); // the title's writes of the arguments before this (`fresh_indirect_arguments`) emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); @@ -2992,7 +3499,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } return fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)); } - if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { + if ROOT_SIGNATURES.read().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) { if gfx { note_skipped_indirect(this, sig); } @@ -3003,8 +3510,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; - // Guard single-command indirect dispatches before binding or chaining so both `record_slicer` - // and the PC `ExecuteIndirect` read clamped, >65535 X-folded arguments from a committed buffer. + // Guard single-command indirect dispatches and indirect Draw/DrawIndexed buffers before + // binding or chaining so out-of-range GPU-written counts are clamped/zeroed in scratch. let mut guarded = None; let mut preset_io = None; if compute && max == 1 && indirect_guard() && signature_dispatches(sig) { @@ -3032,6 +3539,23 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } } + } else if gfx && indirect_guard() && indirect_draw_guard() { + if let Some(dsig) = draw_sig_of(sig) { + let _ = dsig.indexed; + if let Some(commands) = (max as usize).checked_mul(dsig.byte_stride as usize) { + if let Some((p, _)) = commands_at.filter(|&(_, n)| commands > 0 && commands <= n) { + match guard_draw_args(this, list, p, max, dsig.byte_stride, dsig.draw_offset) { + Ok(g) => guarded = Some(g), + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect's draw counts are not checked: {e}"); + } + } + } + } + } + } } let (exec_args, exec_args_off) = guarded.as_ref().map_or((args, args_off), |(b, o)| (b.as_raw() as usize, *o)); if compute && super::real::dispatch_chain::is_split(pso) { @@ -3129,7 +3653,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us count(if gfx { DRAWS } else { DISPATCHES }); // an indirect dispatch: its groups are in the argument buffer (`max` of them) let mark = if gfx { 0 } else { super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [0, 0, max]) }; - if guarded.is_some() { + if guarded.is_some() && count_buf == 0 { pc(this, sig, max, args, args_off, count_buf, count_off); } else { fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) @@ -3176,7 +3700,7 @@ unsafe fn chained_indirect( preset_io: Option, ei: impl FnOnce(), ) -> Result { - let Some(stride) = DISPATCH_ONLY.lock().unwrap().as_ref().and_then(|m| m.get(&sig).copied()) else { + let Some(stride) = DISPATCH_ONLY.read().unwrap().as_ref().and_then(|m| m.get(&sig).copied()) else { return Ok(false); }; let args_va = match guarded { @@ -3458,54 +3982,59 @@ fn pso_for_draw(pso: usize) -> usize { /// translation, or no unified memory). unsafe fn graphics_bound(this: *mut c_void) -> Option { let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); - let pso = with(this, |s| s.pso); - // a pipeline still being built in the background is not waited for (`pso_for_draw`) - let real = pso_for_draw(pso); - if !super::real::is_translated_graphics(real) { - // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in - // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing - // DrawInstanced / DrawIndexedInstanced against a mesh PSO invalidates the command list - // (Close → E_INVALIDARG). - if let Some(tp) = super::real::two_pass_of(real) { - super::list_x::note_dropped_draw(this); - count(DRAWS_SKIPPED); - static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!( - "D3D12.X: draw with two-pass {} pipeline ({real:#x}) skipped – PC pipeline is a mesh shader", - tp.kind - ); + let (pso, cached_gfx) = with(this, |s| { + let hit = s.pso_abi_cache.is_some_and(|c| c.query_pso == s.pso && c.is_gfx); + (s.pso, hit) + }); + if !cached_gfx { + // a pipeline still being built in the background is not waited for (`pso_for_draw`) + let real = pso_for_draw(pso); + if !super::real::is_translated_graphics(real) { + // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in + // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing + // DrawInstanced / DrawIndexedInstanced against a mesh PSO invalidates the command list + // (Close → E_INVALIDARG). + if let Some(tp) = super::real::two_pass_of(real) { + super::list_x::note_dropped_draw(this); + count(DRAWS_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!( + "D3D12.X: draw with two-pass {} pipeline ({real:#x}) skipped – PC pipeline is a mesh shader", + tp.kind + ); + } + return None; } - return None; - } - count(DRAWS_PC); - if super::present::trace_frame() { - // which pipelines draw without a translation (first 12 distinct) - static SEEN: Mutex> = Mutex::new(Vec::new()); - let mut g = SEEN.lock().unwrap(); - if !g.contains(&pso) && g.len() < 12 { - g.push(pso); - let real = super::pso_async::resolve(pso); - crate::xlog_info!( - "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", - super::pso_async::is_pending(pso), - super::real::two_pass_of(real).is_some(), - super::present::rt0_resource(this as usize).map(|r| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) })) - ); + count(DRAWS_PC); + if super::present::trace_frame() { + // which pipelines draw without a translation (first 12 distinct) + static SEEN: Mutex> = Mutex::new(Vec::new()); + let mut g = SEEN.lock().unwrap(); + if !g.contains(&pso) && g.len() < 12 { + g.push(pso); + let real = super::pso_async::resolve(pso); + crate::xlog_info!( + "frame trace: draw with an untranslated pipeline {pso:#x} (resolves to {real:#x}; pending {}, two-pass {}, RT0 {:?})", + super::pso_async::is_pending(pso), + super::real::two_pass_of(real).is_some(), + super::present::rt0_resource(this as usize).map(|r| ID3D12Resource::from_raw_borrowed(&(r as *mut c_void)).map(|x| { let d = x.GetDesc(); (d.Width, d.Height, d.Format.0) })) + ); + } } + // a PC pipeline (also a stand-in or fallback: made with the title's root signature): + // the title's root signature, which nothing else binds on the PC list – a draw without + // one is invalid (the debug layer reports it on every GPU; WARP faults on it) + if super::pso_async::is_stand_in(pso) { + super::list_x::note_dropped_draw(this); + } + let rs = with(this, |s| s.rs_gfx) as *mut c_void; + if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) { + list.SetGraphicsRootSignature(r); + with(this, |s| s.pc_abi_gfx = AbiBound::default()); + } + return Some(list); } - // a PC pipeline (also a stand-in or fallback: made with the title's root signature): - // the title's root signature, which nothing else binds on the PC list – a draw without - // one is invalid (the debug layer reports it on every GPU; WARP faults on it) - if super::pso_async::is_stand_in(pso) { - super::list_x::note_dropped_draw(this); - } - let rs = with(this, |s| s.rs_gfx) as *mut c_void; - if let Some(r) = ID3D12RootSignature::from_raw_borrowed(&rs) { - list.SetGraphicsRootSignature(r); - with(this, |s| s.pc_abi_gfx = AbiBound::default()); - } - return Some(list); } if super::present::trace_frame() { trace_ui_draw(this, pso); @@ -3749,8 +4278,14 @@ unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { let layout = console_list::layout_of(rs as usize); with(this, |s| { - if !console_list::same_layout(&s.layout, &layout) { - s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; + let same = console_list::same_layout(&s.layout, &layout); + if same && s.rs_cs == rs as usize { + return; + } + if !same { + let size = layout.as_ref().map_or(0, |l| l.size as usize); + s.args.clear(); + s.args.resize(size, 0); } s.layout = layout; s.rs_cs = rs as usize; @@ -3771,9 +4306,14 @@ pub(super) unsafe extern "system" fn set_compute_root_constant(this: *mut c_void /// #39 SetComputeRoot32BitConstants (PC #35) pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { - if !data.is_null() { - let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); - put(this, i, offset, &bytes); + if !data.is_null() && n > 0 { + #[cfg(target_endian = "little")] + let bytes = std::slice::from_raw_parts(data.cast::(), (n as usize).saturating_mul(4)); + #[cfg(not(target_endian = "little"))] + let bytes_vec: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); + #[cfg(not(target_endian = "little"))] + let bytes = bytes_vec.as_slice(); + put(this, i, offset, bytes); } } @@ -3787,7 +4327,12 @@ pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_vo /// #25 SetPipelineState: noted, then bound as on the PC pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { - with(this, |s| s.pso = pso as usize); + with(this, |s| { + if s.pso != pso as usize { + s.pso = pso as usize; + s.pso_abi_cache = None; + } + }); super::real::bind_pipeline(this, pso); } @@ -3984,23 +4529,10 @@ unsafe fn alloc_fresh_compute_io(this: *mut c_void, pso: usize) -> Result<(u64, } let windows = s.uma_windows.as_deref().unwrap(); let first = windows[0]; - let layout = s.layout.as_deref(); - let args = s.args.as_slice(); - let inline = layout.map_or(0, |l| console_list::inline_for(l, user_sgprs) as usize).min(args.len()); - let tail = &args[inline..]; - let table_p = s.arena.take(u, tail.len().max(16), 256, &mut s.uma).ok_or("unified memory is full")?; - if !tail.is_empty() { - std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); - } - let table_at = table_p as u64; - let mut io = match layout { - Some(l) => console_list::with_heaps(l, user_sgprs, console_list::user_data_for(l, user_sgprs, args, table_at), s.heaps), - None => vec![table_at as u32, (table_at >> 32) as u32], - }; - io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); - io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; - io[crate::gpu::recomp::IO_GROUP_LIMIT] = 0; - let io_bytes = io.len() * 4; + let inline = s.layout.as_deref().map_or(0, |l| console_list::inline_for(l, user_sgprs) as usize).min(s.args.len()); + let table_at = upload_arg_table(u, &mut s.arena, &mut s.uma, &mut s.dummy_table_p, &s.args[inline..])?; + let io = fill_io_compute(s.layout.as_deref(), user_sgprs, s.args.as_slice(), table_at, s.heaps, u.base(), 0); + let io_bytes = std::mem::size_of_val(&io); let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(io.as_ptr().cast::(), io_p, io_bytes); Ok((uma_va_in(u, windows, io_p as usize).unwrap_or(first), io_p as usize)) @@ -4012,20 +4544,52 @@ unsafe fn alloc_fresh_compute_io(this: *mut c_void, pso: usize) -> Result<(u64, /// memory, u1 res, u2… the memory windows; then the pipeline. `group_limit`: a folded /// dispatch's group count in X (`recomp::IO_GROUP_LIMIT`), 0 for any other. unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, group_limit: u32, preset_io_va: Option) -> Result<(), String> { - super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; - // a pipeline still being built in the background is waited for - let real = super::pso_async::resolve_wait(pso); - // a compute shader takes no more arguments from registers than it has (`inline_for`) - let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; - let rs_raw = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; + let (need_heaps, cached_pso, need_io_dev) = with(this, |s| { + let c = s.pso_abi_cache.filter(|c| c.query_pso == pso && c.is_gfx == gfx); + let io_hit = preset_io_va.is_some() + || (group_limit == 0 + && if gfx { + s.io_cache_gfx.is_some_and(|(gen, _)| gen == s.args_gen_gfx) + } else { + c.is_some_and(|ci| s.io_cache_cs.is_some_and(|(gen, sg, _)| gen == s.args_gen_cs && sg == ci.user_sgprs)) + }); + (!s.heaps_ensured, c, (!io_hit || s.dummy_res_va == 0) && s.vram_io_dev.is_none()) + }); + if need_heaps { + ensure_heaps_cached(this); + } + let (real, user_sgprs, rs_raw, store_pso_cache) = match cached_pso { + Some(c) => (c.real_pso, c.user_sgprs, c.rs_raw, false), + None => { + // a pipeline still being built in the background is waited for + let real = super::pso_async::resolve_wait(pso); + // a compute shader takes no more arguments from registers than it has (`inline_for`) + let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; + let rs_raw = super::real::pso_root_signature(real) + .or_else(|| super::real::abi_rs_cached().map(|p| p as usize)) + .ok_or("no XCL ABI root signature")?; + (real, user_sgprs, rs_raw, true) + } + }; + if need_io_dev { + let _ = ensure_vram_io_dev(this); + } let rs_ptr = rs_raw as *mut c_void; let rs = ID3D12RootSignature::from_raw_borrowed(&rs_ptr).ok_or("root signature")?; let real_ptr = real as *mut c_void; let pc = ID3D12PipelineState::from_raw_borrowed(&real_ptr).ok_or("pipeline")?; - let io_dev = vram_io_device(this); let (set_rs, uav_mask, views) = with(this, |s| -> Result<(bool, u8, [u64; 6]), String> { + if store_pso_cache { + s.pso_abi_cache = Some(CachedPsoAbi { + query_pso: pso, + real_pso: real, + rs_raw, + user_sgprs, + is_gfx: gfx, + }); + } if s.uma_windows.as_ref().is_none_or(Vec::is_empty) { let w = super::real::uma_window_vas(); if w.is_empty() { @@ -4045,7 +4609,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi // Runtime VS/PS/CS shaders never write to `u1` (`res`), so one zeroed 256-byte slot // per recording suffices across all `bind_abi` draws and dispatches. if s.dummy_res_va == 0 { - s.dummy_res_va = match io_dev.as_ref().and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), dev, &[0u8; 256])) { + s.dummy_res_va = match s.vram_io_dev.as_ref().and_then(|o| o.as_ref()).and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), &dev.0, &[0u8; 256])) { Some(va) => va, None => { let p = s.arena.take(u, 256, 256, &mut s.uma).ok_or("unified memory is full")?; @@ -4069,26 +4633,23 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi if let Some(va) = cached_io { va } else { - let (layout, args) = if gfx { (s.layout_gfx.as_deref(), s.args_gfx.as_slice()) } else { (s.layout.as_deref(), s.args.as_slice()) }; - let inline = layout.map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); - let tail = &args[inline..]; + let tail = if gfx { + let inline = s.layout_gfx.as_deref().map_or(0, |l| l.inline_gfx as usize).min(s.args_gfx.len()); + &s.args_gfx[inline..] + } else { + let inline = s.layout.as_deref().map_or(0, |l| console_list::inline_for(l, user_sgprs) as usize).min(s.args.len()); + &s.args[inline..] + }; // 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each) - let table_p = s.arena.take(u, tail.len().max(16), 256, &mut s.uma).ok_or("unified memory is full")?; - if !tail.is_empty() { - std::ptr::copy_nonoverlapping(tail.as_ptr(), table_p, tail.len()); - } - let table_at = table_p as u64; - let mut io = match layout { - Some(l) if gfx => console_list::with_heaps(l, None, console_list::user_data_gfx(l, args, table_at), s.heaps), - Some(l) => console_list::with_heaps(l, user_sgprs, console_list::user_data_for(l, user_sgprs, args, table_at), s.heaps), - None => vec![table_at as u32, (table_at >> 32) as u32], + let table_at = upload_arg_table(u, &mut s.arena, &mut s.uma, &mut s.dummy_table_p, tail)?; + let io = if gfx { + fill_io_gfx(s.layout_gfx.as_deref(), s.args_gfx.as_slice(), table_at, s.heaps, u.base()) + } else { + fill_io_compute(s.layout.as_deref(), user_sgprs, s.args.as_slice(), table_at, s.heaps, u.base(), group_limit) }; - io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); - io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; - io[crate::gpu::recomp::IO_GROUP_LIMIT] = group_limit; - let io_bytes = io.len() * 4; + let io_bytes = std::mem::size_of_val(&io); let io_slice = std::slice::from_raw_parts(io.as_ptr().cast::(), io_bytes); - let va = match io_dev.as_ref().and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), dev, io_slice)) { + let va = match s.vram_io_dev.as_ref().and_then(|o| o.as_ref()).and_then(|dev| alloc_vram_io_in(&mut s.io_blocks, s.allocator, s.prelude_built.is_some(), &dev.0, io_slice)) { Some(va) => va, None => { let io_p = s.arena.take(u, io_bytes.max(16), 256, &mut s.uma).ok_or("unified memory is full")?; @@ -4139,11 +4700,12 @@ pub(super) fn counts_snapshot() -> [u64; 5] { #[cfg(test)] pub(super) fn tracked_pso(list: *mut c_void) -> usize { - STATES + let key = list as usize; + STATES[state_shard(key)] .lock() .unwrap() .as_ref() - .and_then(|m| m.get(&(list as usize))) + .and_then(|m| m.get(&key)) .map_or(0, |s| s.pso) } @@ -4151,14 +4713,16 @@ pub(super) fn tracked_pso(list: *mut c_void) -> usize { /// PC root signatures after an internal graphics/compute sync pass (invalidating cached PC ABI /// root bindings since the internal pass clobbered them). pub(super) fn tracked_root_sigs(list: *mut c_void) -> (usize, usize) { - STATES + let key = list as usize; + STATES[state_shard(key)] .lock() .unwrap() .as_mut() - .and_then(|m| m.get_mut(&(list as usize))) + .and_then(|m| m.get_mut(&key)) .map_or((0, 0), |s| { s.pc_abi_gfx = AbiBound::default(); s.pc_abi_cs = AbiBound::default(); + s.heaps_ensured = false; (s.rs_gfx, s.rs_cs) }) } @@ -4687,7 +5251,7 @@ void main(uint t : SV_GroupIndex) { #[test] fn a_command_signature_made_at_a_freed_ones_address_does_not_keep_its_kind() { let sig = 0x7230_00F0usize; - let changing = |s: usize| ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|set| set.contains(&s)); + let changing = |s: usize| ROOT_SIGNATURES.read().unwrap().as_ref().is_some_and(|set| set.contains(&s)); note_root_changing_signature(sig, true); assert!(changing(sig)); // the signature is freed; a simple one is made at its address @@ -4996,7 +5560,7 @@ void main(uint t : SV_GroupIndex) { dispatch_mesh_sig_of(sig), Some(DispatchMeshSig { companion_dispatch: companion, byte_stride: 28, mesh_offset: 16 }) ); - DISPATCH_MESH_SIGS.lock().unwrap().as_mut().unwrap().remove(&sig); + DISPATCH_MESH_SIGS.write().unwrap().as_mut().unwrap().remove(&sig); assert_eq!(dispatch_mesh_sig_of(sig), None); } @@ -6044,4 +6608,81 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) rb.Unmap(0, None); } } + + #[test] + fn stack_io_builders_match_console_list_user_data_bit_for_bit() { + let layout = console_list::layout_from_blob(&test_rts0_blob()).expect("test layout"); + let args = vec![0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC]; + let table_at = 0x1234_5678_9ABC_DEF0u64; + let heaps = [0x0010_0000u32, 0x0020_0000u32]; + let uma_base = 0x0000_007F_0000_0000usize; + + let mut want_gfx = console_list::with_heaps(&layout, None, console_list::user_data_gfx(&layout, &args, table_at), heaps); + want_gfx.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + want_gfx[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + assert_eq!(fill_io_gfx(Some(&layout), &args, table_at, heaps, uma_base).as_slice(), want_gfx.as_slice()); + + for user_sgprs in [None, Some(4), Some(8), Some(16)] { + let mut want_cs = console_list::with_heaps(&layout, user_sgprs, console_list::user_data_for(&layout, user_sgprs, &args, table_at), heaps); + want_cs.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); + want_cs[crate::gpu::recomp::IO_UMA_BASE_HI] = (uma_base as u64 >> 32) as u32; + want_cs[crate::gpu::recomp::IO_GROUP_LIMIT] = 115_200; + assert_eq!( + fill_io_compute(Some(&layout), user_sgprs, &args, table_at, heaps, uma_base, 115_200).as_slice(), + want_cs.as_slice(), + "compute user_sgprs={user_sgprs:?}" + ); + } + } + + #[test] + fn idempotent_root_signature_preserves_io_cache_and_zero_alloc_constants_write_exact_words() { + let list = 0x7600_9001usize as *mut c_void; + let rs_key = 0x7600_9010usize; + console_list::note_root_signature(rs_key, &test_rts0_blob()); + reset(list, 0x7600_9100, 0); + unsafe { + set_graphics_root_signature(list, rs_key as *mut c_void); + let words = [0x1122_3344u32, 0x5566_7788u32]; + set_graphics_root_constants(list, 0, 2, words.as_ptr(), 0); + } + let gen1 = with(list, |s| { + assert_eq!(&s.args_gfx[..8], &[0x44, 0x33, 0x22, 0x11, 0x88, 0x77, 0x66, 0x55]); + s.io_cache_gfx = Some((s.args_gen_gfx, 0x8888_0000)); + s.args_gen_gfx + }); + // Re-binding the exact same graphics root signature preserves args_gen and io_cache. + unsafe { set_graphics_root_signature(list, rs_key as *mut c_void); } + with(list, |s| { + assert_eq!(s.args_gen_gfx, gen1); + assert_eq!(s.io_cache_gfx, Some((gen1, 0x8888_0000))); + }); + forget(list); + } + + #[test] + fn indirect_draw_guard_caps_per_instance_and_total_vertices() { + // Zero verts or zero instances are zeroed cleanly. + assert!(draw_record_rejected(0, 1)); + assert!(draw_record_rejected(100, 0)); + assert!(draw_record_rejected(0, u32::MAX)); + // Just below 2^23 per instance is allowed. + assert!(!draw_record_rejected(DRAW_VERTS_PER_INST_LIMIT - 1, 1)); + // Exactly 2^23 (8,388,608) per instance is rejected. + assert!(draw_record_rejected(DRAW_VERTS_PER_INST_LIMIT, 1)); + // Exact 2^26 (67,108,864) total vertices is allowed; 2^26 + 1 is rejected. + assert!(!draw_record_rejected(1 << 22, 16)); + assert!(draw_record_rejected(1 << 22, 17)); + assert!(!draw_record_rejected(1, DRAW_TOTAL_VERTS_MAX)); + assert!(draw_record_rejected(1, DRAW_TOTAL_VERTS_MAX + 1)); + // Overflowing u32 products are rejected cleanly without wraparound. + assert!(draw_record_rejected(1 << 20, u32::MAX)); + assert!(draw_record_rejected(u32::MAX, u32::MAX)); + // Draw signature note/clear avoids stale address reuse. + let sig = 0x7600_A001usize; + note_draw_signature(sig, Some((20, 0, true))); + assert_eq!(draw_sig_of(sig), Some(DrawSig { byte_stride: 20, draw_offset: 0, indexed: true })); + note_draw_signature(sig, None); + assert_eq!(draw_sig_of(sig), None); + } } diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 8503cfc3d6..6702588310 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -89,15 +89,18 @@ fn drain_retired_ranges( retired: &mut VecDeque>, free: &mut Vec<(u32, u32)>, mut completed: impl FnMut(&F) -> u64, -) { +) -> bool { + let mut drained = false; while retired .front() .is_some_and(|r| r.marks.as_ref().is_some_and(|m| m.iter().all(|(f, v)| completed(f) >= *v))) { if let Some(r) = retired.pop_front() { merge_release(free, r.first, r.count); + drained = true; } } + drained } struct QueueFences(HashMap); @@ -159,6 +162,8 @@ struct Global { free: Vec<(u32, u32)>, /// released ranges awaiting live GPU queue completion before entering `free` retired: VecDeque>, + /// smallest allocation size that recently failed on a full/fragmented heap (`u32::MAX` = none) + smallest_failed: u32, } // D3D12 descriptor heaps and devices are free-threaded @@ -268,6 +273,7 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), retired: VecDeque::new(), + smallest_failed: u32::MAX, }); } true @@ -361,11 +367,17 @@ unsafe fn set_window_views_checked(dev: &ID3D12Device, windows: &[(usize, usize) fn reserve_global(count: u32) -> Option { let mut g = GLOBAL.write().unwrap(); let s = g.as_mut()?; - unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) } { + s.smallest_failed = u32::MAX; + } + if count >= s.smallest_failed { + return None; + } let (cap, mut next) = (s.cap, s.next); let r = take_range(&mut s.free, &mut next, cap, count); s.next = next; if r.is_none() { + s.smallest_failed = s.smallest_failed.min(count); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { crate::xlog_warn!("console descriptor heaps: the shared heap ({cap}) is full – shaders do not see the views of slots past it"); @@ -407,10 +419,13 @@ pub fn release_global(first: u32, count: u32) { if let Some(s) = GLOBAL.write().unwrap().as_mut() { if marks.as_ref().is_some_and(Vec::is_empty) { merge_release(&mut s.free, first, count); + s.smallest_failed = u32::MAX; } else { s.retired.push_back(RetiredRange { first, count, marks }); } - unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) } { + s.smallest_failed = u32::MAX; + } } } @@ -434,6 +449,23 @@ pub fn global_heap() -> Option { GLOBAL.read().unwrap().as_ref().map(|s| s.heap.clone()) } +/// Raw COM pointer of the shared shader-visible view heap without COM refcount traffic. +pub fn global_heap_raw() -> Option { + GLOBAL.read().unwrap().as_ref().map(|s| s.heap.as_raw() as usize) +} + +/// Binary-search `heaps` (sorted ascending by `shadow`) for the heap covering console handle `cpu`. +#[inline] +fn find_heap_by_addr(heaps: &[Heap], cpu: u64) -> Option<&Heap> { + let idx = heaps.partition_point(|h| (h.shadow as u64) <= cpu); + if idx == 0 { + return None; + } + let h = &heaps[idx - 1]; + let end = (h.shadow as u64).wrapping_add((h.n as u64) * (h.slot_bytes() as u64)); + (cpu < end).then_some(h) +} + /// Whether `obj` (a title's view heap) has its descriptors in the shared heap. pub fn in_global(obj: usize) -> bool { HEAPS.read().unwrap().iter().any(|h| h.obj == obj && !h.sampler && !h.pages.is_empty()) @@ -502,7 +534,11 @@ pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: } else { Vec::new() }; - HEAPS.write().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); + { + let mut heaps = HEAPS.write().unwrap(); + let idx = heaps.partition_point(|h| h.shadow < p as usize); + heaps.insert(idx, Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); + } true } @@ -510,7 +546,7 @@ pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: pub fn unregister(obj: usize) { let gone = { let mut heaps = HEAPS.write().unwrap(); - heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i)) + heaps.iter().position(|h| h.obj == obj).map(|i| heaps.remove(i)) }; if let Some(h) = gone { for (p, f) in h.pages.iter().enumerate().map(|(p, a)| (p, a.load(Ordering::Relaxed))).filter(|&(_, f)| f != UNMAPPED) { @@ -562,11 +598,7 @@ pub struct Slot { pub k: u32, } -/// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot -/// of a heap in the shared heap gets its page's place there now if the page has none yet. -pub fn slot(cpu: u64) -> Option { - let heaps = HEAPS.read().unwrap(); - let h = heaps.iter().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?; +fn resolve_slot(h: &Heap, cpu: u64) -> Slot { let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32; if h.sampler { let shared = sampler_page_of(h, k).and_then(|(first, k0)| { @@ -579,7 +611,7 @@ pub fn slot(cpu: u64) -> Option { // shared heap must map overflowed slots to reserved zero-sampler slot 0 rather than // aliasing unrelated heap entries at local index `k`. let (index, shared_srv) = shared.unwrap_or_else(|| (sampler_unmapped_index(!h.pages.is_empty(), k), 0)); - return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k }); + return Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k }; } let uav = ((2 * k + 1) * h.inc) as u64; let shared = page_of(h, k).and_then(|(first, k0)| { @@ -592,7 +624,23 @@ pub fn slot(cpu: u64) -> Option { let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or_else(|| { (view_unmapped_index(hosted, k), if hosted || h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0) }); - Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k }) + Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k } +} + +/// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot +/// of a heap in the shared heap gets its page's place there now if the page has none yet. +pub fn slot(cpu: u64) -> Option { + let heaps = HEAPS.read().unwrap(); + let h = find_heap_by_addr(&heaps, cpu)?; + Some(resolve_slot(h, cpu)) +} + +/// Resolve both `dst` and `src` console handles under a single `HEAPS` read lock. +pub fn slot_pair(dst: u64, src: u64) -> Option<(Slot, Slot)> { + let heaps = HEAPS.read().unwrap(); + let hd = find_heap_by_addr(&heaps, dst)?; + let hs = find_heap_by_addr(&heaps, src)?; + Some((resolve_slot(hd, dst), resolve_slot(hs, src))) } /// The view (or sampler) just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap. @@ -713,10 +761,10 @@ pub fn copy_words_range(dst: u64, src: u64, n: u32) -> bool { return true; } let heaps = HEAPS.read().unwrap(); - let Some(hd) = heaps.iter().find(|h| dst >= h.shadow as u64 && dst < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64) else { + let Some(hd) = find_heap_by_addr(&heaps, dst) else { return false; }; - let Some(hs) = heaps.iter().find(|h| src >= h.shadow as u64 && src < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64) else { + let Some(hs) = find_heap_by_addr(&heaps, src) else { return false; }; if hd.sampler != hs.sampler { @@ -899,6 +947,7 @@ struct GlobalSampler { next: u32, free: Vec<(u32, u32)>, retired: VecDeque>, + smallest_failed: u32, } unsafe impl Send for GlobalSampler {} @@ -967,6 +1016,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { next: 1, free: Vec::new(), retired: VecDeque::new(), + smallest_failed: u32::MAX, }); } true @@ -975,11 +1025,17 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { fn reserve_global_sampler(count: u32) -> Option { let mut g = GLOBAL_SAMPLER.write().unwrap(); let s = g.as_mut()?; - unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) } { + s.smallest_failed = u32::MAX; + } + if count >= s.smallest_failed { + return None; + } let (cap, mut next) = (s.cap, s.next); let r = take_range(&mut s.free, &mut next, cap, count); s.next = next; if r.is_none() { + s.smallest_failed = s.smallest_failed.min(count); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { crate::xlog_warn!("console descriptor heaps: the shared sampler heap ({cap}) is full – overflowed sampler slots map to reserved slot 0"); @@ -1016,10 +1072,13 @@ fn release_global_sampler(first: u32, count: u32) { if let Some(s) = GLOBAL_SAMPLER.write().unwrap().as_mut() { if marks.as_ref().is_some_and(Vec::is_empty) { merge_release(&mut s.free, first, count); + s.smallest_failed = u32::MAX; } else { s.retired.push_back(RetiredRange { first, count, marks }); } - unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) }; + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) } { + s.smallest_failed = u32::MAX; + } } } @@ -1028,6 +1087,11 @@ pub fn global_sampler_heap() -> Option { GLOBAL_SAMPLER.read().unwrap().as_ref().map(|s| s.heap.clone()) } +/// Raw COM pointer of the shared shader-visible sampler heap without COM refcount traffic. +pub fn global_sampler_heap_raw() -> Option { + GLOBAL_SAMPLER.read().unwrap().as_ref().map(|s| s.heap.as_raw() as usize) +} + /// Whether `obj` (a title's sampler heap) has its descriptors in the shared sampler heap. pub fn in_global_sampler(obj: usize) -> bool { HEAPS.read().unwrap().iter().any(|h| h.obj == obj && h.sampler && !h.pages.is_empty()) @@ -1128,7 +1192,7 @@ mod tests { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, - next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), retired: VecDeque::new(), + next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), retired: VecDeque::new(), smallest_failed: u32::MAX, }); let window = (&mut resource as *mut _ as usize, 0x10000); assert!(set_window_views_checked(&dev, &[window], true)); @@ -1323,7 +1387,7 @@ mod tests { *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), - cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), + cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), smallest_failed: u32::MAX, }); assert_eq!(reserve_global_sampler(4), Some(1)); assert_eq!(reserve_global_sampler(4), Some(5)); @@ -1338,10 +1402,11 @@ mod tests { assert_eq!(reserve_global_sampler(8), Some(1)); // Coalesced range ending at cursor straddles cleanly into the never-used tail. { - let mut g = GLOBAL_SAMPLER.write().unwrap(); - let s = g.as_mut().unwrap(); + let mut s = GLOBAL_SAMPLER.write().unwrap(); + let s = s.as_mut().unwrap(); s.next = 13; s.free.clear(); + s.smallest_failed = u32::MAX; } release_global_sampler(9, 2); release_global_sampler(11, 2); @@ -1382,12 +1447,12 @@ mod tests { *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), - cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), retired: VecDeque::new(), + cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), retired: VecDeque::new(), smallest_failed: u32::MAX, }); *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), - cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), + cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), smallest_failed: u32::MAX, }); if crate::gpu::uma::get().is_some() { assert!(register(0xC100, 16, 0x9000, 0, 16, true, true, true)); diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 39744893e0..20f4ad06e6 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1326,6 +1326,18 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi let stride = u32::from_le_bytes(pc[0..4].try_into().unwrap()); let dispatch_only = list.len() == 1 && list[0][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32 && stride >= 12 && stride % 4 == 0; super::bind::note_dispatch_only_signature(*ppv as usize, dispatch_only.then_some(stride)); + let draw_sig = (!needs_root).then(|| { + let idx = list.iter().position(|a| { + a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW.0 as u32 + || a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32 + })?; + let offset: u32 = list[..idx].iter().map(indirect_arg_bytes).sum(); + let indexed = list[idx][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED.0 as u32; + let min_arg = if indexed { 20u32 } else { 16u32 }; + (stride % 4 == 0 && offset % 4 == 0 && offset.checked_add(min_arg).is_some_and(|end| end <= stride)) + .then_some((stride, offset, indexed)) + }).flatten(); + super::bind::note_draw_signature(*ppv as usize, draw_sig); } hr } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 587cbb1315..6ac0684980 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1263,7 +1263,7 @@ fn bind_cache_enabled() -> bool { } /// Whether `SetPipelineState(pso)` resolved to `bound` is already active on `list` (same title -/// PSO and resolved PC PSO, with no pending/active depth-bias patch), allowing the redundant +/// PSO or resolved PC PSO, with no pending/active depth-bias patch), allowing the redundant /// D3D12 call and DRED marker to be skipped. pub(super) fn skip_redundant_pso_bind(list: *mut c_void, pso: usize, bound: usize) -> bool { if !bind_cache_enabled() || list.is_null() || pso == 0 || bound == 0 { @@ -1274,7 +1274,7 @@ pub(super) fn skip_redundant_pso_bind(list: *mut c_void, pso: usize, bound: usiz .unwrap() .as_ref() .and_then(|m| m.get(&(list as usize))) - .is_some_and(|s| s.bound_pso == pso && s.last_pc_pso == bound && !s.pso_dirty && !s.using_fallback_pso) + .is_some_and(|s| (s.bound_pso == pso || s.last_pc_pso == pso) && s.last_pc_pso == bound && !s.pso_dirty && !s.using_fallback_pso) } /// Track `SetPipelineState` on a command list (for `RSSetDepthBiasX`, `KickoffX`, and redundant @@ -4291,13 +4291,13 @@ unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: b /// title binds one buffer at many offsets (a ring it fills through the frame: a retail title's /// views all end at the buffer's end), so a mirror covers a 64 KiB-aligned range and a view /// inside a mirrored range uses that mirror at its offset. -static MIRRORS: Mutex> = Mutex::new(Vec::new()); +static MIRRORS: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); /// bytes of mirrors made (never freed) static MIRROR_BYTES: AtomicU64 = AtomicU64::new(0); /// Where `[va, va + bytes)` is in a mirror, if it is in one. fn mirrored(va: u64, bytes: usize) -> Option { - MIRRORS.lock().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m)| m + (va - s) as usize) + MIRRORS.read().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m)| m + (va - s) as usize) } /// Per mirror (start, bytes, a bit per 4 KiB page from `start & !0xfff`): pages of its source @@ -4307,14 +4307,15 @@ static MIRROR_STALE: Mutex)>> = Mutex::new(Vec::new()) /// odd while a look takes pages off the write-watch and has not handed them on yet: a draw /// then (or across one) copies its whole range static MIRROR_LOOK_SEQ: AtomicU64 = AtomicU64::new(0); -// the write-watch's answer for a draw's range (one per thread, like `title_textures`' look) +// the write-watch's answer and reusable dirty-page bitset for a draw's range (one per thread) thread_local! { static WRITTEN_BUF: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + static WRITTEN_BITS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; } /// The title's ranges with a mirror (start, end), which `title_textures`' look watches. pub(super) fn mirror_sources() -> Vec<(usize, usize)> { - MIRRORS.lock().unwrap().iter().map(|&(s, l, _)| (s as usize, s as usize + l)).collect() + MIRRORS.read().unwrap().iter().map(|&(s, l, _)| (s as usize, s as usize + l)).collect() } /// Changes when a mirror is made (`mirror_sources` then has a new range). @@ -4344,41 +4345,104 @@ pub(super) fn mirror_pages_written(dirty: &[usize]) { MIRROR_LOOK_SEQ.fetch_add(1, Ordering::SeqCst); } -/// The pages of `[a, end)` (from `a & !0xfff`, in the mirror of the buffer at `va`) a draw -/// copies: those on the write-watch (written since the last look) and those a look took off it -/// since the last copy (whose bits are cleared). None when the range is not write-watched. -unsafe fn written_pages(va: u64, a: usize, end: usize) -> Option> { +/// Call `on_run(first, end)` for every maximal contiguous run of set bits in `bits[..]` below `n`. +fn for_each_bitset_run(bits: &[u64], n: usize, mut on_run: impl FnMut(usize, usize)) { + let words = n.div_ceil(64).min(bits.len()); + let mut run_start: Option = None; + for (wi, &raw) in bits[..words].iter().enumerate() { + let valid_bits = (n - wi * 64).min(64); + let mask = if valid_bits == 64 { u64::MAX } else { (1u64 << valid_bits) - 1 }; + let mut w = raw & mask; + if w == 0 { + if let Some(s) = run_start.take() { + on_run(s, wi * 64); + } + continue; + } + if w == u64::MAX && valid_bits == 64 { + if run_start.is_none() { + run_start = Some(wi * 64); + } + continue; + } + let mut bit = 0usize; + while bit < valid_bits { + if run_start.is_some() { + let ones = (w >> bit).trailing_ones() as usize; + let take = ones.min(valid_bits - bit); + bit += take; + if bit < valid_bits { + let s = run_start.take().unwrap(); + on_run(s, wi * 64 + bit); + } + } else { + let zeros = (w >> bit).trailing_zeros() as usize; + bit += zeros; + if bit < valid_bits { + run_start = Some(wi * 64 + bit); + } + } + } + let _ = &mut w; + } + if let Some(s) = run_start { + on_run(s, n); + } +} + +/// Walk the dirty 4 KiB page runs of `[a, end)` (from `a & !0xfff`, in the mirror of the buffer at +/// `va`) using a reusable thread-local bitset: pages on the write-watch plus those a look took off +/// it since the last copy (whose bits are cleared). Returns `false` when not write-watched. +unsafe fn for_each_written_page_run(va: u64, a: usize, end: usize, mut on_run: impl FnMut(usize, usize)) -> bool { use windows_sys::Win32::System::Memory::GetWriteWatch; let base = a & !0xfff; let n = (end - base + 0xfff) >> 12; - let mut pages = vec![false; n]; - WRITTEN_BUF.with(|c| { - let mut buf = c.borrow_mut(); - if buf.len() < n { - buf.resize(n, std::ptr::null_mut()); - } - let (mut count, mut granularity) = (n, 0u32); - // (no reset: the look's to do, which hands the pages on) - if GetWriteWatch(0, base as *const c_void, n << 12, buf.as_mut_ptr(), &mut count, &mut granularity) != 0 || granularity != 0x1000 { - return None; - } - for &p in &buf[..count] { - pages[(p as usize - base) >> 12] = true; + let words = n.div_ceil(64); + WRITTEN_BITS.with(|bits_cell| { + let mut bits = bits_cell.borrow_mut(); + if bits.len() < words { + bits.resize(words, 0); + } + bits[..words].fill(0); + let ok = WRITTEN_BUF.with(|c| { + let mut buf = c.borrow_mut(); + if buf.len() < n { + buf.resize(n, std::ptr::null_mut()); + } + let (mut count, mut granularity) = (n, 0u32); + // (no reset: the look's to do, which hands the pages on) + if GetWriteWatch(0, base as *const c_void, n << 12, buf.as_mut_ptr(), &mut count, &mut granularity) != 0 || granularity != 0x1000 { + return false; + } + for &p in &buf[..count] { + let k = (p as usize - base) >> 12; + bits[k >> 6] |= 1u64 << (k & 63); + } + true + }); + if !ok { + return false; } - Some(()) - })?; - let mut g = MIRROR_STALE.lock().unwrap(); - if let Some((s, _, bits)) = g.iter_mut().find(|(s, l, _)| va >= *s && end as u64 <= *s + *l as u64) { - let first = (base - (*s as usize & !0xfff)) >> 12; - for (k, page) in pages.iter_mut().enumerate() { - let j = first + k; - if bits[j / 64] >> (j % 64) & 1 != 0 { - *page = true; - bits[j / 64] &= !(1 << (j % 64)); + { + let mut g = MIRROR_STALE.lock().unwrap(); + if let Some((s, _, stale)) = g.iter_mut().find(|(s, l, _)| va >= *s && end as u64 <= *s + *l as u64) { + let first = (base - (*s as usize & !0xfff)) >> 12; + for k in 0..n { + let j = first + k; + let sw = stale[j >> 6]; + let sm = 1u64 << (j & 63); + if sw & sm != 0 { + bits[k >> 6] |= 1u64 << (k & 63); + stale[j >> 6] = sw & !sm; + } + } } } - } - Some(pages) + for_each_bitset_run(&bits[..words], n, |first, last| { + on_run(base + (first << 12), base + (last << 12)); + }); + true + }) } /// `[from, from + len)` of the title's buffer at `va` (`bytes` long) into its mirror at @@ -4402,19 +4466,8 @@ unsafe fn copy_written(va: u64, mirror: usize, bytes: u32, from: u64, len: u64) } }; let seq = MIRROR_LOOK_SEQ.load(Ordering::SeqCst); - let Some(pages) = (seq % 2 == 0).then(|| written_pages(va, a, end)).flatten() else { return copy(a, end) }; - let base = a & !0xfff; - let mut k = 0; - while k < pages.len() { - if !pages[k] { - k += 1; - continue; - } - let first = k; - while k < pages.len() && pages[k] { - k += 1; - } - copy(base + (first << 12), base + (k << 12)); + if seq % 2 != 0 || !for_each_written_page_run(va, a, end, copy) { + return copy(a, end); } // a look took pages off the write-watch meanwhile, which may not have been handed on yet if MIRROR_LOOK_SEQ.load(Ordering::SeqCst) != seq { @@ -4428,7 +4481,7 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { if let Some(p) = mirrored(va, bytes) { return Some(p); } - let mut g = MIRRORS.lock().unwrap(); + let mut g = MIRRORS.write().unwrap(); // again under the lock: two lists binding one new range at once must share a mirror (a // second one would never be synced – every later lookup finds the first) if let Some(&(s, _, m)) = g.iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64) { @@ -4534,6 +4587,17 @@ unsafe fn set_index_buffer(list: *mut c_void, view: Option<&D3D12_INDEX_BUFFER_V f(list, view.map_or(std::ptr::null(), |v| v as *const _)); } +unsafe fn ensure_global_sampler_heap_raw() -> Option { + if let Some(s) = super::console_heap::global_sampler_heap_raw() { + return Some(s); + } + let dev_raw = real::device_raw(); + if let Some(dev) = ID3D12Device::from_raw_borrowed(&dev_raw) { + let _ = super::console_heap::shared_sampler_heap(dev); + } + super::console_heap::global_sampler_heap_raw() +} + /// Ensure the shared shader-visible PC sampler heap exists when a console device is live so /// directly-indexed root signatures (`SAMPLER_HEAP_DIRECTLY_INDEXED`) never run with 0 sampler /// heaps bound (D3D12 #1419 / `0x887A0001`). @@ -4647,18 +4711,18 @@ unsafe fn ensure_console_view_heap(this: *mut c_void) { /// Translated shaders with directly-indexed root signatures (`CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED` /// / `SAMPLER_HEAP_DIRECTLY_INDEXED`) and heap windows (`pso::heap_windows`) require valid /// shader-visible view and sampler heaps to be bound even if the title bound 0 heaps (or only a -/// view heap with 0 sampler heaps). -pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { - let view = if crate::gpu::recomp::pso::heap_windows() { - super::console_heap::global_heap() +/// view heap with 0 sampler heaps). Returns `true` when all required shared heaps exist and are +/// bound on `this` so callers may cache the check until `SetDescriptorHeaps` / `Reset`. +pub(super) unsafe fn ensure_view_heap(this: *mut c_void) -> bool { + let need_view = crate::gpu::recomp::pso::heap_windows(); + let view_raw = if need_view { + super::console_heap::global_heap_raw() } else { None }; - let sampler = ensure_global_sampler_heap(); - let view_raw = view.as_ref().map(|h| h.as_raw() as usize); - let sampler_raw = sampler.as_ref().map(|h| h.as_raw() as usize); + let sampler_raw = ensure_global_sampler_heap_raw(); if view_raw.is_none() && sampler_raw.is_none() { - return; + return false; } let mut to_bind: Option> = None; with_bindings(this, |b| { @@ -4671,6 +4735,7 @@ pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { if let Some(raw) = to_bind { pc::(this, 28)(this, raw.len() as u32, raw.as_ptr()); } + (!need_view || view_raw.is_some()) && sampler_raw.is_some() } /// console #32 SetDescriptorHeaps (PC #28) @@ -8973,6 +9038,8 @@ mod tests { assert!(!skip_redundant_pso_bind(list, 0x1000, 0x3000)); on_set_pipeline_state_bound(list, 0x1000, 0x3000); assert!(skip_redundant_pso_bind(list, 0x1000, 0x3000)); + // bind_abi re-binding the resolved PC PSO directly also hits the cache. + assert!(skip_redundant_pso_bind(list, 0x3000, 0x3000)); // Different title PSO -> must bind! assert!(!skip_redundant_pso_bind(list, 0x1001, 0x3001)); // ClearState / PC Reset / segment clear invalidate the cached PC PSO. @@ -9012,4 +9079,20 @@ mod tests { on_release(list as usize); } } + + #[test] + fn bitset_runs_emit_exact_contiguous_page_ranges() { + let collect = |bits: &[u64], n: usize| { + let mut runs = Vec::new(); + for_each_bitset_run(bits, n, |a, b| runs.push((a, b))); + runs + }; + assert_eq!(collect(&[0, 0], 100), vec![]); + assert_eq!(collect(&[u64::MAX, u64::MAX], 130), vec![(0, 128)]); + assert_eq!(collect(&[u64::MAX, u64::MAX, 0b11], 130), vec![(0, 130)]); + // Word-boundary straddle (bits 62..66), single bit 0, and trailing bit clipped by `n`. + let w0 = (1u64 << 0) | (1u64 << 62) | (1u64 << 63); + let w1 = (1u64 << 0) | (1u64 << 1) | (1u64 << 5) | (1u64 << 10); + assert_eq!(collect(&[w0, w1], 70), vec![(0, 1), (62, 66), (69, 70)]); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e050eb2900..82fd2dadfc 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2497,8 +2497,8 @@ pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, des /// Copy `n` console slots from `src` to `dst` (both in console heaps of one kind): the PC /// descriptors (2 per view slot) and the slots. False: not two console ranges. unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) -> bool { - use super::console_heap::{copy_words_range, slot}; - let (Some(d0), Some(s0)) = (slot(dst), slot(src)) else { return false }; + use super::console_heap::{copy_words_range, slot_pair}; + let Some((d0, s0)) = slot_pair(dst, src) else { return false }; if d0.sampler != s0.sampler { return false; } From 0b2df48a47ae5b99ff62fdf6634528cdb60b8239 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:02:31 +0100 Subject: [PATCH 162/258] d3d12x: close inline guard batch on draws and Enhanced/UAV barriers Break any active 256-slot InlineGuardBatch on graphics draws (DrawInstanced, DrawIndexedInstanced, DispatchMesh, graphics ExecuteIndirect) and mark prelude_blocked + close inline_guard on Enhanced/UAV barriers (uav_barrier_x and UAV resource_barrier_x) so memory-writing graphics shaders never race with a pre-draw indirect guard batch or hoisted prelude (#424). Also gate test-only indirect draw limit constants with #[cfg(test)] for zero warnings. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 11 ++++++++++- crates/xcl/src/hle/d3d12x/list_x.rs | 7 ++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 4ddeeaa67c..e0f4bd266f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -1601,9 +1601,11 @@ const PRELUDE_DRAW_DRED_LABEL: &str = "xcl prelude_guard_draw_args"; /// Exclusive upper bound on vertices/indices per instance in indirect Draw/DrawIndexed (`2^23` = /// `8,388,608`): any record with `verts >= 2^23` is zeroed to prevent garbage indirect-draw hangs. +#[cfg(test)] const DRAW_VERTS_PER_INST_LIMIT: u32 = 1 << 23; /// Inclusive upper bound on total vertices (`verts_per_inst * instances`, `2^26` = `67,108,864`): /// any record with `verts * instances > 2^26` is zeroed. +#[cfg(test)] const DRAW_TOTAL_VERTS_MAX: u32 = 1 << 26; /// Pure check matching `GUARD_DRAW_ARGS_*` / `PRELUDE_DRAW_GUARD_*`: true when an indirect @@ -3306,7 +3308,10 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: pc_dm(this, n * tp.mesh_groups_per_record, 1, 1); super::culprit::after_dispatch(list, m2); emit_uav_barrier(list, Some(&res_buf)); - with(this, |s| s.arg_order_clean = false); + with(this, |s| { + s.arg_order_clean = false; + s.inline_guard = None; + }); Ok(()) })(); match run { @@ -3663,7 +3668,10 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us with(this, |s| { s.arg_order_clean = false; s.prelude_blocked = true; + s.inline_guard = None; }); + } else { + with(this, |s| s.inline_guard = None); } } Err(e) => { @@ -3983,6 +3991,7 @@ fn pso_for_draw(pso: usize) -> usize { unsafe fn graphics_bound(this: *mut c_void) -> Option { let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let (pso, cached_gfx) = with(this, |s| { + s.inline_guard = None; let hit = s.pso_abi_cache.is_some_and(|c| c.query_pso == s.pso && c.is_gfx); (s.pso, hit) }); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 6ac0684980..af95a9fb36 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3619,6 +3619,7 @@ pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u3 /// writes become visible, parses any readable `D3D12_BARRIER_GROUP` texture barriers targeting /// tracked depth+UAV resources, and notifies `depth_uav` / `format_alias` of global UAV barriers. pub(super) unsafe extern "system" fn uav_barrier_x(this: *mut c_void, n: u32, barriers: *const c_void) { + super::bind::note_gpu_write(this); let b = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, @@ -5089,7 +5090,11 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 super::title_textures::note_transitions(this as usize, &t); } if !out.is_empty() { - super::bind::invalidate_inline_guard(this); + if any_uav || uav_transition { + super::bind::note_gpu_write(this); + } else { + super::bind::invalidate_inline_guard(this); + } pc::(this, PC_RESOURCE_BARRIER)(this, out.len() as u32, out.as_ptr()); if super::cpu_writes::has_water_readback() { const WRITE_STATES: u32 = UNORDERED_ACCESS | 0x4; // UNORDERED_ACCESS | RENDER_TARGET From 1471472710a0dca8c0495c27e1036ec6487f6fa2 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:54:14 +0100 Subject: [PATCH 163/258] KernelX: floor title thread priorities and restore fine timer on exit Complete Win11 scheduling hardening in kernelx/host/real: - Export guest SetThreadPriority in kernelx.rs and floor guest priorities below THREAD_PRIORITY_BELOW_NORMAL (IDLE / LOWEST) to BELOW_NORMAL unless XCL_PRIORITY=0, preventing Windows 11 hybrid E-core starvation of title streaming/background threads while leaving internal XCL pso_async workers (calling win32 directly) untouched. - Add winmm timeBeginPeriod(1) alongside NtSetTimerResolution(finest, 1) in kernelx::fine_timer(), and add idempotent restore_fine_timer() called on normal exit (host.rs) and forced/timed exit (real::end_title) so both timer-resolution requests are cleanly released on shutdown. - Add unit tests covering priority flooring (pure + live guest hook) and idempotent timer-resolution restoration. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 1 + crates/xcl/src/hle/kernelx.rs | 128 +++++++++++++++++++++++++++--- crates/xcl/src/host.rs | 2 + 3 files changed, 121 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 82fd2dadfc..e5dffe836c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4275,6 +4275,7 @@ pub fn end_title(code: u32) -> ! { } } drain_gpu(); + crate::hle::kernelx::restore_fine_timer(); crate::log::flush(); windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), code); } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 4b2514f6ce..3fd882494e 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -7,7 +7,7 @@ #![allow(non_snake_case)] use std::ffi::c_void; -use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use windows_sys::Win32::Foundation as fnd; use windows_sys::Win32::System::LibraryLoader as ll; @@ -78,6 +78,7 @@ pub fn exports() -> Vec<(&'static str, usize)> { SetThreadpoolAffinityMask, SetThreadAffinityMask, SetThreadGroupAffinity, + SetThreadPriority, QueryProcessorSchedulingStatistics, GetConsoleType, OutputDebugStringA, @@ -2197,6 +2198,35 @@ pub unsafe extern "system" fn SetThreadGroupAffinity(h: HANDLE, a: *const GROUP_ thr::SetThreadGroupAffinity(h, &fit, prev) } +fn priority_boost_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PRIORITY").map_or(true, |v| v.trim() != "0")) +} + +/// Floor guest/title thread priorities at `THREAD_PRIORITY_BELOW_NORMAL` (`-1`) so console +/// background/streaming threads requesting `LOWEST` (`-2`) or `IDLE` (`-15`) are not starved +/// on Windows 11 hybrid E-cores. Values `>= THREAD_PRIORITY_BELOW_NORMAL` (including normal, +/// high, time-critical, and background-mode flags) pass through unchanged. +fn clamp_thread_priority(priority: i32, floor_enabled: bool) -> i32 { + if floor_enabled && priority < thr::THREAD_PRIORITY_BELOW_NORMAL { + thr::THREAD_PRIORITY_BELOW_NORMAL + } else { + priority + } +} + +pub unsafe extern "system" fn SetThreadPriority(h: HANDLE, priority: i32) -> BOOL { + let clamped = clamp_thread_priority(priority, priority_boost_enabled()); + if clamped != priority { + static CLAMPED: AtomicU64 = AtomicU64::new(0); + let n = CLAMPED.fetch_add(1, Ordering::Relaxed) + 1; + if n <= 4 || n.is_power_of_two() { + crate::xlog_info!("SetThreadPriority: floored {priority} → {clamped} (THREAD_PRIORITY_BELOW_NORMAL; #{n})"); + } + } + thr::SetThreadPriority(h, clamped) +} + pub unsafe extern "system" fn QueryProcessorSchedulingStatistics(out: *mut [u64; 3]) { if out.is_null() { return; @@ -2239,6 +2269,16 @@ extern "system" { fn NtSetTimerResolution(desired: u32, set: u8, current: *mut u32) -> i32; } +#[link(name = "winmm", kind = "raw-dylib")] +extern "system" { + fn timeBeginPeriod(period: u32) -> u32; + fn timeEndPeriod(period: u32) -> u32; +} + +/// Active timer-resolution requests so `restore_fine_timer()` can cleanly release both on exit. +static TIMER_MM_ACTIVE: AtomicBool = AtomicBool::new(false); +static TIMER_NT_FINEST: AtomicU32 = AtomicU32::new(0); + pub fn host_os_version() -> (u32, u32, u32) { unsafe { let mut v: OsVersionInfoW = std::mem::zeroed(); @@ -2248,12 +2288,13 @@ pub fn host_os_version() -> (u32, u32, u32) { } } -/// The finest timer Windows offers (0.5 ms) for the title: with the default 15.6 ms tick every -/// sleep rounds up (a retail game's audio mixer ran at a third of real time). Windows 11 keeps -/// it while the window is hidden only when told to. Also opt out of Windows 11 Efficiency Mode +/// The finest timer Windows offers (0.5 ms via `NtSetTimerResolution`, plus `timeBeginPeriod(1)` +/// fallback) for the title: with the default 15.6 ms tick every sleep rounds up (a retail game's +/// audio mixer ran at a third of real time). Windows 11 keeps it while the window is hidden only +/// when told to. Also opt out of Windows 11 Efficiency Mode /// (`PROCESS_POWER_THROTTLING_EXECUTION_SPEED`) and lift process priority to `ABOVE_NORMAL` so /// foreground title rendering/streaming threads are not demoted behind background OS work -/// (`XCL_PRIORITY=0` disables priority boost). +/// (`XCL_PRIORITY=0` disables priority boost and thread-priority flooring). pub fn fine_timer() { use windows_sys::Win32::System::Threading::{ GetCurrentProcess, ProcessPowerThrottling, SetPriorityClass, SetProcessInformation, ABOVE_NORMAL_PRIORITY_CLASS, @@ -2281,29 +2322,63 @@ pub fn fine_timer() { }; unsafe { SetProcessInformation(GetCurrentProcess(), ProcessPowerThrottling, &eco_only as *const _ as *const c_void, size) }; } - let boosted = if std::env::var("XCL_PRIORITY").map_or(true, |v| v.trim() != "0") { + let boosted = if priority_boost_enabled() { unsafe { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS) != 0 } } else { false }; + let mm_ok = if TIMER_MM_ACTIVE.load(Ordering::Acquire) { + true + } else if unsafe { timeBeginPeriod(1) } == 0 { + TIMER_MM_ACTIVE.store(true, Ordering::Release); + true + } else { + false + }; // in 100 ns units; "finest" is the smallest period the system supports let (mut coarsest, mut finest, mut was) = (0u32, 0u32, 0u32); if unsafe { NtQueryTimerResolution(&mut coarsest, &mut finest, &mut was) } < 0 || finest == 0 { - crate::xlog_warn!("timer: NtQueryTimerResolution failed – Windows' default resolution (above-normal priority: {boosted})"); + crate::xlog_warn!( + "timer: NtQueryTimerResolution failed (winmm 1 ms: {}; above-normal priority: {})", + if mm_ok { "yes" } else { "no" }, + if boosted { "yes" } else { "no" } + ); return; } - let mut now = 0u32; - let status = unsafe { NtSetTimerResolution(finest, 1, &mut now) }; + let mut now = was; + let status = if TIMER_NT_FINEST.load(Ordering::Acquire) == finest { + 0 + } else { + let s = unsafe { NtSetTimerResolution(finest, 1, &mut now) }; + if s >= 0 { + TIMER_NT_FINEST.store(finest, Ordering::Release); + } + s + }; crate::xlog_info!( - "timer: {} (was {:.2} ms, now {:.2} ms; EcoQoS/timer-throttle off: {}; above-normal priority: {})", + "timer: {} (was {:.2} ms, now {:.2} ms; winmm 1 ms: {}; EcoQoS/timer-throttle off: {}; above-normal priority: {})", if status >= 0 { "finest resolution for the title" } else { "raising the resolution failed" }, was as f64 / 10_000.0, now as f64 / 10_000.0, + if mm_ok { "yes" } else { "no" }, if kept { "yes" } else { "no" }, if boosted { "yes" } else { "no" } ); } +/// Release the process's `NtSetTimerResolution` and `timeBeginPeriod(1)` requests on exit. +/// Idempotent so both normal returns and forced exits can call it safely. +pub fn restore_fine_timer() { + let finest = TIMER_NT_FINEST.swap(0, Ordering::AcqRel); + if finest != 0 { + let mut now = 0u32; + unsafe { NtSetTimerResolution(finest, 0, &mut now) }; + } + if TIMER_MM_ACTIVE.swap(false, Ordering::AcqRel) { + unsafe { timeEndPeriod(1) }; + } +} + pub unsafe extern "system" fn GetSystemOSVersion(out: *mut SystemOsVersionInfo) { if out.is_null() { return; @@ -2737,6 +2812,39 @@ mod tests { } let per = t.elapsed() / 20; assert!(per < std::time::Duration::from_millis(5), "Sleep(1) took {per:?}: the 15.6 ms tick"); + // Verify clean, idempotent exit restoration of NtSetTimerResolution + timeBeginPeriod(1). + restore_fine_timer(); + restore_fine_timer(); + assert!(!TIMER_MM_ACTIVE.load(Ordering::Acquire)); + assert_eq!(TIMER_NT_FINEST.load(Ordering::Acquire), 0); + } + + #[test] + fn thread_priority_floor_clamps_lowest_and_idle_to_below_normal() { + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_IDLE, true), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_LOWEST, true), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_BELOW_NORMAL, true), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_NORMAL, true), thr::THREAD_PRIORITY_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_ABOVE_NORMAL, true), thr::THREAD_PRIORITY_ABOVE_NORMAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_HIGHEST, true), thr::THREAD_PRIORITY_HIGHEST); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_TIME_CRITICAL, true), thr::THREAD_PRIORITY_TIME_CRITICAL); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_IDLE, false), thr::THREAD_PRIORITY_IDLE); + assert_eq!(clamp_thread_priority(thr::THREAD_PRIORITY_LOWEST, false), thr::THREAD_PRIORITY_LOWEST); + + // Live thread check through the exported guest hook: IDLE/LOWEST floor to BELOW_NORMAL. + if priority_boost_enabled() { + std::thread::spawn(|| unsafe { + let me = thr::GetCurrentThread(); + assert_ne!(SetThreadPriority(me, thr::THREAD_PRIORITY_IDLE), 0); + assert_eq!(thr::GetThreadPriority(me), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_ne!(SetThreadPriority(me, thr::THREAD_PRIORITY_LOWEST), 0); + assert_eq!(thr::GetThreadPriority(me), thr::THREAD_PRIORITY_BELOW_NORMAL); + assert_ne!(SetThreadPriority(me, thr::THREAD_PRIORITY_NORMAL), 0); + assert_eq!(thr::GetThreadPriority(me), thr::THREAD_PRIORITY_NORMAL); + }) + .join() + .unwrap(); + } } #[test] diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index f5e673bf80..10a95991b9 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -162,6 +162,7 @@ pub fn host_main(boot_path: &Path) -> i32 { Err(e) => { crate::xlog_error!("loading the game failed: {e}"); crate::report::write_final(Some(format!("loader: {e}"))); + crate::hle::kernelx::restore_fine_timer(); return 0x7C1_0002; } }; @@ -172,5 +173,6 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::hle::d3d12x::real::flush_pipeline_library(); crate::report::write_final(None); crate::log::flush(); + crate::hle::kernelx::restore_fine_timer(); code as i32 } From cb8eb0ef28f0999ce51003fa3294c54f1fafd011 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:04:39 +0100 Subject: [PATCH 164/258] D3D12.X: add 12s per-frame pipeline wait window per kind and prioritize deferred submits Give graphics and compute pipelines independent 12 s per-frame wait windows (XCL_PSO_FRAME_BUDGET_MS, default 12000 ms; 0 = skip immediately, off = disabled). Builds run on prioritized wanted xcl-pso-* workers so title threads always wake when a frame's window expires; once spent, remaining unready draws or dispatches for that kind return the stand-in for the current frame and retry with a fresh window on the next frame instead of stalling PresentX into title render watchdogs or dropping fast cold graphics draws permanently. Also mark deferred submits wanted immediately in need_by_submit so DXC/big-compile gates and preload workers prioritize them right away. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 30 +-- crates/xcl/src/hle/d3d12x/pso_async.rs | 254 +++++++++++++++++++++---- 2 files changed, 232 insertions(+), 52 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index e0f4bd266f..ca2d2075a9 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3976,11 +3976,10 @@ pub(super) unsafe fn emit_prepared_indexed_draw( list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); } -/// The pipeline a draw (or an ExecuteIndirect) uses now: a graphics pipeline still being built -/// is not waited for – its build goes to the workers and its stand-in, which draws nothing, is -/// used until it is built (`pso_async`). A compute one is waited for. Waiting held a retail -/// title's threads 1 – 5 s per draw in the driver's compiler (33 s in all as its world loaded, -/// on an NVIDIA GPU), and its hang watchdog ended it. +/// The pipeline a draw (or an ExecuteIndirect) uses now: both graphics and compute pipelines wait +/// within their own per-frame wait window (`XCL_PSO_FRAME_BUDGET_MS`, default 12 s per kind per +/// frame); once a frame's window is spent, remaining unready draws/dispatches get the stand-in +/// for this frame and retry on the next frame (`pso_async`). fn pso_for_draw(pso: usize) -> usize { super::pso_async::resolve_for_bind(pso) } @@ -4926,27 +4925,18 @@ void main(uint t : SV_GroupIndex) { } } - /// A draw does not wait for a graphics pipeline still being built: its build goes to the - /// workers and the draw gets the stand-in at once; once built, the real one. A compute - /// pipeline is still waited for. + /// Both graphics and compute draws wait within their per-frame pipeline wait window + /// (`XCL_PSO_FRAME_BUDGET_MS`) so cold compiles that finish in time render on their first use. #[test] - fn a_draw_does_not_wait_for_a_graphics_pipeline_still_being_built() { + fn a_draw_waits_for_a_graphics_pipeline_within_the_frame_window() { let (graphics, compute) = (0x7E57_6101usize, 0x7E57_6102usize); pso_async::submit_lazy(graphics, false, Box::new(|| { - std::thread::sleep(std::time::Duration::from_millis(1500)); + std::thread::sleep(std::time::Duration::from_millis(50)); 0x1301 }), 0); pso_async::submit_lazy(compute, true, Box::new(|| 0x1302), 0); - let t = std::time::Instant::now(); - assert_eq!(pso_for_draw(graphics), graphics, "the stand-in, not the real one"); - assert!(t.elapsed() < std::time::Duration::from_millis(500), "a draw waited {:?}", t.elapsed()); - // the draw sent it to the workers: it is built with no further draw - let start = std::time::Instant::now(); - while pso_async::is_pending(graphics) && start.elapsed() < std::time::Duration::from_secs(10) { - std::thread::sleep(std::time::Duration::from_millis(5)); - } - assert_eq!(pso_for_draw(graphics), 0x1301, "built by a worker"); - assert_eq!(pso_for_draw(compute), 0x1302, "a compute pipeline is waited for"); + assert_eq!(pso_for_draw(graphics), 0x1301, "graphics waited within frame window"); + assert_eq!(pso_for_draw(compute), 0x1302, "compute waited within frame window"); pso_async::released(graphics); pso_async::released(compute); } diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 039f698c17..0d8a3797d7 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1406,8 +1406,8 @@ pub fn resolve(pso: usize) -> usize { } } -/// `resolve`, waiting for a pipeline still being built – built here if no worker has started -/// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). +/// `resolve`, waiting for a pipeline still being built within the per-frame wait window +/// (`XCL_PSO_FRAME_BUDGET_MS`, default 12 s per kind per frame). pub fn resolve_wait(pso: usize) -> usize { resolve_wait_for(pso, wait_budget()) } @@ -1484,41 +1484,167 @@ fn set_submit_wait_for_test(most: Option) { SUBMIT_WAIT_FOR_TEST.with(|b| b.set(most)); } -/// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). +/// `resolve_wait`, waiting at most `budget` per pipeline (and at most the remaining +/// per-frame window for this pipeline's kind). fn resolve_wait_for(pso: usize, budget: Option) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); if p.spared.load(Ordering::Acquire) || p.bvh_traversal.load(Ordering::Acquire) { return resolve_spared(&p, pso); } - // (the title's thread is held from here until the pipeline is built or the budget is over) - let _held = (!*p.done.lock().unwrap()).then(Held::new); - if let Some(budget) = budget { - return resolve_within(&p, pso, budget); + let frame = super::present::presents(); + resolve_wait_in(&p, pso, budget, frame_budget(), frame, kind_frame_budget(p.compute)) +} + +/// Default per-frame pipeline wait window (`12 s`) for each kind (`graphics`, `compute`). +const DEFAULT_FRAME_BUDGET_MS: u64 = 12_000; + +/// Parses `XCL_PSO_FRAME_BUDGET_MS`: unset/empty defaults to `12_000 ms` (`12 s`), `0` skips +/// waiting immediately, `off` / `none` disables the per-frame cap, and a positive integer sets +/// the per-frame window in milliseconds for each kind (`graphics`, `compute`). +fn parse_frame_budget(val: Option<&str>) -> Option { + let Some(raw) = val.map(str::trim).filter(|s| !s.is_empty()) else { + return Some(std::time::Duration::from_millis(DEFAULT_FRAME_BUDGET_MS)); + }; + if raw.eq_ignore_ascii_case("off") || raw.eq_ignore_ascii_case("none") { + return None; } - if p.deprioritized.load(Ordering::Acquire) && !building_here() { - // Heavy non-RT producer compute PSO: mark wanted BEFORE enqueueing so it jumps straight - // to the front of `PsoQueue` on `xcl-pso-*` workers (under `BIG_COMPILES`/`GIANT_COMPILES` - // gating) and wait until ready so the producer dispatch is NEVER skipped. - p.want(); + match raw.parse::() { + Ok(ms) => Some(std::time::Duration::from_millis(ms)), + Err(_) => Some(std::time::Duration::from_millis(DEFAULT_FRAME_BUDGET_MS)), + } +} + +fn frame_budget() -> Option { + static B: OnceLock> = OnceLock::new(); + *B.get_or_init(|| parse_frame_budget(std::env::var("XCL_PSO_FRAME_BUDGET_MS").ok().as_deref())) +} + +static FRAME_BUDGET_GFX: Mutex = Mutex::new(FrameWaitBudget::new()); +static FRAME_BUDGET_CS: Mutex = Mutex::new(FrameWaitBudget::new()); + +fn kind_frame_budget(compute: bool) -> &'static Mutex { + if compute { &FRAME_BUDGET_CS } else { &FRAME_BUDGET_GFX } +} + +/// Waits for `p` within both an optional per-PSO cap (`budget`) and an optional per-frame +/// per-kind window (`frame_cap` tracked in `frame_state` for `frame`). Builds run on +/// `xcl-pso-*` workers (prioritized as `wanted`) so the caller always wakes when the window +/// expires; once a frame's window is spent, remaining unready draws/dispatches return the +/// stand-in for this frame and retry with a fresh window on the next frame. +fn resolve_wait_in( + p: &Arc, + pso: usize, + budget: Option, + frame_cap: Option, + frame: u64, + frame_state: &Mutex, +) -> usize { + let built = |p: &Pending| match p.real.load(Ordering::Acquire) { + 0 => p.stand(pso), + r => r, + }; + let r = p.real.load(Ordering::Acquire); + if r != 0 { + return r; + } + if *p.done.lock().unwrap() { + return built(p); + } + if budget.is_some() && p.late.load(Ordering::Acquire) { if !p.sent.swap(true, Ordering::AcqRel) { enqueue(p.clone()); } - } else { + return p.stand(pso); + } + // Recursive resolve on a worker thread: run inline to avoid worker-pool deadlock. + if building_here() { let job = p.job.lock().unwrap().take(); if let Some(job) = job { - complete(&p, job()); + complete(p, job()); } p.want(); + let mut done = p.done.lock().unwrap(); + while !*done { + done = p.cv.wait(done).unwrap(); + } + return built(p); } - let mut done = p.done.lock().unwrap(); - while !*done { - done = p.cv.wait(done).unwrap(); + // Mark wanted BEFORE enqueueing so `PsoQueue::pop` jumps this pipeline ahead of background + // and deprioritized builds and preload workers raise priority immediately. + p.want(); + if !p.sent.swap(true, Ordering::AcqRel) { + enqueue(p.clone()); } - match p.real.load(Ordering::Acquire) { - 0 => p.stand(pso), - r => r, + let Some(fcap) = frame_cap else { + if !p.compute { + return p.stand(pso); + } + let _held = Held::new(); + if let Some(b) = budget { + return resolve_within(p, pso, b); + } + if !p.deprioritized.load(Ordering::Acquire) { + let job = p.job.lock().unwrap().take(); + if let Some(job) = job { + complete(p, job()); + } + } + let mut done = p.done.lock().unwrap(); + while !*done { + done = p.cv.wait(done).unwrap(); + } + return built(p); + }; + let rem = frame_state.lock().unwrap().remaining(frame, fcap); + if rem.is_zero() { + return p.stand(pso); + } + let (wait_for, per_pso_binding) = match budget { + Some(b) if b <= rem => (b, true), + _ => (rem, false), + }; + let _held = Held::new(); + let t0 = std::time::Instant::now(); + let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), wait_for, |d| !*d).unwrap(); + let finished = *done; + drop(done); + let elapsed = t0.elapsed(); + if finished { + frame_state.lock().unwrap().record(frame, elapsed); + return built(p); } + if per_pso_binding { + frame_state.lock().unwrap().record(frame, elapsed); + p.late.store(true, Ordering::Release); + static N: AtomicUsize = AtomicUsize::new(0); + let n = N.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + crate::xlog_warn!( + "D3D12.X: a pipeline still being built after {} ms: its binds go on without it until it is built ({} so far)", + wait_for.as_millis(), + n + 1 + ); + } + } else { + // Clamp recorded wait to `rem` on frame-budget timeout so OS timer jitter cannot leave a + // sub-millisecond sliver causing subsequent unready calls on this frame to spin. + // Do NOT set `p.late` so the pipeline is retried with a fresh window on the next frame. + frame_state.lock().unwrap().record(frame, elapsed.max(rem)); + static N_GFX: AtomicUsize = AtomicUsize::new(0); + static N_CS: AtomicUsize = AtomicUsize::new(0); + let counter = if p.compute { &N_CS } else { &N_GFX }; + let n = counter.fetch_add(1, Ordering::Relaxed); + if n < 16 || n.is_power_of_two() { + let kind = if p.compute { "compute" } else { "graphics" }; + crate::xlog_warn!( + "D3D12.X: {kind} pipeline wait window ({} ms) spent on frame {frame}: skipping remaining unready {kind} work until next frame ({} so far)", + fcap.as_millis(), + n + 1 + ); + } + } + p.stand(pso) } /// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until @@ -1723,19 +1849,12 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { } } -/// For binding: compute pipelines are waited for, graphics ones are not. +/// For binding: both graphics and compute pipelines wait within their own per-frame wait window +/// (`XCL_PSO_FRAME_BUDGET_MS`, default 12 s per kind per frame). Once a frame's window for that +/// kind is spent, remaining unready draws/dispatches get the stand-in and retry on the next frame. pub fn resolve_for_bind(pso: usize) -> usize { match entry(pso) { - Some(p) if p.compute => resolve_wait(pso), - Some(p) => { - let bound = resolve(pso); - // a draw needs it now and goes on without it (`bind::pso_for_draw`): its build does not - // wait for free commit, which the speculative ones do - if !*p.done.lock().unwrap() { - p.want(); - } - bound - } + Some(_) => resolve_wait(pso), None => pso, } } @@ -1774,9 +1893,11 @@ pub fn want(pso: usize) { } } -/// A call with `pso` was put off to the submit: its build goes before the workers' queue. +/// A call with `pso` was put off to the submit: its build goes before the workers' queue +/// and is immediately marked wanted so DXC / big-compile gates and preload threads prioritize it. pub fn need_by_submit(pso: usize) { let Some(p) = entry(pso) else { return }; + p.want(); if !std::mem::replace(&mut p.demand.lock().unwrap().by_submit, true) { NEEDED.lock().unwrap().push_back(p); queue().push(Box::new(|| ()), None); @@ -1927,4 +2048,73 @@ mod pso_queue_tests { assert_eq!(released(standin), 0); assert_eq!(resolve(standin), standin); } + + #[test] + fn frame_budget_env_parsing() { + let ms = std::time::Duration::from_millis; + assert_eq!(parse_frame_budget(None), Some(ms(12_000))); + assert_eq!(parse_frame_budget(Some("")), Some(ms(12_000))); + assert_eq!(parse_frame_budget(Some("0")), Some(ms(0))); + assert_eq!(parse_frame_budget(Some("5000")), Some(ms(5000))); + assert_eq!(parse_frame_budget(Some("off")), None); + assert_eq!(parse_frame_budget(Some("none")), None); + assert_eq!(parse_frame_budget(Some("bad")), Some(ms(12_000))); + } + + #[test] + fn frame_budget_waits_within_window_skips_rest_of_frame_and_retries_next_frame() { + use std::time::{Duration, Instant}; + + let gfx_budget = Mutex::new(FrameWaitBudget::new()); + let cs_budget = Mutex::new(FrameWaitBudget::new()); + let cap = Some(Duration::from_millis(60)); + + let (g_fast, g_slow1, g_slow2, c_fast) = (0x7E57_F001usize, 0x7E57_F002usize, 0x7E57_F003usize, 0x7E57_F004usize); + let (go_tx, go_rx) = mpsc::channel::<()>(); + let (go2_tx, go2_rx) = mpsc::channel::<()>(); + submit_lazy(g_fast, false, Box::new(|| { + std::thread::sleep(Duration::from_millis(10)); + 0xF101 + }), 0); + submit_lazy(g_slow1, false, Box::new(move || { + let _ = go_rx.recv(); + 0xF102 + }), 0); + submit_lazy(g_slow2, false, Box::new(move || { + let _ = go2_rx.recv(); + 0xF103 + }), 0); + submit_lazy(c_fast, true, Box::new(|| { + std::thread::sleep(Duration::from_millis(10)); + 0xF104 + }), 0); + + // Frame 1: fast graphics PSO finishes within the 60 ms graphics window. + let p_fast = entry(g_fast).unwrap(); + assert_eq!(resolve_wait_in(&p_fast, g_fast, None, cap, 1, &gfx_budget), 0xF101); + + // Frame 1: slow graphics PSO spends the rest of frame 1's graphics window and skips. + let p_slow1 = entry(g_slow1).unwrap(); + assert_eq!(resolve_wait_in(&p_slow1, g_slow1, None, cap, 1, &gfx_budget), g_slow1); + + // Frame 1: second unready graphics PSO sees 0 ms remaining and skips immediately. + let p_slow2 = entry(g_slow2).unwrap(); + let t0 = Instant::now(); + assert_eq!(resolve_wait_in(&p_slow2, g_slow2, None, cap, 1, &gfx_budget), g_slow2); + assert!(t0.elapsed() < Duration::from_millis(25), "spent frame budget must skip immediately ({:?})", t0.elapsed()); + + // Frame 1: compute has its own independent per-frame window and completes cleanly! + let p_cs = entry(c_fast).unwrap(); + assert_eq!(resolve_wait_in(&p_cs, c_fast, None, cap, 1, &cs_budget), 0xF104); + + // Release both slow graphics workers and retry on Frame 2: both resolve (not stuck `late`)! + go_tx.send(()).unwrap(); + go2_tx.send(()).unwrap(); + assert_eq!(resolve_wait_in(&p_slow1, g_slow1, None, Some(Duration::from_secs(5)), 2, &gfx_budget), 0xF102); + assert_eq!(resolve_wait_in(&p_slow2, g_slow2, None, Some(Duration::from_secs(5)), 2, &gfx_budget), 0xF103); + + for s in [g_fast, g_slow1, g_slow2, c_fast] { + let _ = released(s); + } + } } From 806eee33d46c895d412d283b72c34ea49a315c76 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:06:06 +0100 Subject: [PATCH 165/258] D3D12.X: skip AMD stub .pso disk cache (#2577) and evict retired texture caches (#2578) Adapt two cache-safe stability fixes cleanly onto origin/amd-dev (bf02341f): - #2577 (real.rs, shaders.rs): record the chosen adapter's PCI vendor ID in driver_cache::note_vendor() and disable on-disk .pso driver blobs on AMD (0x1002) unless XCL_PSO_DISK_CACHE=1, avoiding device removals from stale 954-byte driver cache stubs written before a crash/kill (#2512). Adds driver_cache::tests::blobs_are_kept_on_disk_unless_they_are_references. - #2578 (title_textures.rs): return all retired resource pointers from Table::retire_range() so retire_overlapping() evicts LAST_CONTENT and STREAM_RECHECK for every retired texture (not only placed unmap targets). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 45 +++++++++++++++++++-- crates/xcl/src/hle/d3d12x/title_textures.rs | 37 +++++++++++------ crates/xcl/src/shaders.rs | 1 + 3 files changed, 68 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index e5dffe836c..238a046f9c 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -569,6 +569,7 @@ pub fn init() -> Result { } for (adapter, desc) in list { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { + driver_cache::note_vendor(desc.VendorId); device = Some(dev); name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; @@ -5457,7 +5458,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL /// and the program compiled as before). `XCL_PSO_DISK_CACHE=0`: off. pub(crate) mod driver_cache { use std::path::{Path, PathBuf}; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; /// builds shorter than this are not worth a file const KEEP: std::time::Duration = std::time::Duration::from_millis(250); @@ -5482,9 +5483,37 @@ pub(crate) mod driver_cache { format!("gfx-{hash:016x}-{bytes:x}.pso") } + /// On AMD (`0x1002`), `ID3D12PipelineState::GetCachedBlob` hands out ~954-byte references into + /// the driver's own shader cache rather than self-contained ISA (#2512). A stale reference left + /// by a crashed or killed run can remove the device when passed back in `CachedPSO`. Skip + /// on-disk `.pso` blobs on AMD unless explicitly opted in with `XCL_PSO_DISK_CACHE=1`. + static STUBS: AtomicBool = AtomicBool::new(false); + + /// Record the chosen adapter's PCI vendor ID (`DXGI_ADAPTER_DESC1::VendorId`). + pub fn note_vendor(vendor: u32) { + let stubs = stub_vendor(vendor); + let was = STUBS.swap(stubs, Ordering::Relaxed); + if stubs && !was && !enabled() { + crate::xlog_info!("D3D12.X: an AMD driver's pipeline blobs only name entries of its own cache – none kept on disk (XCL_PSO_DISK_CACHE=1 keeps them)"); + } + } + + fn stub_vendor(vendor: u32) -> bool { + vendor == 0x1002 + } + + /// `XCL_PSO_DISK_CACHE`: "0" off, "1" on, unset: on unless the driver's blobs are references. + fn env_setting() -> Option { + static ON: std::sync::OnceLock> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").ok().map(|v| v.trim() != "0")) + } + + fn enabled_with(setting: Option, stubs: bool) -> bool { + setting.unwrap_or(!stubs) + } + fn enabled() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0")) + enabled_with(env_setting(), STUBS.load(Ordering::Relaxed)) } pub fn path(dxil: &[u8], flags: i32) -> Option { @@ -5585,6 +5614,16 @@ pub(crate) mod driver_cache { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } + #[test] + fn blobs_are_kept_on_disk_unless_they_are_references() { + assert!(stub_vendor(0x1002), "AMD"); + assert!(!stub_vendor(0x10DE) && !stub_vendor(0x8086) && !stub_vendor(0x1414), "NVIDIA, Intel, WARP"); + assert!(enabled_with(None, false)); + assert!(!enabled_with(None, true)); + assert!(enabled_with(Some(true), true), "XCL_PSO_DISK_CACHE=1 keeps them"); + assert!(!enabled_with(Some(false), false), "XCL_PSO_DISK_CACHE=0 turns them off"); + } + #[test] fn a_file_is_named_after_its_dxil_and_flags() { assert_eq!(name(b"abc", 0), name(b"abc", 0)); diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d3197f4058..6d99fd7688 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -257,9 +257,9 @@ impl Table { /// Permanently retire active and shadowed entries overlapping `[va, end)` (used when a /// GPU-owned render target / depth / UAV overwrites the address range). Returns - /// `(pending_delta, retired_count, placed_res_to_unmap)`. - fn retire_range(&mut self, va: usize, end: usize) -> (isize, usize, Vec) { - let (mut pending_delta, mut retired, mut to_unmap) = (0isize, 0usize, Vec::new()); + /// `(pending_delta, retired_res, placed_res_to_unmap)`. + fn retire_range(&mut self, va: usize, end: usize) -> (isize, Vec, Vec) { + let (mut pending_delta, mut retired, mut to_unmap) = (0isize, Vec::new(), Vec::new()); for (ova, ores, _) in self.active_overlaps(va, end) { self.by_va.remove(&(ova, ores)); if let Some(old) = self.by_res.remove(&ores) { @@ -270,7 +270,7 @@ impl Table { if old.placed && !old.unmapped { to_unmap.push(ores); } - retired += 1; + retired.push(ores); } } for (sva, sres, _) in self.shadowed_overlaps(va, end) { @@ -279,7 +279,7 @@ impl Table { if old.placed && !old.unmapped { to_unmap.push(sres); } - retired += 1; + retired.push(sres); } } if self.shadowed.is_empty() { @@ -653,30 +653,43 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { .into_iter() .filter(|&g| g != va && mirror_source(g) == va) .collect(); - let (retired, to_unmap) = { + let (retired_ptrs, to_unmap) = { let mut t = TEXTURES.lock().unwrap(); - let (mut delta, mut retired, mut unmap_ptrs) = t.retire_range(va, va.saturating_add(len)); + let (mut delta, mut retired_ptrs, mut unmap_ptrs) = t.retire_range(va, va.saturating_add(len)); if src != va { let (d2, r2, u2) = t.retire_range(src, src.saturating_add(len)); delta += d2; - retired += r2; + retired_ptrs.extend(r2); unmap_ptrs.extend(u2); } for g in gpu_aliases { let (d3, r3, u3) = t.retire_range(g, g.saturating_add(len)); delta += d3; - retired += r3; + retired_ptrs.extend(r3); unmap_ptrs.extend(u3); } adjust_pending(delta); TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); - (retired, clone_resources(&unmap_ptrs)) + (retired_ptrs, clone_resources(&unmap_ptrs)) }; + if !retired_ptrs.is_empty() { + { + let mut last = LAST_CONTENT.lock().unwrap(); + for &r in &retired_ptrs { + last.remove(&r); + } + } + { + let mut g = STREAM_RECHECK.lock().unwrap(); + for &r in &retired_ptrs { + g.remove(&r); + } + } + } for r in &to_unmap { - LAST_CONTENT.lock().unwrap().remove(&(r.as_raw() as usize)); super::vram::unmap_superseded(r); } - if retired > 0 { + if !retired_ptrs.is_empty() { TEXTURES_GEN.fetch_add(1, Ordering::Release); } } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 89385152e1..239fda9448 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1452,6 +1452,7 @@ impl Pipelines { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; let sel = crate::gpu::adapter::Selector::from_env_or("auto"); let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + crate::hle::d3d12x::real::driver_cache::note_vendor(desc.VendorId); let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; // Match `real::init`'s adapter string verbatim so offline `--precompile --pipelines` // opens and populates the exact same `pso-library//gen-*.plib` directory. From e4b66e577ca9992c140c7004aed62181267f7894 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:18:47 +0100 Subject: [PATCH 166/258] D3D12.X / KernelX: lazy-commit alloc_vram_only sparse buffers on CPU access (#2582) Fix #2582 (0xc0000005 CPU write AV inside sparse UMA windows on buffers backed by OutsideBufferTable / sparse::alloc_vram_only): - place_at_title_address stored alloc_vram_only's uncommitted sparse VA (holes = 0xFFFF, MEM_RESERVE only) in UMA_BUFFERS, so GetGPUVirtualAddress and Map handed that uncommitted VA back to the title. When the title later CPU-wrote through it (e.g. clearing a 128x0x5c0 table), Windows raised 0xc0000005. - Mark alloc_vram_only 64 KiB pages with kernelx::lazy::mark (0 upfront CPU commit, GPU-only buffers keep holes = 0xFFFF and never clobber UAV writes) and unmark + MEM_DECOMMIT them cleanly in free_vram_only. - When the title first CPU-touches a page, kernelx::lazy::commit commits it and queues it via sparse::note_lazy_commit (without locking sparse::STATE inside the VEH); before_execute, readback_now, readback_after_execute, and decommit_range drain LAZY_COMMITS to clear entry.holes without touching to_zero so only CPU-written 4 KiB pages upload to VRAM. - In real::res_map, call kernelx::lazy::ensure(p, bytes) before readback_now so Map() on a lazy sparse buffer commits pages before VRAM->CPU copy. - Add regression test lazy_commit_clears_vram_only_holes_without_clobbering_to_zero. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 3 + crates/xcl/src/hle/d3d12x/sparse.rs | 93 ++++++++++++++++++++++++++++- crates/xcl/src/hle/kernelx/lazy.rs | 5 +- 3 files changed, 97 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 238a046f9c..8d7bf972c3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1924,6 +1924,9 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v // the start of the PC resource, before the address for a buffer placed below it) if let Some((p, bytes)) = console_buffer(this as usize) { if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p)) { + // If this buffer uses a lazy VRAM-only sparse backing (`alloc_vram_only`, #2582), + // commit its CPU pages before readback or returning the pointer to the title. + let _opened = crate::hle::kernelx::lazy::ensure(p, bytes); if !range.is_null() { let r = *(range as *const D3D12_RANGE); if r.End > r.Begin { diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 638aaaa6bc..374c6ab5a7 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1283,8 +1283,25 @@ pub unsafe fn free(p: usize) -> bool { u.sparse_release(p).is_some() } -/// Allocate a VRAM-only sparse block (zero CPU commit, `holes = 0xFFFF` so CPU write-watch -/// never overwrites GPU UAV writes) for GPU-writable buffers placed outside the UMA windows. +/// 64 KiB sparse pages lazily committed by `kernelx::lazy` when the title first CPU-touches a +/// `alloc_vram_only` buffer (queued without locking `STATE` so the VEH can never deadlock). +static LAZY_COMMITS: Mutex> = Mutex::new(Vec::new()); +static HAS_LAZY_COMMITS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Record that `kernelx::lazy` just CPU-committed 64 KiB page `page`. Safe inside the VEH: +/// never acquires `STATE`. +pub(crate) fn note_lazy_commit(page: usize) { + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(page)) { + LAZY_COMMITS.lock().unwrap_or_else(|e| e.into_inner()).push(page); + HAS_LAZY_COMMITS.store(true, Ordering::Release); + } +} + +/// Allocate a VRAM-only sparse block (zero upfront CPU commit, `holes = 0xFFFF` so CPU +/// write-watch never overwrites GPU UAV writes) for GPU-writable buffers placed outside the UMA +/// windows. Each 64 KiB page is marked with `kernelx::lazy` so if the title later CPU-writes or +/// reads it (via `GetGPUVirtualAddress()` or `Map()`, #2582), the page commits on demand and +/// subsequent CPU writes upload cleanly to sparse VRAM. pub unsafe fn alloc_vram_only(size: usize, align: usize) -> Option<(usize, usize)> { let u = crate::gpu::uma::get()?; let (addr, rounded) = u.sparse_alloc(size, align.max(TILE))?; @@ -1307,17 +1324,25 @@ pub unsafe fn alloc_vram_only(size: usize, align: usize) -> Option<(usize, usize u.sparse_release(addr); return None; } + for page in (addr..addr + rounded).step_by(TILE) { + crate::hle::kernelx::lazy::mark(page); + } Some((addr, rounded)) } -/// Release a VRAM-only sparse block from `alloc_vram_only` (defers tile unmap behind GPU fences). +/// Release a VRAM-only sparse block from `alloc_vram_only` (unmarks lazy pages, defers tile +/// unmap behind GPU fences, and decommits any pages that were lazily committed by CPU access). pub unsafe fn free_vram_only(p: usize) -> bool { let Some(u) = crate::gpu::uma::get() else { return false }; if !u.is_sparse(p) { return false; } let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false }; + for page in (start..start + len).step_by(TILE) { + crate::hle::kernelx::lazy::unmark(page); + } decommitted(start, len); + VirtualFree(start as *mut c_void, len, MEM_DECOMMIT); u.sparse_release(p).is_some() } @@ -1336,6 +1361,7 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz } let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; + s.drain_lazy_commits(); s.note_queue(queue); let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); if filtered.is_empty() { @@ -1445,6 +1471,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { if s.window_index(va).is_none() { return; } + s.drain_lazy_commits(); let zeroed = std::mem::take(&mut s.to_zero); if !zeroed.is_empty() { for &(a, n) in &zeroed { @@ -1640,9 +1667,25 @@ impl State { } } + /// Clear hole masks for 64 KiB tiles lazily CPU-committed by `kernelx::lazy` (#2582). + /// Leaves `to_zero` untouched so existing GPU VRAM contents remain intact while subsequent + /// write-watch dirty 4 KiB pages upload cleanly from the CPU view. + fn drain_lazy_commits(&mut self) { + if !HAS_LAZY_COMMITS.swap(false, Ordering::AcqRel) { + return; + } + let pages = std::mem::take(&mut *LAZY_COMMITS.lock().unwrap_or_else(|e| e.into_inner())); + for page in pages { + if let Some(entry) = self.mapped.get_mut(&(page & !(TILE - 1))) { + entry.holes = 0; + } + } + } + /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps /// them and frees their pool tiles) unsafe fn decommit_range(&mut self, a: usize, n: usize) { + self.drain_lazy_commits(); let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); let mut t = a & !(TILE - 1); let end = a.saturating_add(n); @@ -1916,6 +1959,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let gpu_view_prep = if gpu_view::on() { gpu_view::prepare_sync() } else { None }; let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; + s.drain_lazy_commits(); s.note_queue(queue); // the title's work sees what was decommitted unmapped, as it was let flushed = s.flush_parked(); @@ -3082,4 +3126,47 @@ mod tests { assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } } + + #[test] + fn lazy_commit_clears_vram_only_holes_without_clobbering_to_zero() { + let mut mapped = BTreeMap::new(); + let tile_a = 0x4_6eb2_0000usize; + let tile_unmapped = 0x4_6eb3_0000usize; + mapped.insert(tile_a, TileEntry { pool: (0, 0), holes: 0xFFFF, sent: std::array::from_fn(|_| None) }); + { + let mut g = LAZY_COMMITS.lock().unwrap_or_else(|e| e.into_inner()); + g.clear(); + g.push(tile_a + 0x5920); + g.push(tile_unmapped); + } + HAS_LAZY_COMMITS.store(true, Ordering::Release); + + // Drain via the exact same logic used by `State::drain_lazy_commits`: + // mapped tile clears all holes (`0xFFFF -> 0`), unmapped tile is ignored cleanly. + assert!(HAS_LAZY_COMMITS.swap(false, Ordering::AcqRel)); + let pages = std::mem::take(&mut *LAZY_COMMITS.lock().unwrap_or_else(|e| e.into_inner())); + for page in pages { + if let Some(entry) = mapped.get_mut(&(page & !(TILE - 1))) { + entry.holes = 0; + } + } + assert_eq!(mapped[&tile_a].holes, 0); + assert!(!mapped.contains_key(&tile_unmapped)); + assert!(!HAS_LAZY_COMMITS.load(Ordering::Acquire)); + + // Direct CPU write onto a reserved-only 64 KiB page marked with `kernelx::lazy::mark` + // (matching `alloc_vram_only` + title clear loop at `+0x501eb50`) commits cleanly. + unsafe { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + let p = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(p, 0); + crate::hle::kernelx::lazy::mark(p); + let slice = std::slice::from_raw_parts_mut((p + 0x5920) as *mut u32, 0x100); + slice.fill(0xFFFF_FFFF); + assert_eq!(slice[0], 0xFFFF_FFFF); + assert_eq!(slice[0xFF], 0xFFFF_FFFF); + assert!(!crate::hle::kernelx::lazy::unmark(p), "page must already have been committed by VEH"); + assert_ne!(VirtualFree(p as *mut c_void, 0, MEM_RELEASE), 0); + } + } } diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index bb4d07d093..2777415ac6 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -47,6 +47,9 @@ unsafe fn commit(page: usize) -> bool { // (a view of a physical page committed here is writable, not guarded: count it as written) super::guards::committed(page); super::alias::committed_at(page); + // If this lazy page belongs to a VRAM-only sparse backing (`sparse::alloc_vram_only`), + // queue it lock-free of `sparse::STATE` so the next execute/readback clears its hole mask. + crate::hle::d3d12x::sparse::note_lazy_commit(page); true } @@ -90,7 +93,7 @@ pub fn is_lazy(page: usize) -> bool { } /// `page` is unmapped: true if it was never used (nothing to keep of it). -pub(super) fn unmark(page: usize) -> bool { +pub(crate) fn unmark(page: usize) -> bool { LAZY.write().unwrap_or_else(|e| e.into_inner()).remove(&page) } From 6a0bb5b4f294b0729771ed457af1f96c01f5c06b Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:13:58 +0100 Subject: [PATCH 167/258] D3D12.X: enforce wall-clock frame wait windows, bound deferred segments, and keep split whole builds async Eliminate the remaining multi-second stalls observed past the 12 s per-frame pipeline wait window on cold/warm world frames: - Track in-flight wall-clock waits (`active_waiters` / `active_since`) in `pso_async::FrameWaitBudget` so staggered concurrent title threads share one hard wall-clock ceiling per kind per frame instead of each getting a fresh 12 s window (applied to both `FRAME_BUDGET_GFX`/`FRAME_BUDGET_CS` and `FRAME_WAIT`). - Skip deferring pending compute dispatches to submit in `list_x::defer` when `XCL_PSO_WAIT_MS` is set (#2581), when the current frame's compute wait window is already spent, or once 16 deferred segments have already been allocated on the current frame (prevents 512+ deferred segments and command-allocator/RAM churn). - Never compile `Chain::whole()` synchronously on a title/submit thread inside `dispatch_chain::dispatch` when scratch allocation fails under memory pressure or missing backing allocator: kick off `start_whole_async()` and return an error so the dispatch is skipped cleanly until the background whole build finishes, matching `whole_nonblocking`. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/list_x.rs | 71 +++++++++++ crates/xcl/src/hle/d3d12x/pso_async.rs | 118 +++++++++++++++--- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 15 ++- 3 files changed, 187 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index af95a9fb36..283581e80a 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3104,11 +3104,59 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { Some(next_pc) } +/// Cap on deferred compute segments per frame when per-frame wait windows are active so a cold +/// burst of thousands of unbuilt dispatches never exhausts command-list memory (`#2581`). +const MAX_DEFERRED_PER_FRAME: u32 = 16; + +struct FrameDeferCap { + frame: u64, + count: u32, +} + +impl FrameDeferCap { + const fn new() -> Self { + Self { frame: 0, count: 0 } + } + + fn has_slot(&mut self, frame: u64, limit: u32) -> bool { + if frame > self.frame { + self.frame = frame; + self.count = 0; + } + self.count < limit + } + + fn record(&mut self, frame: u64) { + if frame > self.frame { + self.frame = frame; + self.count = 1; + } else if frame == self.frame { + self.count = self.count.saturating_add(1); + } + } +} + +static FRAME_DEFER_CAP: Mutex = Mutex::new(FrameDeferCap::new()); + /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { + // With bounded per-PSO waits (`XCL_PSO_WAIT_MS`, #2581) or an exhausted per-frame compute + // wait window (`XCL_PSO_FRAME_BUDGET_MS`), record at once instead of allocating a segment + // per unbuilt dispatch (thousands of deferred segments can OOM command lists -> 0x887a0001). + if super::pso_async::waits_bounded() || super::pso_async::compute_frame_budget_spent() { + return false; + } + let bounded_frame = super::pso_async::frame_budget_enabled(); + let frame = if bounded_frame { super::present::presents() } else { 0 }; + if bounded_frame && !FRAME_DEFER_CAP.lock().unwrap().has_slot(frame, MAX_DEFERRED_PER_FRAME) { + return false; + } if split(list, Some(what)).is_none() { return false; } + if bounded_frame { + FRAME_DEFER_CAP.lock().unwrap().record(frame); + } static N: AtomicU64 = AtomicU64::new(0); let n = N.fetch_add(1, Ordering::Relaxed) + 1; if n <= 4 || n.is_power_of_two() { @@ -3117,6 +3165,29 @@ pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { true } +#[cfg(test)] +mod defer_cap_tests { + use super::FrameDeferCap; + + #[test] + fn frame_defer_cap_bounds_segments_per_frame_and_resets_on_new_frame() { + let mut cap = FrameDeferCap::new(); + for _ in 0..3 { + assert!(cap.has_slot(1, 3)); + cap.record(1); + } + assert!(!cap.has_slot(1, 3), "must stop deferring once per-frame segment cap is reached"); + assert!(cap.has_slot(2, 3), "advancing frame must reset the per-frame defer cap"); + cap.record(2); + // Stale lower frame must not disturb frame 2's count. + cap.record(1); + assert!(cap.has_slot(2, 3)); + cap.record(2); + cap.record(2); + assert!(!cap.has_slot(2, 3)); + } +} + /// Builds of a submit's put-off calls that go on without the commit headroom, as a title thread's own do: about what the title's threads had in the driver at once before. const WANTED_AT_ONCE: usize = 4; diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 0d8a3797d7..39b3535cdc 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -1596,7 +1596,7 @@ fn resolve_wait_in( } return built(p); }; - let rem = frame_state.lock().unwrap().remaining(frame, fcap); + let rem = frame_state.lock().unwrap().begin_wait(frame, fcap, std::time::Instant::now()); if rem.is_zero() { return p.stand(pso); } @@ -1605,17 +1605,15 @@ fn resolve_wait_in( _ => (rem, false), }; let _held = Held::new(); - let t0 = std::time::Instant::now(); let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), wait_for, |d| !*d).unwrap(); let finished = *done; drop(done); - let elapsed = t0.elapsed(); + let frame_timed_out = !finished && !per_pso_binding; + frame_state.lock().unwrap().end_wait(frame, fcap, std::time::Instant::now(), frame_timed_out); if finished { - frame_state.lock().unwrap().record(frame, elapsed); return built(p); } if per_pso_binding { - frame_state.lock().unwrap().record(frame, elapsed); p.late.store(true, Ordering::Release); static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); @@ -1627,10 +1625,7 @@ fn resolve_wait_in( ); } } else { - // Clamp recorded wait to `rem` on frame-budget timeout so OS timer jitter cannot leave a - // sub-millisecond sliver causing subsequent unready calls on this frame to spin. // Do NOT set `p.late` so the pipeline is retried with a fresh window on the next frame. - frame_state.lock().unwrap().record(frame, elapsed.max(rem)); static N_GFX: AtomicUsize = AtomicUsize::new(0); static N_CS: AtomicUsize = AtomicUsize::new(0); let counter = if p.compute { &N_CS } else { &N_GFX }; @@ -1673,6 +1668,25 @@ pub(super) fn set_wait_budget_for_test(budget: Option) { BUDGET_FOR_TEST.with(|b| b.set(budget)); } +/// Binds wait at most `XCL_PSO_WAIT_MS`: a dispatch is then not put off to the submit +/// (`list_x::defer`), where it would only wait as long. +pub fn waits_bounded() -> bool { + wait_budget().is_some() +} + +/// Whether per-frame pipeline wait windows (`XCL_PSO_FRAME_BUDGET_MS`) are active. +pub fn frame_budget_enabled() -> bool { + frame_budget().is_some() +} + +/// Whether the current frame's compute pipeline wait window has already been spent. +pub fn compute_frame_budget_spent() -> bool { + frame_budget().is_some_and(|cap| { + let frame = super::present::presents(); + FRAME_BUDGET_CS.lock().unwrap().remaining_at(frame, cap, std::time::Instant::now()).is_zero() + }) +} + /// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a /// pipeline not built by then is `late` – it and later binds of it get the stand-in (their /// dispatches are skipped) until a worker has built it. @@ -1770,21 +1784,69 @@ fn frame_wait_budget() -> Option { struct FrameWaitBudget { frame: u64, spent: std::time::Duration, + active_waiters: usize, + active_since: Option, } impl FrameWaitBudget { const fn new() -> Self { - Self { frame: 0, spent: std::time::Duration::ZERO } + Self { frame: 0, spent: std::time::Duration::ZERO, active_waiters: 0, active_since: None } } - fn remaining(&mut self, frame: u64, cap: std::time::Duration) -> std::time::Duration { + fn advance(&mut self, frame: u64, now: std::time::Instant) { if frame > self.frame { self.frame = frame; self.spent = std::time::Duration::ZERO; + self.active_since = (self.active_waiters > 0).then_some(now); + } + } + + fn effective_spent(&self, now: std::time::Instant) -> std::time::Duration { + let in_flight = self.active_since.map_or(std::time::Duration::ZERO, |s| now.saturating_duration_since(s)); + self.spent.saturating_add(in_flight) + } + + fn remaining_at(&mut self, frame: u64, cap: std::time::Duration, now: std::time::Instant) -> std::time::Duration { + self.advance(frame, now); + cap.saturating_sub(self.effective_spent(now)) + } + + /// Reserve a wait slot on `frame`: tracks wall-clock overlap across concurrent threads so + /// staggered callers share one hard `cap` ceiling per frame and can never cascade past `cap`. + fn begin_wait(&mut self, frame: u64, cap: std::time::Duration, now: std::time::Instant) -> std::time::Duration { + self.advance(frame, now); + let rem = cap.saturating_sub(self.effective_spent(now)); + if rem.is_zero() { + return std::time::Duration::ZERO; + } + if self.active_waiters == 0 { + self.active_since = Some(now); } - cap.saturating_sub(self.spent) + self.active_waiters += 1; + rem } + fn end_wait(&mut self, frame: u64, cap: std::time::Duration, now: std::time::Instant, frame_timed_out: bool) { + self.advance(frame, now); + if self.active_waiters > 0 { + self.active_waiters -= 1; + if self.active_waiters == 0 { + if let Some(since) = self.active_since.take() { + self.spent = self.spent.saturating_add(now.saturating_duration_since(since)); + } + } + } + if frame_timed_out && frame == self.frame { + self.spent = self.spent.max(cap); + } + } + + #[cfg(test)] + fn remaining(&mut self, frame: u64, cap: std::time::Duration) -> std::time::Duration { + self.remaining_at(frame, cap, std::time::Instant::now()) + } + + #[cfg(test)] fn record(&mut self, frame: u64, elapsed: std::time::Duration) { if frame > self.frame { self.frame = frame; @@ -1815,13 +1877,12 @@ fn resolve_spared(p: &Arc, pso: usize) -> usize { if !p.bvh_traversal.load(Ordering::Acquire) && !p.late.load(Ordering::Acquire) { if let Some(cap) = frame_wait_budget() { let frame = super::present::presents(); - let rem = FRAME_WAIT.lock().unwrap().remaining(frame, cap); + let rem = FRAME_WAIT.lock().unwrap().begin_wait(frame, cap, std::time::Instant::now()); if !rem.is_zero() { - let t0 = std::time::Instant::now(); let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), rem, |d| !*d).unwrap(); let finished = *done; drop(done); - FRAME_WAIT.lock().unwrap().record(frame, t0.elapsed()); + FRAME_WAIT.lock().unwrap().end_wait(frame, cap, std::time::Instant::now(), !finished); if finished { return match p.real.load(Ordering::Acquire) { 0 => p.stand(pso), @@ -2117,4 +2178,33 @@ mod pso_queue_tests { let _ = released(s); } } + + #[test] + fn wall_clock_frame_budget_prevents_staggered_multithread_cascade() { + use std::time::{Duration, Instant}; + + let cap = Duration::from_secs(12); + let t0 = Instant::now(); + let mut b = FrameWaitBudget::new(); + + // Thread 1 starts waiting at t=0: full 12 s. + assert_eq!(b.begin_wait(1467, cap, t0), Duration::from_secs(12)); + // Thread 2 arrives staggered at t=10 s while thread 1 is still waiting: only 2 s left! + assert_eq!(b.begin_wait(1467, cap, t0 + Duration::from_secs(10)), Duration::from_secs(2)); + // Thread 3 arrives at t=11.5 s: only 0.5 s left! + assert_eq!(b.begin_wait(1467, cap, t0 + Duration::from_millis(11_500)), Duration::from_millis(500)); + // Thread 4 arrives at t=12.0 s: 0 ms left immediately (no cascade!). + assert_eq!(b.begin_wait(1467, cap, t0 + Duration::from_secs(12)), Duration::ZERO); + + // All 3 active waiters finish at t=12 s -> budget spent on frame 1467. + b.end_wait(1467, cap, t0 + Duration::from_secs(12), true); + b.end_wait(1467, cap, t0 + Duration::from_secs(12), true); + b.end_wait(1467, cap, t0 + Duration::from_secs(12), true); + assert_eq!(b.remaining_at(1467, cap, t0 + Duration::from_secs(12)), Duration::ZERO); + + // Advancing to frame 1468 resets the wall-clock window cleanly. + assert_eq!(b.begin_wait(1468, cap, t0 + Duration::from_secs(13)), Duration::from_secs(12)); + b.end_wait(1468, cap, t0 + Duration::from_secs(14), false); + assert_eq!(b.remaining_at(1468, cap, t0 + Duration::from_secs(14)), Duration::from_secs(11)); + } } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index c701228407..839f956a27 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -534,9 +534,18 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, let most = scratch.as_ref().map_or(1, |(s, _)| (s.bytes / group).max(1)); let slabs = pso::dispatch_slabs(grid, most); let Some((scratch, used)) = scratch else { - list.SetPipelineState(&chain.whole()?); - list.Dispatch(x, y, z); - return Ok(()); + if let Some(whole) = chain.whole.get() { + list.SetPipelineState(whole); + list.Dispatch(x, y, z); + return Ok(()); + } + if !super::super::pso_async::enabled() { + list.SetPipelineState(&chain.whole()?); + list.Dispatch(x, y, z); + return Ok(()); + } + chain.start_whole_async(); + return Err("whole compute pipeline still building in background".into()); }; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); let held = Arc::new(Recording { scratch, first, chain, indirect: None }); From d625b209a86bda5f3a0cab18d60c6b573c9db9de Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:38:40 +0100 Subject: [PATCH 168/258] D3D12.X: zero recycled VRAM page-pool tiles on mapping queue (#505/#1833) Track recycled (previously returned/cooled) 64 KiB tiles in vram::TilePool via a per-heap bitmap (freshly allocated D3D12 heaps remain clean with zero extra GPU work) and asynchronously zero recycled tiles in one coalesced CopyBufferRegion batch on Pages::queue before flushing Pages::fence in before_execute (default ON, XCL_ZERO_TARGET_PAGES=0 disables): - PoolHeaps caches a 0-extra-VRAM aliased 64 MiB placed BUFFER per pool heap (D3D12_HEAP_FLAG_NONE Tier 2) and ZeroRing reuses a 4-slot DIRECT command ring + 1 MiB pre-zeroed UPLOAD source with D3D12_RESOURCE_BARRIER_TYPE_ALIASING so stale render-target/depth/UAV bytes never bleed into newly mapped targets (e.g., 2560x1440 R9G9B9E5 lighting blocks/white-outs). - Add unit tests tile_pool_tracks_dirty_bits_only_for_recycled_tiles and coalesce_tile_runs_merges_adjacent_tiles_per_heap. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/vram.rs | 364 +++++++++++++++++++++++++++++- 1 file changed, 357 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 04cc55ef7d..2fd19148d9 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -608,6 +608,10 @@ struct TilePool { free_by_heap: Vec>, /// Whether `free_by_heap[h]` must be sorted descending before popping. dirty_sort: Vec, + /// Per-heap bitmap of recycled tiles (`1` = previously allocated & returned, holds stale VRAM + /// contents that must be zeroed before handing to a new texture under `XCL_ZERO_TARGET_PAGES`). + /// Freshly created heaps start all `0` (already zeroed by D3D12). + dirty_bits: Vec<[u64; (POOL_PAGES as usize).div_ceil(64)]>, /// Total free tiles currently available across all heaps. free_total: usize, /// Tiles given back, reusable after `COOL`. @@ -619,20 +623,47 @@ impl TilePool { TilePool { free_by_heap: Vec::new(), dirty_sort: Vec::new(), + dirty_bits: Vec::new(), free_total: 0, cooling: std::collections::VecDeque::new(), } } + #[inline] + fn mark_dirty(&mut self, h: usize, t: u32) { + let word = (t as usize) >> 6; + if let Some(bits) = self.dirty_bits.get_mut(h) { + if let Some(w) = bits.get_mut(word) { + *w |= 1u64 << (t & 63); + } + } + } + + #[inline] + fn take_dirty(&mut self, h: usize, t: u32) -> bool { + let word = (t as usize) >> 6; + if let Some(bits) = self.dirty_bits.get_mut(h) { + if let Some(w) = bits.get_mut(word) { + let mask = 1u64 << (t & 63); + let was = (*w & mask) != 0; + *w &= !mask; + return was; + } + } + false + } + fn add_heap_at(&mut self, slot: u32, pool_pages: u32) { let idx = slot as usize; if idx >= self.free_by_heap.len() { self.free_by_heap.resize_with(idx + 1, Vec::new); self.dirty_sort.resize(idx + 1, false); + self.dirty_bits.resize(idx + 1, [0u64; (POOL_PAGES as usize).div_ceil(64)]); } debug_assert!(self.free_by_heap[idx].is_empty()); self.free_by_heap[idx] = (0..pool_pages).rev().collect(); self.dirty_sort[idx] = false; + self.dirty_bits[idx] = [0u64; (POOL_PAGES as usize).div_ceil(64)]; self.free_total += pool_pages as usize; } @@ -655,6 +686,7 @@ impl TilePool { self.free_by_heap[h].clear(); self.free_by_heap[h].shrink_to_fit(); self.dirty_sort[h] = false; + self.dirty_bits[h] = [0u64; (POOL_PAGES as usize).div_ceil(64)]; self.free_total -= full; reclaimed.push(h as u32); } @@ -677,6 +709,7 @@ impl TilePool { if idx < self.free_by_heap.len() { self.free_by_heap[idx].push(t); self.dirty_sort[idx] = true; + self.mark_dirty(idx, t); self.free_total += 1; } } @@ -694,11 +727,26 @@ impl TilePool { if idx < self.free_by_heap.len() { self.free_by_heap[idx].push(t); self.dirty_sort[idx] = true; + self.mark_dirty(idx, t); self.free_total += 1; } } } + fn return_rollback_tiles(&mut self, tiles: &[Tile], dirty: &[Tile]) { + for &(h, t) in tiles { + let idx = h as usize; + if idx < self.free_by_heap.len() { + self.free_by_heap[idx].push(t); + self.dirty_sort[idx] = true; + self.free_total += 1; + } + } + for &(h, t) in dirty { + self.mark_dirty(h as usize, t); + } + } + /// Pick the pool heap to take up to `rem` tiles from: /// 1. `preferred` if it fits all `rem` tiles (keeps partial-overlap placements on 1 heap), /// 2. otherwise best-fit heap with `len >= rem` (fits the whole texture in 1 heap without @@ -746,6 +794,7 @@ impl TilePool { self.take_batch_fenced(count, preferred, now, None, pool_pages, make_heap) } + #[cfg(test)] fn take_batch_fenced( &mut self, count: usize, @@ -753,6 +802,20 @@ impl TilePool { now: std::time::Instant, safe_before: Option, pool_pages: u32, + make_heap: impl FnMut() -> Option, + ) -> Option> { + let mut ignored = Vec::new(); + self.take_batch_fenced_recycled(count, preferred, now, safe_before, pool_pages, &mut ignored, make_heap) + } + + fn take_batch_fenced_recycled( + &mut self, + count: usize, + preferred: Option, + now: std::time::Instant, + safe_before: Option, + pool_pages: u32, + recycled_out: &mut Vec, mut make_heap: impl FnMut() -> Option, ) -> Option> { if count == 0 { @@ -760,13 +823,15 @@ impl TilePool { } self.drain_cooling_before(now, safe_before); let mut out = Vec::with_capacity(count); + let recycled_start = recycled_out.len(); while out.len() < count { let rem = count - out.len(); let h = match self.pick_heap(rem, preferred) { Some(h) => h, None => { let Some(new_h) = make_heap() else { - self.return_tiles(&out); + let rolled_dirty = recycled_out.split_off(recycled_start); + self.return_rollback_tiles(&out, &rolled_dirty); return None; }; self.add_heap_at(new_h, pool_pages); @@ -777,10 +842,12 @@ impl TilePool { self.free_by_heap[h].sort_unstable_by(|a, b| b.cmp(a)); self.dirty_sort[h] = false; } - let free = &mut self.free_by_heap[h]; - let take = rem.min(free.len()); + let take = rem.min(self.free_by_heap[h].len()); for _ in 0..take { - let t = free.pop().unwrap(); + let t = self.free_by_heap[h].pop().unwrap(); + if self.take_dirty(h, t) { + recycled_out.push((h as u32, t)); + } out.push((h as u32, t)); } self.free_total -= take; @@ -789,6 +856,32 @@ impl TilePool { } } +/// Coalesce recycled `(heap, tile_idx)` pairs into sorted, deduplicated `(heap, start_tile, count)` +/// runs so GPU zero-fills issue one `CopyBufferRegion` per contiguous tile span. +fn coalesce_tile_runs(tiles: &mut Vec) -> Vec<(u32, u32, u32)> { + if tiles.is_empty() { + return Vec::new(); + } + tiles.sort_unstable(); + tiles.dedup(); + let mut runs: Vec<(u32, u32, u32)> = Vec::new(); + for &(h, t) in tiles.iter() { + match runs.last_mut() { + Some(last) if last.0 == h && last.1 + last.2 == t => last.2 += 1, + _ => runs.push((h, t, 1)), + } + } + runs +} + +/// Zero recycled page-pool tiles on the mapping queue before handing them to newly mapped +/// textures so stale render-target/depth/UAV bytes never bleed into new targets (`#505`/`#1833`). +/// Enabled by default (`XCL_ZERO_TARGET_PAGES=0` disables). +fn zero_target_pages() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_ZERO_TARGET_PAGES").map_or(true, |v| v.trim() != "0")) +} + /// Allocate one 64 MiB default heap for `Pages`. unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { let desc = D3D12_HEAP_DESC { @@ -815,13 +908,16 @@ unsafe fn alloc_pool_heap(dev: &ID3D12Device) -> Option { /// are reclaimed back to local VRAM. `len()` reports the count of live heaps. struct PoolHeaps { slots: Vec>, + /// Aliased 64 MiB `BUFFER` placed at offset 0 of each pool heap for GPU zero-fills of recycled + /// tiles (0 bytes of extra VRAM; lazily created on first recycled tile in that heap). + zero_bufs: Vec>, free_slots: Vec, live: usize, } impl PoolHeaps { fn new() -> Self { - Self { slots: Vec::new(), free_slots: Vec::new(), live: 0 } + Self { slots: Vec::new(), zero_bufs: Vec::new(), free_slots: Vec::new(), live: 0 } } fn len(&self) -> usize { @@ -833,20 +929,113 @@ impl PoolHeaps { if let Some(idx) = self.free_slots.pop() { debug_assert!(self.slots[idx as usize].is_none()); self.slots[idx as usize] = Some(heap); + self.zero_bufs[idx as usize] = None; idx } else { let idx = self.slots.len() as u32; self.slots.push(Some(heap)); + self.zero_bufs.push(None); idx } } fn take_heap(&mut self, idx: u32) -> Option { + self.zero_bufs.get_mut(idx as usize).map(|b| b.take()); let h = self.slots.get_mut(idx as usize)?.take()?; self.live -= 1; self.free_slots.push(idx); Some(h) } + + unsafe fn zero_buffer(&mut self, dev: &ID3D12Device, idx: usize) -> Option { + if let Some(b) = self.zero_bufs.get(idx)?.as_ref() { + return Some(b.clone()); + } + let heap = self.slots.get(idx)?.as_ref()?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: POOL_PAGES as u64 * PAGE as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + let mut res: Option = None; + let ok = super::title_textures::own_work(|| { + dev.CreatePlacedResource(heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut res) + }) + .is_ok(); + if !ok { + return None; + } + let buf = res?; + if super::real::dred_on() { + super::real::name_resource(buf.as_raw(), &format!("xcl vram zero_alias h={idx}")); + } + self.zero_bufs[idx] = Some(buf.clone()); + Some(buf) + } +} + +/// Reusable 4-slot command ring + 1 MiB pre-zeroed upload buffer for asynchronous GPU zero-fills +/// of recycled VRAM pool tiles on `Pages::queue`. +const ZERO_BUF_BYTES: u64 = 1 << 20; +const ZERO_SLOTS: usize = 4; + +struct ZeroSlot { + alloc: ID3D12CommandAllocator, + list: ID3D12GraphicsCommandList, + fence_val: u64, + kept_bufs: Vec, +} + +struct ZeroRing { + zero_src: ID3D12Resource, + slots: Vec, +} + +impl ZeroRing { + unsafe fn new(dev: &ID3D12Device) -> Option { + let mut src: Option = None; + let hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: ZERO_BUF_BYTES, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + }; + super::title_textures::own_work(|| { + dev.CreateCommittedResource(&hp, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut src) + }) + .ok()?; + let zero_src = src?; + let mut mapped = std::ptr::null_mut(); + zero_src.Map(0, None, Some(&mut mapped)).ok()?; + std::ptr::write_bytes(mapped as *mut u8, 0, ZERO_BUF_BYTES as usize); + zero_src.Unmap(0, None); + let mut slots = Vec::with_capacity(ZERO_SLOTS); + for _ in 0..ZERO_SLOTS { + let (alloc, list) = super::title_textures::own_work(|| -> windows::core::Result<_> { + let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let l: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None)?; + l.Close()?; + Ok((a, l)) + }) + .ok()?; + slots.push(ZeroSlot { alloc, list, fence_val: 0, kept_bufs: Vec::new() }); + } + Some(ZeroRing { zero_src, slots }) + } } impl std::ops::Index for PoolHeaps { @@ -985,6 +1174,12 @@ struct Pages { scratch_flags: Vec, scratch_offsets: Vec, scratch_counts: Vec, + /// recycled tiles awaiting batched GPU zero-fill on `self.queue` before next `before_execute` + pending_zero_tiles: Vec, + /// lazily initialized command ring + 1 MiB zero source for `flush_zero_tiles` + zero_ring: Option, + /// true once `ZeroRing::new` failed so we don't retry every submit + zero_ring_failed: bool, } // D3D12 objects are free-threaded @@ -1036,6 +1231,9 @@ impl Pages { scratch_flags: Vec::new(), scratch_offsets: Vec::new(), scratch_counts: Vec::new(), + pending_zero_tiles: Vec::new(), + zero_ring: None, + zero_ring_failed: false, }) } @@ -1164,6 +1362,107 @@ impl Pages { self.dirty_signal = true; } + /// Asynchronously zero all queued recycled pool tiles on `self.queue` in one batched command + /// list, then emit an aliasing barrier + `self.fence` signal so any title queue waiting in + /// `before_execute` sees zeroed tiles before reading or writing newly mapped textures. + unsafe fn flush_zero_tiles(&mut self, dev: &ID3D12Device) { + if self.pending_zero_tiles.is_empty() { + return; + } + if !zero_target_pages() || self.zero_ring_failed { + self.pending_zero_tiles.clear(); + return; + } + let runs = coalesce_tile_runs(&mut self.pending_zero_tiles); + self.pending_zero_tiles.clear(); + if runs.is_empty() { + return; + } + if self.zero_ring.is_none() { + match ZeroRing::new(dev) { + Some(r) => self.zero_ring = Some(r), + None => { + self.zero_ring_failed = true; + return; + } + } + } + // Resolve aliased 64 MiB buffers for every touched live heap before borrowing `zero_ring`. + let mut heap_bufs: std::collections::HashMap = std::collections::HashMap::new(); + for &(h, _, _) in &runs { + if !heap_bufs.contains_key(&h) { + if let Some(buf) = self.pools.zero_buffer(dev, h as usize) { + heap_bufs.insert(h, buf); + } + } + } + if heap_bufs.is_empty() { + return; + } + let done = self.fence.GetCompletedValue(); + let ring = self.zero_ring.as_mut().unwrap(); + let slot_idx = match ring.slots.iter().position(|s| s.fence_val <= done) { + Some(i) => i, + None => { + let (oldest_idx, oldest_val) = ring + .slots + .iter() + .enumerate() + .min_by_key(|(_, s)| s.fence_val) + .map(|(i, s)| (i, s.fence_val)) + .unwrap(); + let _ = crate::gpu::fence::wait(&self.fence, oldest_val, dev, None, 5_000); + oldest_idx + } + }; + let zero_src = ring.zero_src.clone(); + let slot = &mut ring.slots[slot_idx]; + slot.kept_bufs.clear(); + let ok = super::title_textures::own_work(|| -> windows::core::Result<()> { + slot.alloc.Reset()?; + slot.list.Reset(&slot.alloc, None)?; + for &(h, start, count) in &runs { + let Some(dst) = heap_bufs.get(&h) else { continue }; + let mut offset = start as u64 * PAGE as u64; + let mut rem = count as u64 * PAGE as u64; + while rem > 0 { + let chunk = rem.min(ZERO_BUF_BYTES); + slot.list.CopyBufferRegion(dst, offset, &zero_src, 0, chunk); + offset += chunk; + rem -= chunk; + } + } + let mut barriers: Vec = Vec::with_capacity(heap_bufs.len()); + for buf in heap_bufs.values() { + slot.kept_bufs.push(buf.clone()); + barriers.push(D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { + Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER { + pResourceBefore: std::mem::transmute_copy(buf), + pResourceAfter: std::mem::zeroed(), + }), + }, + }); + } + if !barriers.is_empty() { + slot.list.ResourceBarrier(&barriers); + } + slot.list.Close()?; + let cmd: ID3D12CommandList = slot.list.cast()?; + self.queue.ExecuteCommandLists(&[Some(cmd)]); + Ok(()) + }) + .is_ok(); + if ok { + self.value += 1; + let _ = self.queue.Signal(&self.fence, self.value); + self.dirty_signal = false; + slot.fence_val = self.value; + } + } + /// Emit one `queue.Signal` covering all batched `map()` / `unmap()` calls since the last flush. unsafe fn flush_signal(&mut self) { if self.dirty_signal { @@ -1366,7 +1665,8 @@ impl Pages { let safe_before = self.cool_bound(); let pools = &mut self.pools; let pool = &mut self.pool; - let fresh = pool.take_batch_fenced(missing, preferred, now, safe_before, POOL_PAGES, || { + let pending_zero = &mut self.pending_zero_tiles; + let fresh = pool.take_batch_fenced_recycled(missing, preferred, now, safe_before, POOL_PAGES, pending_zero, || { let _timer = step(Step::Heap); let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) @@ -1430,6 +1730,9 @@ impl Pages { } } self.map(res, sub, &tiles); + if self.pending_zero_tiles.len() >= 256 { + self.flush_zero_tiles(dev); + } Some((used, used_extra, follows)) } @@ -1494,7 +1797,8 @@ impl Pages { None => { let pools = &mut self.pools; let pool = &mut self.pool; - let Some(mut fresh) = pool.take_batch_fenced(1, None, now, safe_before, POOL_PAGES, || { + let pending_zero = &mut self.pending_zero_tiles; + let Some(mut fresh) = pool.take_batch_fenced_recycled(1, None, now, safe_before, POOL_PAGES, pending_zero, || { let _timer = step(Step::Heap); let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) @@ -2180,6 +2484,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { if !changed.is_empty() && !pages.follow.is_empty() { pages.apply_backing(&dev, &changed); } + pages.flush_zero_tiles(&dev); pages.flush_signal(); let key = queue.as_raw() as usize; if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { @@ -3509,4 +3814,49 @@ mod tests { VirtualFree(va as *mut c_void, 0, MEM_RELEASE); } } + + #[test] + fn tile_pool_tracks_dirty_bits_only_for_recycled_tiles() { + let mut pool = TilePool::new(); + let now = std::time::Instant::now(); + let mut recycled = Vec::new(); + let mut next_h = 0u32; + + // Fresh heap tiles are never marked recycled (D3D12 guarantees fresh heaps are zeroed). + let first = pool + .take_batch_fenced_recycled(4, None, now, None, POOL_PAGES, &mut recycled, || { + let h = next_h; + next_h += 1; + Some(h) + }) + .unwrap(); + assert_eq!(first, vec![(0, 0), (0, 1), (0, 2), (0, 3)]); + assert!(recycled.is_empty(), "freshly allocated heap tiles must not need GPU zeroing"); + + // Returned tiles are marked dirty and reported in `recycled` when re-taken. + pool.return_tiles(&[(0, 1), (0, 2)]); + let again = pool + .take_batch_fenced_recycled(3, Some(0), now, None, POOL_PAGES, &mut recycled, || None) + .unwrap(); + assert_eq!(again, vec![(0, 1), (0, 2), (0, 4)]); + assert_eq!(recycled, vec![(0, 1), (0, 2)], "only previously returned tiles require zeroing"); + + // Cooled tiles also mark dirty when drained back into free_by_heap. + recycled.clear(); + pool.push_cooling((0, 0), now); + let later = now + COOL + std::time::Duration::from_millis(1); + let cooled = pool + .take_batch_fenced_recycled(1, Some(0), later, None, POOL_PAGES, &mut recycled, || None) + .unwrap(); + assert_eq!(cooled, vec![(0, 0)]); + assert_eq!(recycled, vec![(0, 0)]); + } + + #[test] + fn coalesce_tile_runs_merges_adjacent_tiles_per_heap() { + let mut tiles = vec![(1, 5), (0, 3), (0, 2), (1, 6), (0, 3), (0, 10), (1, 4)]; + assert_eq!(coalesce_tile_runs(&mut tiles), vec![(0, 2, 2), (0, 10, 1), (1, 4, 3)]); + let mut empty = Vec::new(); + assert!(coalesce_tile_runs(&mut empty).is_empty()); + } } From 51d5f3353977b2e8710457f72c89f624608168f5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:01:12 +0100 Subject: [PATCH 169/258] D3D12.X: detect reused heap vtables in real::class_for (#2588) Agility SDK 1.620+ allocates some D3D12 COM vtables on the heap rather than inside a loaded module. If a COM object is freed and a different object reuses the same heap address for its vtable, caching Class solely by (orig, kind) can dispatch through stale methods from the previous object. Snapshot the copied runtime method pointers on Class when module_of(orig) == 0, compare them against the live vtable before reusing a cached Class, and double-check under CLASSES.write() before leaking a new extended vtable. DLL-resident vtables keep copied = None with zero extra overhead. Verified with cargo check -p xcl --lib and class_for_rebuilds_when_heap_vtable_reused_with_different_methods (1 passed, 0 failed). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/real.rs | 102 +++++++++++++++++++++++++++++- 1 file changed, 99 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 8d7bf972c3..d1efa6a264 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -666,6 +666,10 @@ struct Class { iface: &'static Iface, public: usize, scanned: usize, + /// When `orig` lies outside any loaded module (e.g., Agility SDK 1.620+ heap-allocated open + /// command-list vtables, #2588), snapshot the copied runtime method slots so `class_for` only + /// reuses `ext` while the live table at `orig` still holds the exact same methods. + copied: Option>, } static CLASSES: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); @@ -773,11 +777,25 @@ pub unsafe fn adopt(obj: *mut c_void, kind: Kind) { *(obj as *mut usize) = ext; } +unsafe fn find_matching_class(classes: &[Class], orig: usize, kind: Kind, ot: *const usize) -> Option { + classes + .iter() + .rev() + .find(|c| { + c.orig == orig + && c.kind == kind + && c.copied.as_ref().is_none_or(|saved| { + saved.iter().enumerate().all(|(i, &want)| *ot.add(i) == want) + }) + }) + .map(|c| c.ext) +} + unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { - if let Some(ext) = CLASSES.read().unwrap().iter().find(|c| c.orig == orig && c.kind == kind).map(|c| c.ext) { + let ot = orig as *const usize; + if let Some(ext) = find_matching_class(&CLASSES.read().unwrap(), orig, kind, ot) { return ext; } - let ot = orig as *const usize; // most derived PC interface this object implements let chain = layout::chain(kind.base()); let qi: QiFn = std::mem::transmute(*ot); @@ -880,6 +898,11 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { v[1 + i] = super::guard::make_tracer(v[1 + i], name); } } + let copied = (module_of(orig) == 0).then(|| (0..scanned).map(|i| *ot.add(i)).collect::>().into_boxed_slice()); + let mut classes = CLASSES.write().unwrap(); + if let Some(ext) = find_matching_class(&classes, orig, kind, ot) { + return ext; + } let leaked: &'static [usize] = Box::leak(v.into_boxed_slice()); let ext = leaked.as_ptr() as usize + 8; EXTS.write().unwrap().get_or_insert_with(HashSet::new).insert(ext); @@ -889,7 +912,7 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize { scanned - public, crate::modules::describe_address(orig) ); - CLASSES.write().unwrap().push(Class { orig, kind, ext, iface, public, scanned }); + classes.push(Class { orig, kind, ext, iface, public, scanned, copied }); ext } @@ -9973,6 +9996,7 @@ mod mesh_stream_tests { iface, public: iface.methods.len(), scanned: iface.methods.len(), + copied: None, }); ABI_RS_SAMPLERS.write().unwrap().get_or_insert_with(HashMap::new).insert(key.clone(), 0x1234_5678); let _cleanup = Cleanup { ext: ext_vtbl, key }; @@ -11394,4 +11418,76 @@ mod outside_buffer_tests { assert_eq!(t.release_ref(base), None); assert_eq!(t.lookup(base + 0x1000, 0x1000), Some(uma + 0x1000)); } + + /// Regression for #2588: when Agility SDK 1.620+ allocates an open command list's vtable in + /// heap memory (outside any loaded module) and a later list reuses that same heap address with + /// different runtime method slots (e.g., compute list -> direct list `ClearDepthStencilView`), + /// `class_for` must not hand back the stale extended vtable. + #[test] + fn class_for_rebuilds_when_heap_vtable_reused_with_different_methods() { + unsafe extern "system" fn fake_qi(_this: *mut c_void, _iid: *const GUID, out: *mut *mut c_void) -> HRESULT { + if !out.is_null() { + *out = std::ptr::null_mut(); + } + -2147467262 // E_NOINTERFACE + } + unsafe extern "system" fn fake_ref(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn method_a(_this: *mut c_void) {} + unsafe extern "system" fn method_b(_this: *mut c_void) {} + + let base_iface = layout::find(Kind::CommandList.base()).unwrap(); + let n = base_iface.methods.len(); + // Heap-allocated vtable (`module_of(orig) == 0`) with a trailing sentinel `0` so scanning + // stops cleanly at `n`. + let mut heap_vtbl = vec![method_a as usize; n + 1]; + heap_vtbl[0] = fake_qi as usize; + heap_vtbl[1] = fake_ref as usize; + heap_vtbl[2] = fake_ref as usize; + heap_vtbl[n] = 0; + + let orig = heap_vtbl.as_ptr() as usize; + assert_eq!(module_of(orig), 0, "test vtable must live outside any loaded module"); + + struct Cleanup(usize); + impl Drop for Cleanup { + fn drop(&mut self) { + let mut exts = Vec::new(); + CLASSES.write().unwrap().retain(|c| { + if c.orig == self.0 { + exts.push(c.ext); + false + } else { + true + } + }); + if let Some(set) = EXTS.write().unwrap().as_mut() { + for e in exts { + set.remove(&e); + } + } + } + } + let _cleanup = Cleanup(orig); + + let mut obj = orig; + let obj_ptr = &mut obj as *mut usize as *mut c_void; + unsafe { + let ext1 = class_for(obj_ptr, orig, Kind::CommandList); + assert_eq!(class_for(obj_ptr, orig, Kind::CommandList), ext1, "unchanged heap vtable reuses cached class"); + + // Simulate a released compute list's heap vtable address reused by a direct list + // (changing slot 47 `ClearDepthStencilView` and unhooked slot 5 `SetPrivateData`). + heap_vtbl[5] = method_b as usize; + heap_vtbl[47] = method_b as usize; + let ext2 = class_for(obj_ptr, orig, Kind::CommandList); + assert_ne!(ext2, ext1, "reused heap vtable with changed runtime methods must not reuse stale ext"); + assert_eq!(*(ext2 as *const usize).add(5), method_b as usize); + assert_eq!(class_for(obj_ptr, orig, Kind::CommandList), ext2, "matching new methods reuse ext2"); + + // Restoring original slots hits ext1 again cleanly without unbounded growth. + heap_vtbl[5] = method_a as usize; + heap_vtbl[47] = method_a as usize; + assert_eq!(class_for(obj_ptr, orig, Kind::CommandList), ext1); + } + } } From 3ca3e45731ea5b3e80a4380a53a7ee9fc3701cbe Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:02:47 +0100 Subject: [PATCH 170/258] D3D12.X: fix placed SRV/UAV UAF and cache-race drop in format_alias placed_srv_resource and placed_uav_resource returned uncounted raw ID3D12Resource pointers after dropping TABLE.lock(), and on a concurrent cache-miss race entry(key).or_insert(res) dropped the losing resource inside TABLE.lock() (risking res_release -> format_alias::forget deadlock) while still returning the dropped loser pointer. Furthermore, concurrent eviction via evict_stale_internal_at -> defer_drop_resources -> late_release::hold could synchronously run drain_known(true) and release the PC COM object while dev_create_srv_x was mid-call before r.GetDesc() (crashing inside amdxc64.dll). Fix all three lifetime bugs: - Return owned Option cloned inside TABLE.lock() from placed_srv_resource and placed_uav_resource (via cache_insert_or_clone), dropping any race loser outside TABLE.lock(), and hold the owned reference across dev_create_srv_x / dev_create_uav_x. - Pin internal PlacedUav/PlacedSrv resources across sync_pair in on_uav_barrier and sync_title_writers. - Drop adopted evicted resources normally in defer_drop_resources (outside TABLE.lock()) so real::res_release cleans up title_textures/vram/format_alias maps on the final ref before deferring the PC Release via late_release::hold. - Reuse a single r.GetDesc() call across dev_create_srv_x. Verified with cargo check -p xcl --lib and cargo test -p xcl --lib -- hle::d3d12x::format_alias::tests --test-threads=1 (5 passed, 0 failed). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/format_alias.rs | 172 ++++++++++++++++------ crates/xcl/src/hle/d3d12x/real.rs | 19 ++- 2 files changed, 137 insertions(+), 54 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/format_alias.rs b/crates/xcl/src/hle/d3d12x/format_alias.rs index ae3ab872a2..dfb1f15b27 100644 --- a/crates/xcl/src/hle/d3d12x/format_alias.rs +++ b/crates/xcl/src/hle/d3d12x/format_alias.rs @@ -445,6 +445,14 @@ impl AliasTable { self.pairs.push(pair); } + fn clone_internal(&self, res: usize) -> Option { + self.placed_uavs + .values() + .chain(self.placed_srvs.values()) + .find(|r| r.as_raw() as usize == res) + .cloned() + } + fn remove(&mut self, res: usize) -> Option { if let Some(old) = self.by_res.remove(&res) { if old.owner == Owner::TitlePlaced { @@ -474,11 +482,31 @@ static TRACKED_TITLE_TEX: AtomicUsize = AtomicUsize::new(0); static ACTIVE_PAIRS: AtomicUsize = AtomicUsize::new(0); static ACTIVE_PLACED_UAV_PAIRS: AtomicUsize = AtomicUsize::new(0); -/// Defer releasing internal resources evicted from `placed_uavs` / `placed_srvs` until in-flight -/// GPU work has completed. +/// Insert `value` at `key` or keep the existing entry, always returning a cloned handle to the +/// winning map entry plus `Some(loser)` if another thread won the race so the caller can drop the +/// loser outside the table lock. +fn cache_insert_or_clone( + map: &mut HashMap, + key: K, + value: V, +) -> (V, Option) { + match map.entry(key) { + std::collections::hash_map::Entry::Occupied(e) => (e.get().clone(), Some(value)), + std::collections::hash_map::Entry::Vacant(e) => (e.insert(value).clone(), None), + } +} + +/// Release internal resources evicted from `placed_uavs` / `placed_srvs` outside `TABLE`. +/// Adopted resources route through `real::res_release`, which cleans up `title_textures` / +/// `vram` / `format_alias` tracking on the final ref and defers the PC `Release` via +/// `late_release::hold` once no in-flight caller still holds a cloned reference. unsafe fn defer_drop_resources(evicted: Vec) { for r in evicted { - super::late_release::hold(r.into_raw() as usize); + if super::real::is_adopted(r.as_raw()) || !super::late_release::enabled() { + drop(r); + } else { + super::late_release::hold(r.into_raw() as usize); + } } } @@ -553,10 +581,11 @@ unsafe fn create_internal_texture(dev: *mut c_void, pc_desc: &[u8; 0x38], initia Some(ID3D12Resource::from_raw(out)) } -/// Obtain or create the host UAV texture backing `CreateUnorderedAccessViewAtX` at `va`. -pub(super) unsafe fn placed_uav_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> *mut c_void { +/// Obtain or create the host UAV texture backing `CreateUnorderedAccessViewAtX` at `va`, +/// returning an owned reference so concurrent eviction cannot free it mid-call. +pub(super) unsafe fn placed_uav_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> Option { if rdesc.is_null() || va == 0 || !crate::gpu::shader::readable(rdesc as usize, 0x38) { - return std::ptr::null_mut(); + return None; } let raw_x: [u8; 0x38] = (rdesc as *const [u8; 0x38]).read_unaligned(); let prepared = prepare_placed_uav_desc(&raw_x, view_fmt); @@ -566,7 +595,7 @@ pub(super) unsafe fn placed_uav_resource(dev: *mut c_void, rdesc: *const u8, va: let mut g = TABLE.lock().unwrap(); let t = g.get_or_insert_with(AliasTable::new); if let Some(res) = t.placed_uavs.get(&key) { - return res.as_raw(); + return Some(res.clone()); } } @@ -583,7 +612,7 @@ pub(super) unsafe fn placed_uav_resource(dev: *mut c_void, rdesc: *const u8, va: if N.fetch_add(1, Ordering::Relaxed) < 8 { crate::xlog_warn!("D3D12.X: placed UAV texture at {va:#x} (view fmt {view_fmt}) could not be created"); } - return std::ptr::null_mut(); + return None; }; let raw = res.as_raw(); if is_depth_uav { @@ -591,47 +620,52 @@ pub(super) unsafe fn placed_uav_resource(dev: *mut c_void, rdesc: *const u8, va: } let pc_desc = res.GetDesc(); let shape = TexShape::from_pc_desc(&pc_desc); - let mark = { + let (winner, lost_race, mark) = { let mut g = TABLE.lock().unwrap(); let t = g.get_or_insert_with(AliasTable::new); - let entry = t.placed_uavs.entry(key).or_insert(res); - let raw_in = entry.as_raw(); - if raw_in == raw && !is_depth_uav && enabled() { + let (winner, loser) = cache_insert_or_clone(&mut t.placed_uavs, key, res); + let mark = if loser.is_none() && !is_depth_uav && enabled() { t.insert( raw as usize, TrackedTex::new(dev as usize, va as usize, shape, Owner::PlacedUav, STATE_UAV, true), ) } else { Vec::new() - } + }; + (winner, loser, mark) }; + if let Some(loser) = lost_race { + defer_drop_resources(vec![loser]); + } else { + static LOGGED: AtomicU64 = AtomicU64::new(0); + let n = LOGGED.fetch_add(1, Ordering::Relaxed); + if n < 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: placed UAV texture at {va:#x} ({}x{}x{}, {} mips, pc fmt {}, view fmt {view_fmt}) -> {raw:p} ({} created)", + pc_desc.Width, + pc_desc.Height, + pc_desc.DepthOrArraySize, + pc_desc.MipLevels, + pc_desc.Format.0, + n + 1 + ); + } + } for reader in mark { super::title_textures::note_gpu_write(reader); } - static LOGGED: AtomicU64 = AtomicU64::new(0); - let n = LOGGED.fetch_add(1, Ordering::Relaxed); - if n < 8 || n.is_power_of_two() { - crate::xlog_info!( - "D3D12.X: placed UAV texture at {va:#x} ({}x{}x{}, {} mips, pc fmt {}, view fmt {view_fmt}) -> {raw:p} ({} created)", - pc_desc.Width, - pc_desc.Height, - pc_desc.DepthOrArraySize, - pc_desc.MipLevels, - pc_desc.Format.0, - n + 1 - ); - } - raw + Some(winner) } -/// Obtain or create the host SRV texture backing `CreateShaderResourceViewAtX` at `va`. +/// Obtain or create the host SRV texture backing `CreateShaderResourceViewAtX` at `va`, +/// returning an owned reference so concurrent eviction cannot free it mid-call. /// If a GPU writer already occupies `va` with a compatible shape, creates a dedicated GPU-synced /// SRV texture (skipping `title_textures` so CPU zeros never overwrite GPU writes); otherwise /// delegates to `create_placed_resource_x` and registers it as a reader in case a placed UAV /// appears at `va` later. -pub(super) unsafe fn placed_srv_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> *mut c_void { +pub(super) unsafe fn placed_srv_resource(dev: *mut c_void, rdesc: *const u8, va: u64, view_fmt: u32) -> Option { if rdesc.is_null() || va == 0 || !crate::gpu::shader::readable(rdesc as usize, 0x38) { - return std::ptr::null_mut(); + return None; } let raw_x: [u8; 0x38] = (rdesc as *const [u8; 0x38]).read_unaligned(); let prepared = prepare_placed_srv_desc(&raw_x, view_fmt); @@ -644,17 +678,14 @@ pub(super) unsafe fn placed_srv_resource(dev: *mut c_void, rdesc: *const u8, va: let mut g = TABLE.lock().unwrap(); let t = g.get_or_insert_with(AliasTable::new); if let Some(res) = t.placed_srvs.get(&key) { - return res.as_raw(); + return Some(res.clone()); } enabled() && t.has_writer_at(va as usize, &shape) }; let res = if has_writer { // Dedicated GPU-synced SRV texture in COMMON state (not registered in title_textures). - match create_internal_texture(dev, &pc, STATE_COMMON) { - Some(r) => r, - None => return std::ptr::null_mut(), - } + create_internal_texture(dev, &pc, STATE_COMMON)? } else { let mut r = std::ptr::null_mut(); let hr = super::device_x::create_placed_resource_x( @@ -671,31 +702,34 @@ pub(super) unsafe fn placed_srv_resource(dev: *mut c_void, rdesc: *const u8, va: if N.fetch_add(1, Ordering::Relaxed) < 8 { crate::xlog_warn!("D3D12.X: placed SRV texture at {va:#x}: resource creation failed ({hr:#x})"); } - return std::ptr::null_mut(); + return None; } ID3D12Resource::from_raw(r) }; let raw = res.as_raw(); let owner = if has_writer { Owner::PlacedSrv } else { Owner::TitlePlaced }; - let mark = { + let (winner, lost_race, mark) = { let mut g = TABLE.lock().unwrap(); let t = g.get_or_insert_with(AliasTable::new); - let entry = t.placed_srvs.entry(key).or_insert(res); - let raw_in = entry.as_raw(); - if raw_in == raw && enabled() { + let (winner, loser) = cache_insert_or_clone(&mut t.placed_srvs, key, res); + let mark = if loser.is_none() && enabled() { t.insert( raw as usize, TrackedTex::new(dev as usize, va as usize, shape, owner, STATE_COMMON, false), ) } else { Vec::new() - } + }; + (winner, loser, mark) }; + if let Some(loser) = lost_race { + defer_drop_resources(vec![loser]); + } for reader in mark { super::title_textures::note_gpu_write(reader); } - raw + Some(winner) } /// Register a title-created placed texture from `device_x::create_placed_resource_x`. @@ -1164,7 +1198,7 @@ pub(super) unsafe fn on_uav_barrier(list: *mut c_void, specific_targets: Option< }; let dev_raw = dev.as_raw() as usize; let mut skipped = 0usize; - let pairs: Vec = { + let pairs: Vec<(AliasPair, Option, Option)> = { let g = TABLE.lock().unwrap(); match g.as_ref() { Some(t) => t @@ -1188,6 +1222,7 @@ pub(super) unsafe fn on_uav_barrier(list: *mut c_void, specific_targets: Option< } true }) + .map(|p| (p, t.clone_internal(p.writer), t.clone_internal(p.reader))) .collect(), None => return, } @@ -1196,7 +1231,7 @@ pub(super) unsafe fn on_uav_barrier(list: *mut c_void, specific_targets: Option< note_skipped_sync(); } let mut writer_ok: HashMap = HashMap::new(); - for pair in pairs { + for (pair, _writer_pin, _reader_pin) in pairs { let ok = sync_pair(list, &dev, ty, pair, STATE_UAV); let entry = writer_ok.entry(pair.writer).or_insert(true); *entry &= ok; @@ -1237,10 +1272,16 @@ pub(super) unsafe fn sync_title_writers(list: *mut c_void, writers: &[(usize, u3 if !seen.insert(writer) { continue; } - let pairs: Vec = { + let pairs: Vec<(AliasPair, Option, Option)> = { let g = TABLE.lock().unwrap(); match g.as_ref() { - Some(t) => t.pairs.iter().copied().filter(|p| p.writer == writer && p.device == dev_raw).collect(), + Some(t) => t + .pairs + .iter() + .copied() + .filter(|p| p.writer == writer && p.device == dev_raw) + .map(|p| (p, t.clone_internal(p.writer), t.clone_internal(p.reader))) + .collect(), None => continue, } }; @@ -1248,7 +1289,7 @@ pub(super) unsafe fn sync_title_writers(list: *mut c_void, writers: &[(usize, u3 continue; } let mut all_ok = true; - for pair in pairs { + for (pair, _writer_pin, _reader_pin) in pairs { all_ok &= sync_pair(list, &dev, ty, pair, state); } if all_ok { @@ -1588,4 +1629,41 @@ mod tests { forget(reader); forget(writer); } + + #[test] + fn cache_insert_or_clone_returns_winner_and_keeps_handle_alive_across_eviction() { + use std::sync::Arc; + + let mut cache: HashMap> = HashMap::new(); + let first = Arc::new(111u32); + let second = Arc::new(222u32); + + // Initial insert: map and caller both hold a reference to `first`. + let (h1, loser1) = cache_insert_or_clone(&mut cache, 0x1000, Arc::clone(&first)); + assert!(loser1.is_none()); + assert_eq!(*h1, 111); + assert_eq!(Arc::strong_count(&first), 3); // local `first` + cache + `h1` + + // Concurrent miss race: returns a handle to the winning `first` and hands `second` + // back to the caller so it can be dropped outside the lock without UAF or deadlock. + let (h2, loser2) = cache_insert_or_clone(&mut cache, 0x1000, Arc::clone(&second)); + assert_eq!(*h2, 111, "concurrent race must return the cached winner, not the loser"); + assert!(Arc::ptr_eq(&h2, &first)); + let loser = loser2.expect("duplicate loser must be returned for outside-lock drop"); + assert!(Arc::ptr_eq(&loser, &second)); + assert_eq!(Arc::strong_count(&second), 2); + drop(loser); + assert_eq!(Arc::strong_count(&second), 1); + + // Concurrent eviction while `h1` / `h2` are in use keeps the resource alive until dropped. + drop(first); + let evicted = cache.remove(&0x1000).unwrap(); + drop(evicted); + assert_eq!(*h1, 111); + assert_eq!(*h2, 111); + assert_eq!(Arc::strong_count(&h1), 2); + drop(h1); + assert_eq!(Arc::strong_count(&h2), 1); + drop(h2); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index d1efa6a264..bb8f4cf052 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2831,7 +2831,8 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } // a depth buffer's view in the formats the PC has for it (a D24S8 format itself, R16_UNORM of // a D16S8 buffer …: an invalid call, the device removed) - if let Some(v) = ID3D12Resource::from_raw_borrowed(&res).and_then(|r| pc_srv(&r.GetDesc(), copy.as_ref())) { + let rdesc_opt = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); + if let Some(v) = rdesc_opt.as_ref().and_then(|rd| pc_srv(rd, copy.as_ref())) { copy = Some(v); } let desc = copy.as_ref().map_or(desc, |c| c as *const _); @@ -2878,15 +2879,14 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, if super::present::trace_frame() && super::title_textures::address(res as usize).is_some() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 24 { - let rd = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()); let v = desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0, v.Shader4ComponentMapping, v.Anonymous.Texture2D.MostDetailedMip, v.Anonymous.Texture2D.MipLevels, v.Anonymous.Texture2D.ResourceMinLODClamp)); crate::xlog_info!( "frame trace: SRV of title texture {res:p} {:?}: view (format, dimension, mapping, mip, mips, clamp) {v:x?}", - rd.map(|d| (d.Width, d.Height, d.Format.0, d.MipLevels, d.Flags.0)) + rdesc_opt.map(|d| (d.Width, d.Height, d.Format.0, d.MipLevels, d.Flags.0)) ); } } - let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else { + let Some(rdesc) = rdesc_opt else { super::ambient::note_descriptor(slot.index, 0, 0, 0, false); // A null image SRV was already created and published at `slot.index`. Writing `[0; 8]` // would point shaders at `ResourceDescriptorHeap[0]` (memory window 0 / uninitialized), @@ -2906,7 +2906,6 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true)); } - let rdesc = r.GetDesc(); super::ambient::note_descriptor(slot.index, res as usize, desc.as_ref().map_or(rdesc.Format.0, |v| v.Format.0), rdesc.Format.0, false); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { Some(t) => super::console_heap::write(&slot, &t), @@ -2954,7 +2953,10 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true); return super::console_heap::write(&slot, &words); } - dev_create_srv_x(this, super::format_alias::placed_srv_resource(this, rdesc, va, v.Format.0 as u32), &v, cpu); + let placed = super::format_alias::placed_srv_resource(this, rdesc, va, v.Format.0 as u32); + let res = placed.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw); + dev_create_srv_x(this, res, &v, cpu); + drop(placed); } /// device #71: the same for an unordered access view ({ the PC's UAV desc; GPU address @0x28; @@ -2972,7 +2974,10 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, false); return super::console_heap::write(&slot, &words); } - dev_create_uav_x(this, super::format_alias::placed_uav_resource(this, rdesc, va, v.Format.0 as u32), std::ptr::null_mut(), &v, cpu); + let placed = super::format_alias::placed_uav_resource(this, rdesc, va, v.Format.0 as u32); + let res = placed.as_ref().map_or(std::ptr::null_mut(), Interface::as_raw); + dev_create_uav_x(this, res, std::ptr::null_mut(), &v, cpu); + drop(placed); } /// V# of `n` elements from element `first` of the buffer at `va`. From 3a2a89123371a9a3e615ec00f4ade92c2cc14e39 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:15:22 +0100 Subject: [PATCH 171/258] D3D12.X: fix ambient stand-in SM 6.6 heap/UAV lookup and indirect dispatch In live world runs ambient.rs tracked TemporalResolve / ReflectionHistory PSOs and captured the 128x128 sky dome, yet ambient_fill_cs and reflect_clamp_cs never dispatched because find_dispatch_views missed the output UAV: - SM 6.6 directly-indexed bindless heaps bind the view heap via SetDescriptorHeaps (s.heaps[0]) rather than Param::Table, leaving tables empty. - ExecuteIndirect compute dispatches (both chained split and direct) never called ambient::after_compute_dispatch, and matches_dispatch_target rejected indirect/1D dispatches. - matches_dispatch_target checked the resource format (often R16G16B16A16_TYPELESS) instead of the concrete UAV view format (R16G16B16A16_FLOAT / R11G11B10_FLOAT / R32G32B32A32_FLOAT). - VIEW_SLOTS was keyed only by slot.index, colliding across CPU-only view heaps before CopyDescriptors copied them to the >1.24M-slot shader-visible heap, while the 1<<20 index cap and 256-byte CBV scan truncated high slots and larger pass CBVs. Pass s.heaps[0] into find_dispatch_views, hook ExecuteIndirect compute dispatches, index ViewSlots by both unique slot.at and hosted GLOBAL index, raise the slot cap to 2_000_000 and CBV scan to 2048 B, match by concrete UAV view format with DepthOrArraySize == 1 guard, rank candidates by dispatch grid match, and log first-4 diagnostic misses. Verified with cargo check -p xcl --lib and hle::d3d12x::ambient::tests (5 passed, 0 failed). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/ambient.rs | 274 +++++++++++++++++----- crates/xcl/src/hle/d3d12x/bind.rs | 12 +- crates/xcl/src/hle/d3d12x/console_heap.rs | 14 +- crates/xcl/src/hle/d3d12x/real.rs | 14 +- 4 files changed, 238 insertions(+), 76 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index fc76f75b34..fcc3aac59f 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -13,7 +13,7 @@ //! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, //! `XCL_AMBIENT_REFLECT`. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::ffi::c_void; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; @@ -185,8 +185,10 @@ fn role_of(pso: usize) -> Option { PSO_ROLES.read().unwrap().as_ref()?.get(&pso).copied() } -/// Descriptor-heap view metadata indexed by `GLOBAL` heap descriptor index (`T# word 0`), so -/// descriptors copied via either `CopyDescriptorsSimple` or inline title `memcpy` resolve cleanly. +/// Descriptor-heap view metadata indexed by BOTH console slot UMA address (`slot.at`, globally +/// unique across all shader-visible and CPU-only heaps) and `GLOBAL` heap descriptor index +/// (`slot.index` when hosted in `GLOBAL`) so both `CopyDescriptors*` and inline title `memcpy` +/// resolve without CPU-only heap index collisions. #[derive(Clone, Copy, Debug)] struct ViewEntry { res: usize, @@ -194,11 +196,18 @@ struct ViewEntry { is_uav: bool, } -static VIEW_SLOTS: RwLock>> = RwLock::new(None); +#[derive(Default)] +struct ViewSlots { + by_addr: HashMap, + by_idx: HashMap, +} + +static VIEW_SLOTS: RwLock> = RwLock::new(None); static HAS_VIEW_SLOTS: AtomicBool = AtomicBool::new(false); fn is_ambient_uav_format(fmt: i32) -> bool { - matches!(fmt, 10 | 26) // R16G16B16A16_FLOAT, R11G11B10_FLOAT + // R16G16B16A16_FLOAT (10), R11G11B10_FLOAT (26), R32G32B32A32_FLOAT (2) + matches!(fmt, 10 | 26 | 2) } fn is_depth_srv_format(fmt: i32) -> bool { @@ -210,15 +219,21 @@ fn is_depth_resource_format(fmt: i32) -> bool { matches!(fmt, 19 | 20 | 39 | 40 | 44 | 45 | 53 | 55) } -/// Record a 2D texture UAV or depth SRV written at `GLOBAL` descriptor index `slot_index`. -pub(super) fn note_descriptor(slot_index: u32, res: usize, fmt: i32, res_fmt: i32, is_uav: bool) { - if !enabled() || slot_index == 0 { +/// Record a 2D texture UAV or depth SRV written at console slot address `slot_at` (and optional +/// `GLOBAL` descriptor index `global_index`, 0 when on a CPU-only / unhosted heap). +pub(super) fn note_descriptor(slot_at: usize, global_index: u32, res: usize, fmt: i32, res_fmt: i32, is_uav: bool) { + if !enabled() || (slot_at == 0 && global_index == 0) { return; } if res == 0 { if HAS_VIEW_SLOTS.load(Ordering::Relaxed) { - if let Some(m) = VIEW_SLOTS.write().unwrap().as_mut() { - m.remove(&slot_index); + if let Some(s) = VIEW_SLOTS.write().unwrap().as_mut() { + if slot_at != 0 { + s.by_addr.remove(&slot_at); + } + if global_index != 0 { + s.by_idx.remove(&global_index); + } } } return; @@ -230,11 +245,22 @@ pub(super) fn note_descriptor(slot_index: u32, res: usize, fmt: i32, res_fmt: i3 }; let mut g = VIEW_SLOTS.write().unwrap(); if keep { - g.get_or_insert_with(HashMap::new) - .insert(slot_index, ViewEntry { res, fmt, is_uav }); + let s = g.get_or_insert_with(ViewSlots::default); + let ve = ViewEntry { res, fmt, is_uav }; + if slot_at != 0 { + s.by_addr.insert(slot_at, ve); + } + if global_index != 0 { + s.by_idx.insert(global_index, ve); + } HAS_VIEW_SLOTS.store(true, Ordering::Release); - } else if let Some(m) = g.as_mut() { - m.remove(&slot_index); + } else if let Some(s) = g.as_mut() { + if slot_at != 0 { + s.by_addr.remove(&slot_at); + } + if global_index != 0 { + s.by_idx.remove(&global_index); + } } } @@ -244,25 +270,43 @@ pub(super) fn forget_resource(res: usize) { if res == 0 || !HAS_VIEW_SLOTS.load(Ordering::Relaxed) { return; } - if let Some(m) = VIEW_SLOTS.write().unwrap().as_mut() { - m.retain(|_, v| v.res != res); + if let Some(s) = VIEW_SLOTS.write().unwrap().as_mut() { + s.by_addr.retain(|_, v| v.res != res); + s.by_idx.retain(|_, v| v.res != res); } } -/// Propagate view metadata when `CopyDescriptorsSimple` renumbers a T# from `src_index` to `dst_index`. -pub(super) fn copy_descriptor(src_index: u32, dst_index: u32) { - if !enabled() || src_index == dst_index { +/// Propagate view metadata when `CopyDescriptors*` copies from `src_at` (with pre-copy T# word 0 +/// `src_global_index`) to `dst_at` (with destination `GLOBAL` index `dst_global_index`, 0 if unhosted). +pub(super) fn copy_descriptor(src_at: usize, src_global_index: u32, dst_at: usize, dst_global_index: u32) { + if !enabled() || !HAS_VIEW_SLOTS.load(Ordering::Relaxed) || (src_at == dst_at && src_global_index == dst_global_index) { return; } - let entry = VIEW_SLOTS.read().unwrap().as_ref().and_then(|m| m.get(&src_index).copied()); + let entry = VIEW_SLOTS.read().unwrap().as_ref().and_then(|s| { + s.by_addr + .get(&src_at) + .or_else(|| (src_global_index != 0).then(|| s.by_idx.get(&src_global_index)).flatten()) + .copied() + }); let mut g = VIEW_SLOTS.write().unwrap(); match entry { Some(v) => { - g.get_or_insert_with(HashMap::new).insert(dst_index, v); + let s = g.get_or_insert_with(ViewSlots::default); + if dst_at != 0 { + s.by_addr.insert(dst_at, v); + } + if dst_global_index != 0 { + s.by_idx.insert(dst_global_index, v); + } } None => { - if let Some(m) = g.as_mut() { - m.remove(&dst_index); + if let Some(s) = g.as_mut() { + if dst_at != 0 { + s.by_addr.remove(&dst_at); + } + if dst_global_index != 0 { + s.by_idx.remove(&dst_global_index); + } } } } @@ -276,25 +320,46 @@ fn is_sky_dome_target(rd: &D3D12_RESOURCE_DESC) -> bool { && rd.SampleDesc.Count == 1 } -/// Match a screen-space resolve/reflection output UAV against dispatch grid dimensions. -fn matches_dispatch_target(rd: &D3D12_RESOURCE_DESC, groups: [u32; 3]) -> bool { +/// Match a screen-space resolve/reflection output UAV against dispatch grid dimensions, returning +/// a lower-is-better score when compatible (`None` if incompatible). +/// Uses the UAV view's concrete `view_fmt` so typeless resources (`R16G16B16A16_TYPELESS`) match. +fn score_dispatch_target(rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; 3]) -> Option { if rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D + || rd.DepthOrArraySize != 1 || rd.SampleDesc.Count != 1 || rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 - || !is_ambient_uav_format(rd.Format.0) + || !is_ambient_uav_format(view_fmt) { - return false; + return None; } let w = rd.Width as u32; let h = rd.Height; - if w < 64 || h < 64 || groups[0] == 0 || groups[1] == 0 { - return false; + if w < 64 || h < 64 { + return None; } - let max_w = groups[0].saturating_mul(32); - let max_h = groups[1].saturating_mul(32); - let min_w = groups[0].saturating_mul(4); - let min_h = groups[1].saturating_mul(4); - w >= min_w && w <= max_w && h >= min_h && h <= max_h + // Indirect or 1D tiled dispatch (`groups[0] == 0` or `groups[1] <= 1`): match screen-space 2D + // float UAV targets (>= 128x72), preferring larger resolution. + if groups[0] == 0 || groups[1] <= 1 { + if w < 128 || h < 72 { + return None; + } + return Some(u64::MAX - (w as u64).saturating_mul(h as u64)); + } + let max_w = groups[0].saturating_mul(64); + let max_h = groups[1].saturating_mul(64); + let min_w = groups[0].saturating_mul(2); + let min_h = groups[1].saturating_mul(2); + if w < min_w || w > max_w || h < min_h || h > max_h { + return None; + } + let ideal_w = groups[0].saturating_mul(8) as i64; + let ideal_h = groups[1].saturating_mul(8) as i64; + Some((w as i64 - ideal_w).unsigned_abs() + (h as i64 - ideal_h).unsigned_abs()) +} + +#[cfg(test)] +fn matches_dispatch_target(rd: &D3D12_RESOURCE_DESC, groups: [u32; 3]) -> bool { + score_dispatch_target(rd, rd.Format.0, groups).is_some() } /// Compute scalar/RGB stand-in sky level (mirrors the GPU `sky_reduce_cs` transfer curve). @@ -771,21 +836,38 @@ pub(super) unsafe fn after_draw(list: *mut c_void, pso_resolved: usize) { } } -/// Inspect a compute dispatch's bound descriptor tables and root constants/CBVs to locate its -/// output screen-space float UAV (and optional depth SRV for crease AO). -unsafe fn find_dispatch_views(layout: &Layout, args: &[u8], groups: [u32; 3]) -> (Option<(usize, i32, u32, u32)>, Option<(usize, i32, u32, u32)>) { - let Some(u) = crate::gpu::uma::get() else { return (None, None) }; +/// Maximum bindless descriptor-heap slot index probed from root constants/CBVs +/// (covers >1.24M-slot console shader-visible view heaps). +const MAX_SLOT_INDEX: u32 = 2_000_000; + +/// Inspect a compute dispatch's bound descriptor tables, SM 6.6 directly-indexed view heap +/// (`view_heap_base`), and root constants/CBVs to locate its output screen-space float UAV +/// (and optional depth SRV for crease AO). +unsafe fn find_dispatch_views( + layout: &Layout, + args: &[u8], + groups: [u32; 3], + view_heap_base: u32, +) -> (Option<(usize, i32, u32, u32)>, Option<(usize, i32, u32, u32)>, usize, usize) { + let Some(u) = crate::gpu::uma::get() else { return (None, None, 0, 0) }; let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); let mut tables: Vec = Vec::new(); let mut indices: Vec = Vec::new(); + let mut seen: HashSet = HashSet::new(); + let mut push_idx = |v: u32| { + if v < MAX_SLOT_INDEX && seen.insert(v) { + indices.push(v); + } + }; + if view_heap_base != 0 { + tables.push(view_heap_base); + } for p in &layout.params { match *p { Param::Constants { at, count } => { - for k in 0..count.min(32) as usize { + for k in 0..count.min(64) as usize { if let Some(v) = word(at as usize + 4 * k) { - if v < (1 << 20) { - indices.push(v); - } + push_idx(v); } } } @@ -793,18 +875,26 @@ unsafe fn find_dispatch_views(layout: &Layout, args: &[u8], groups: [u32; 3]) -> let lo = word(at as usize).unwrap_or(0) as u64; let hi = word(at as usize + 4).unwrap_or(0) as u64; let va = (lo | (hi << 32)) as usize; - if va != 0 && crate::gpu::shader::readable(va, 256) { - for k in 0..64usize { - let v = ((va + 4 * k) as *const u32).read_unaligned(); - if v < (1 << 20) { - indices.push(v); + if va != 0 { + // Scan up to 2048 bytes (512 u32s) in 256-byte readable chunks so bindless + // pass/frame CBVs larger than 256 bytes are covered safely. + for chunk in 0..8usize { + let base = va + chunk * 256; + if !crate::gpu::shader::readable(base, 256) { + break; + } + for k in 0..64usize { + let v = ((base + 4 * k) as *const u32).read_unaligned(); + if v != 0 { + push_idx(v); + } } } } } Param::Table { at } => { if let Some(t) = word(at as usize) { - if t != 0 { + if t != 0 && !tables.contains(&t) { tables.push(t); } } @@ -813,13 +903,13 @@ unsafe fn find_dispatch_views(layout: &Layout, args: &[u8], groups: [u32; 3]) -> } // Also probe direct table slots 0..16 in case descriptors are bound directly without bindless indices. for k in 0..16u32 { - indices.push(k); + push_idx(k); } - let mut uav_hit: Option<(usize, i32, u32, u32)> = None; + let mut uav_hit: Option<(u64, usize, i32, u32, u32)> = None; let mut depth_hit: Option<(usize, i32, u32, u32)> = None; let slots = VIEW_SLOTS.read().unwrap(); - let Some(map) = slots.as_ref() else { return (None, None) }; + let Some(vs) = slots.as_ref() else { return (None, None, tables.len(), indices.len()) }; for &t in &tables { for &idx in &indices { @@ -834,27 +924,34 @@ unsafe fn find_dispatch_views(layout: &Layout, args: &[u8], groups: [u32; 3]) -> if (w3 >> 28) < 8 { continue; } - let Some(&ve) = map.get(&w0) else { continue }; + let Some(&ve) = vs + .by_addr + .get(&addr) + .or_else(|| (w0 != 0).then(|| vs.by_idx.get(&w0)).flatten()) + else { + continue; + }; let ptr = ve.res as *mut c_void; let Some(res) = ID3D12Resource::from_raw_borrowed(&ptr) else { continue }; let rd = res.GetDesc(); - if ve.is_uav && uav_hit.is_none() && matches_dispatch_target(&rd, groups) { - uav_hit = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height)); - } else if !ve.is_uav - && depth_hit.is_none() + if ve.is_uav { + if let Some(score) = score_dispatch_target(&rd, ve.fmt, groups) { + if uav_hit.is_none_or(|(best, _, _, _, _)| score < best) { + uav_hit = Some((score, ve.res, ve.fmt, rd.Width as u32, rd.Height)); + } + } + } else if depth_hit.is_none() && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && rd.DepthOrArraySize == 1 && rd.SampleDesc.Count == 1 && rd.Width >= 64 && rd.Height >= 64 { depth_hit = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height)); } - if uav_hit.is_some() && depth_hit.is_some() { - return (uav_hit, depth_hit); - } } } - (uav_hit, depth_hit) + (uav_hit.map(|(_, r, f, w, h)| (r, f, w, h)), depth_hit, tables.len(), indices.len()) } /// Called right after a translated compute dispatch completes: when RT is gated off and a sky @@ -866,6 +963,7 @@ pub(super) unsafe fn after_compute_dispatch( groups: [u32; 3], layout: Option<&Layout>, args: &[u8], + view_heap_base: u32, ) { if !has_compute_psos() || !active() { return; @@ -887,11 +985,23 @@ pub(super) unsafe fn after_compute_dispatch( let Some(dev) = dev else { return }; let Some(ad) = get_device(&dev) else { return }; if !ad.sky_ready.load(Ordering::Acquire) { + static NO_SKY: AtomicU64 = AtomicU64::new(0); + if NO_SKY.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_info!("D3D12.X: ambient: {role:?} dispatched ({groups:?}) before sky dome capture"); + } return; } - let (uav_opt, depth_opt) = find_dispatch_views(layout, args, groups); - let Some((uav_res, uav_fmt, w, h)) = uav_opt else { return }; + let (uav_opt, depth_opt, n_tables, n_indices) = find_dispatch_views(layout, args, groups, view_heap_base); + let Some((uav_res, uav_fmt, w, h)) = uav_opt else { + static MISS: AtomicU64 = AtomicU64::new(0); + if MISS.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_info!( + "D3D12.X: ambient: {role:?} ({groups:?}) found no matching UAV (tables={n_tables}, view_heap={view_heap_base:#x}, indices={n_indices})" + ); + } + return; + }; if role == PassRole::ReflectionHistory && !typed_uav_load_supported(&dev, DXGI_FORMAT(uav_fmt)) { return; } @@ -1045,4 +1155,44 @@ mod tests { assert!(compile_cs_sm5(AMBIENT_FILL_HLSL).is_some(), "AMBIENT_FILL_HLSL failed D3DCompile"); assert!(compile_cs_sm5(REFLECT_CLAMP_HLSL).is_some(), "REFLECT_CLAMP_HLSL failed D3DCompile"); } + + #[test] + fn typeless_uav_indirect_dispatch_and_cpu_heap_slot_copy_resolve_cleanly() { + // Typeless resource with concrete R16G16B16A16_FLOAT UAV view must match (both direct and indirect). + let typeless = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1920, + Height: 1080, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_TYPELESS, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + assert!(score_dispatch_target(&typeless, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [240, 135, 1]).is_some()); + assert!(score_dispatch_target(&typeless, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [0, 0, 0]).is_some()); + // Texture2DArray must be rejected for TEXTURE2D view creation. + let arr = D3D12_RESOURCE_DESC { DepthOrArraySize: 4, ..typeless }; + assert!(score_dispatch_target(&arr, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [240, 135, 1]).is_none()); + + // Two distinct CPU-only heap slots (`global_index == 0`) at different addresses must not collide + // before being copied to the shader-visible heap. + let cpu_slot_a = 0x7F00_0000_0020usize; + let cpu_slot_b = 0x7F00_0010_0020usize; + let sv_slot_dst = 0x7F00_0020_0040usize; + let res_a = 0x7F00_AAAAusize; + let res_b = 0x7F00_BBBBusize; + note_descriptor(cpu_slot_a, 0, res_a, DXGI_FORMAT_R16G16B16A16_FLOAT.0, DXGI_FORMAT_R16G16B16A16_TYPELESS.0, true); + note_descriptor(cpu_slot_b, 0, res_b, DXGI_FORMAT_R8G8B8A8_UNORM.0, DXGI_FORMAT_R8G8B8A8_UNORM.0, false); + copy_descriptor(cpu_slot_a, 0, sv_slot_dst, 1_100_002); + { + let g = VIEW_SLOTS.read().unwrap(); + let vs = g.as_ref().unwrap(); + assert_eq!(vs.by_addr.get(&sv_slot_dst).map(|v| v.res), Some(res_a)); + assert_eq!(vs.by_idx.get(&1_100_002).map(|v| v.res), Some(res_a)); + } + forget_resource(res_a); + note_descriptor(cpu_slot_b, 0, 0, 0, 0, false); + } } diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index ca2d2075a9..8b52dc708e 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3588,6 +3588,10 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us ) { Ok(true) => { super::culprit::after_dispatch(list, mark); + if super::ambient::has_compute_psos() { + let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); + super::ambient::after_compute_dispatch(this, pso, [0, 0, 0], layout.as_deref(), &args, view_heap); + } with(this, |s| { s.pc_abi_cs = AbiBound::default(); s.arg_order_clean = false; @@ -3665,6 +3669,10 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } super::culprit::after_dispatch(list, mark); if compute { + if super::ambient::has_compute_psos() { + let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); + super::ambient::after_compute_dispatch(this, pso, [0, 0, 0], layout.as_deref(), &args, view_heap); + } with(this, |s| { s.arg_order_clean = false; s.prelude_blocked = true; @@ -4493,8 +4501,8 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis let r = super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]); super::culprit::after_dispatch(list, mark); if super::ambient::has_compute_psos() { - let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone())); - super::ambient::after_compute_dispatch(this, pso, [x, y, z], layout.as_deref(), &args); + let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); + super::ambient::after_compute_dispatch(this, pso, [x, y, z], layout.as_deref(), &args, view_heap); } with(this, |s| { s.arg_order_clean = false; diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 6702588310..59e1b97ed4 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -738,6 +738,7 @@ pub fn copy_words(src: &Slot, dst: &Slot) { let n = if src.sampler { 4 } else { 8 }; let mut w = [0u32; 8]; unsafe { std::ptr::copy_nonoverlapping(src.at as *const u32, w.as_mut_ptr(), n) }; + let src_w0 = w[0]; if src.sampler { w[3] = (w[3] & !0xFFF) | (dst.index & 0xFFF); } else if w[3] >> 28 >= 8 { @@ -749,7 +750,9 @@ pub fn copy_words(src: &Slot, dst: &Slot) { note_resource(dst, resource_at(src.at).unwrap_or(0)); } if w[3] >> 28 >= 8 { - super::ambient::copy_descriptor(src.index, dst.index); + let src_idx = if src.shared_srv != 0 { src_w0 } else { 0 }; + let dst_idx = if dst.shared_srv != 0 { dst.index } else { 0 }; + super::ambient::copy_descriptor(src.at, src_idx, dst.at, dst_idx); } } } @@ -801,6 +804,7 @@ pub fn copy_words_range(dst: u64, src: u64, n: u32) -> bool { }; let mut w = [0u32; 8]; unsafe { std::ptr::copy_nonoverlapping(src_at as *const u32, w.as_mut_ptr(), words_n) }; + let src_w0 = w[0]; let is_tex = !sampler && (w[3] >> 28 >= 8); if sampler { w[3] = (w[3] & !0xFFF) | (dst_idx & 0xFFF); @@ -819,11 +823,9 @@ pub fn copy_words_range(dst: u64, src: u64, n: u32) -> bool { } } if is_tex { - let src_idx = match s_page { - Some((first, k0)) => first + 2 * (ksi - k0), - None => view_unmapped_index(s_hosted, ksi), - }; - super::ambient::copy_descriptor(src_idx, dst_idx); + let src_global = if s_hosted && s_page.is_some() { src_w0 } else { 0 }; + let dst_global = if d_hosted && d_page.is_some() { dst_idx } else { 0 }; + super::ambient::copy_descriptor(src_at, src_global, dst_at, dst_global); } } done += run; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index bb8f4cf052..0f02207d65 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2886,8 +2886,9 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, ); } } + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; let Some(rdesc) = rdesc_opt else { - super::ambient::note_descriptor(slot.index, 0, 0, 0, false); + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, false); // A null image SRV was already created and published at `slot.index`. Writing `[0; 8]` // would point shaders at `ResourceDescriptorHeap[0]` (memory window 0 / uninitialized), // so write a valid T# referencing `slot.index` with the view's format class and type. @@ -2901,12 +2902,12 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, return super::console_heap::write(&slot, &[0; 8]); }; if let Some(v) = desc.as_ref().filter(|v| v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { - super::ambient::note_descriptor(slot.index, 0, 0, 0, false); + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, false); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true)); } - super::ambient::note_descriptor(slot.index, res as usize, desc.as_ref().map_or(rdesc.Format.0, |v| v.Format.0), rdesc.Format.0, false); + super::ambient::note_descriptor(slot.at, amb_idx, res as usize, desc.as_ref().map_or(rdesc.Format.0, |v| v.Format.0), rdesc.Format.0, false); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { Some(t) => super::console_heap::write(&slot, &t), None => { @@ -3299,8 +3300,9 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, pc_uav(slot.pc_uav); super::console_heap::publish(&slot, true); super::console_heap::note_resource(&slot, res as usize); + let amb_idx = if slot.shared_srv != 0 { slot.index } else { 0 }; let Some(r) = ID3D12Resource::from_raw_borrowed(&uav_res) else { - super::ambient::note_descriptor(slot.index, 0, 0, 0, true); + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, true); // A null image UAV was already created and published at `slot.index + 1`. Create a // matching null companion SRV at `slot.index` and write a valid T# referencing // `slot.index` so shaders never fall back to `ResourceDescriptorHeap[0]` / `[1]`. @@ -3319,7 +3321,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, }; let rd = uav_rd_opt.unwrap(); if let Some(v) = uav_desc.as_ref().filter(|v| v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { - super::ambient::note_descriptor(slot.index, 0, 0, 0, true); + super::ambient::note_descriptor(slot.at, amb_idx, 0, 0, 0, true); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, false)); @@ -3340,7 +3342,7 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } None => (rd.Format, resource_dim_to_view(&rd), rd.DepthOrArraySize as u32, 0), }; - super::ambient::note_descriptor(slot.index, uav_res as usize, format.0, rd.Format.0, true); + super::ambient::note_descriptor(slot.at, amb_idx, uav_res as usize, format.0, rd.Format.0, true); let Some((fmt, ty, w, h, d, _)) = view_shape(r, format, dim, array, 1) else { note_buffer_view(); return super::console_heap::write(&slot, &[0; 8]); From 4d0f0eb2008c255ef8ba5b316949edab6e5c40b7 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:17:08 +0100 Subject: [PATCH 172/258] KernelX / D3D12.X: clean coherent VirtualFree AWAY state and water readbacks Two defensive memory/resource-lifetime fixes: - kernelx.rs / uma.rs: clean up AWAY physical-page mappings, mirrors, and title mapping records on coherent UMA VirtualFree (MEM_DECOMMIT and MEM_RELEASE), matching sparse and plain VirtualFree so freed/reused coherent blocks never retain dangling AWAY entries. Add Uma::allocation_at and extend virtual_free_unmaps_away_pages_in_plain_and_sparse_reservations to cover coherent UMA MEM_DECOMMIT and MEM_RELEASE. - real.rs: call cpu_writes::unregister_water_readback in res_release so released or recycled placed textures never retain stale water-readback entries. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/gpu/uma.rs | 16 ++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 1 + crates/xcl/src/hle/kernelx.rs | 30 +++++++++++++++++++++++++++++- 3 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index fffb5e4690..faa2d32dbc 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -679,6 +679,22 @@ impl Uma { Some(p) } + /// The committed-window allocation covering `p`: `(start, bytes)` (excluding XCL's arena pool). + pub fn allocation_at(&self, p: usize) -> Option<(usize, usize)> { + if !self.is_committed(p) { + return None; + } + { + let pool = self.pool.lock().unwrap(); + if p >= pool.0 && p < pool.1 { + return None; + } + } + let off = p - self.base; + let g = self.inner.lock().unwrap(); + g.used.range(..=off).next_back().map(|(&o, &l)| (self.base + o, l)).filter(|&(a, l)| p < a + l) + } + /// Release a block from `alloc` (false: not one of ours). pub fn free(&self, p: usize) -> bool { if !self.is_committed(p) { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 0f02207d65..49a93efc04 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2087,6 +2087,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } super::depth_uav::forget(this as usize); super::format_alias::forget(this as usize); + super::cpu_writes::unregister_water_readback(this as usize); super::ambient::forget_resource(this as usize); forget_outside_resource(this as usize); let gone = UMA_BUFFERS.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 3fd882494e..38e4e700a8 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -672,10 +672,23 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 return 1; } if let Some(u) = crate::gpu::uma::get().filter(|u| u.contains(addr as usize)) { + let a = addr as usize; if t & 0x8000 != 0 { - return u.free(addr as usize) as BOOL; + let len = u.allocation_at(a).filter(|&(start, _)| start == a).map(|(_, l)| l); + if let Some(n) = len { + unmap_away_range(a, n); + } + let ok = u.free(a); + if ok { + mirrors::released(a); + if let Some(n) = len { + forget_title_mappings(a, n); + } + } + return ok as BOOL; } if t & 0x4000 != 0 && size > 0 { + unmap_away_range(a, size); std::ptr::write_bytes(addr as *mut u8, 0, size); } return 1; @@ -4149,6 +4162,21 @@ mod tests { assert!(!physical_page_at(sp) && physical_page_at(sp + PHYS_PAGE)); assert_eq!(VirtualFree(sp as *mut c_void, 0, mem::MEM_RELEASE), 1); assert!(!physical_page_at(sp + PHYS_PAGE) && !lazy::unmark(sp + PHYS_PAGE)); + // Coherent UMA allocation: partial MEM_DECOMMIT + MEM_RELEASE unmap AWAY pages cleanly. + let coh = u.alloc(2 * PHYS_PAGE, PHYS_PAGE).expect("coherent UMA alloc") as usize; + assert!(u.is_committed(coh)); + assert_eq!(MapTitlePhysicalPages(coh as *mut c_void, 2, 0, 4, [p0, p2].as_mut_ptr()) as usize, coh); + assert_eq!(*(coh as *const u32), 0x6666_0001); + *(coh as *mut u32) = 0x7777_0001; + *(coh.wrapping_add(PHYS_PAGE) as *mut u32) = 0x7777_0002; + assert_eq!(VirtualFree(coh as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT), 1); + assert!(!physical_page_at(coh) && physical_page_at(coh + PHYS_PAGE)); + assert_eq!(*(coh as *const u32), 0, "MEM_DECOMMIT zeroes coherent UMA range"); + assert_eq!(VirtualFree(coh as *mut c_void, 0, mem::MEM_RELEASE), 1); + assert!(!physical_page_at(coh + PHYS_PAGE)); + // Saved home bytes for p0 and p2 survive coherent VirtualFree. + let h0 = MapTitlePhysicalPages(std::ptr::null_mut(), 3, 0, 4, pages.as_mut_ptr()) as usize; + assert_eq!((*(h0 as *const u32), *((h0 + 2 * PHYS_PAGE) as *const u32)), (0x7777_0001, 0x7777_0002)); assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()), 1); } } From a9b637ee90b1b123446b7b510900c4923439065b Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:20:25 +0100 Subject: [PATCH 173/258] D3D12.X: never skip non-spared producer compute shaders, stamp slow graphics once, and guard unbuilt ExecuteIndirect - Keep non-spared memory-writing producer compute pipelines (`!spared && !bvh_traversal`) exempt from the per-frame `XCL_PSO_FRAME_BUDGET_MS` skip cutoff so world-entry dispatches never leave title memory/tables uninitialized; prioritize wanted producer compute ahead of wanted graphics in `PsoQueue::pop`, and run non-deprioritized producer compute inline when no worker has started it yet. - Restrict `XCL_PSO_FRAME_BUDGET_MS` skipping to graphics pipelines and stamp `waited_frame` on `Pending` so an unready slow graphics PSO stalls at most one frame while workers finish compiling it in the background. - Skip `list_x::defer` for `spared`/`bvh_traversal` compute PSOs and make `FrameDeferCap` slot reservation atomic (`try_reserve`/`release`) so concurrent threads cannot overshoot the per-frame deferred segment cap (producer dispatches past the cap fall through to `resolve_wait` instead of being dropped). - Add `pso_async::bound_unbuilt(raw_pso, pso)` for `execute_indirect` and `dispatch_mesh` so a pipeline that finishes building right after `resolve_for_bind` returned the stand-in cannot slip into the raw PC call with a mismatched root signature. Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/bind.rs | 14 +- crates/xcl/src/hle/d3d12x/list_x.rs | 64 ++++---- crates/xcl/src/hle/d3d12x/pso_async.rs | 214 +++++++++++++++++++------ 3 files changed, 210 insertions(+), 82 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 8b52dc708e..6d2bc04f0b 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3333,7 +3333,7 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: } return; } - if super::pso_async::is_pending(raw_pso) { + if super::pso_async::bound_unbuilt(raw_pso, pso) { count(DRAWS_SKIPPED); return; } @@ -3364,7 +3364,10 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let raw_pso = with(this, |s| s.pso); - let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); + let unbuilt_compute = signature_dispatches(sig) + && super::pso_async::is_pending(raw_pso) + && !super::pso_async::is_spared(raw_pso) + && super::real::is_console_compute(raw_pso); if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { return super::pso_async::need_by_submit(raw_pso); } @@ -3457,7 +3460,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // call with that pair is invalid (debug layer 953, "the currently set Root Signature // doesn't match the currently set Pipeline State Object"; a retail title's world then // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. - if super::pso_async::is_pending(raw_pso) { + if super::pso_async::bound_unbuilt(raw_pso, pso) { note_skipped_indirect(this, sig); count(DRAWS_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -4358,7 +4361,10 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, s.inline_guard = None; s.pso }); - if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) { + if super::pso_async::is_pending(pso) + && !super::pso_async::is_spared(pso) + && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) + { return super::pso_async::need_by_submit(pso); } let pso = super::pso_async::resolve_wait(pso); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 283581e80a..3b4667a184 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -3104,8 +3104,9 @@ unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { Some(next_pc) } -/// Cap on deferred compute segments per frame when per-frame wait windows are active so a cold -/// burst of thousands of unbuilt dispatches never exhausts command-list memory (`#2581`). +/// Cap on deferred compute segments per frame so a cold burst of unbuilt dispatches never +/// exhausts command-list memory (`#2581`). Once reached, subsequent `!spared` producer dispatches +/// fall through to `pso_async::resolve_wait` and wait inline instead of being dropped. const MAX_DEFERRED_PER_FRAME: u32 = 16; struct FrameDeferCap { @@ -3118,20 +3119,23 @@ impl FrameDeferCap { Self { frame: 0, count: 0 } } - fn has_slot(&mut self, frame: u64, limit: u32) -> bool { + fn try_reserve(&mut self, frame: u64, limit: u32) -> bool { if frame > self.frame { self.frame = frame; self.count = 0; } - self.count < limit + if frame == self.frame && self.count >= limit { + return false; + } + if frame == self.frame { + self.count = self.count.saturating_add(1); + } + true } - fn record(&mut self, frame: u64) { - if frame > self.frame { - self.frame = frame; - self.count = 1; - } else if frame == self.frame { - self.count = self.count.saturating_add(1); + fn release(&mut self, frame: u64) { + if frame == self.frame { + self.count = self.count.saturating_sub(1); } } } @@ -3140,23 +3144,19 @@ static FRAME_DEFER_CAP: Mutex = Mutex::new(FrameDeferCap::new()); /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { - // With bounded per-PSO waits (`XCL_PSO_WAIT_MS`, #2581) or an exhausted per-frame compute - // wait window (`XCL_PSO_FRAME_BUDGET_MS`), record at once instead of allocating a segment - // per unbuilt dispatch (thousands of deferred segments can OOM command lists -> 0x887a0001). - if super::pso_async::waits_bounded() || super::pso_async::compute_frame_budget_spent() { + // With bounded per-PSO waits (`XCL_PSO_WAIT_MS`, #2581), record at once instead of allocating + // a segment per unbuilt dispatch. + if super::pso_async::waits_bounded() { return false; } - let bounded_frame = super::pso_async::frame_budget_enabled(); - let frame = if bounded_frame { super::present::presents() } else { 0 }; - if bounded_frame && !FRAME_DEFER_CAP.lock().unwrap().has_slot(frame, MAX_DEFERRED_PER_FRAME) { + let frame = super::present::presents(); + if !FRAME_DEFER_CAP.lock().unwrap().try_reserve(frame, MAX_DEFERRED_PER_FRAME) { return false; } if split(list, Some(what)).is_none() { + FRAME_DEFER_CAP.lock().unwrap().release(frame); return false; } - if bounded_frame { - FRAME_DEFER_CAP.lock().unwrap().record(frame); - } static N: AtomicU64 = AtomicU64::new(0); let n = N.fetch_add(1, Ordering::Relaxed) + 1; if n <= 4 || n.is_power_of_two() { @@ -3173,18 +3173,20 @@ mod defer_cap_tests { fn frame_defer_cap_bounds_segments_per_frame_and_resets_on_new_frame() { let mut cap = FrameDeferCap::new(); for _ in 0..3 { - assert!(cap.has_slot(1, 3)); - cap.record(1); - } - assert!(!cap.has_slot(1, 3), "must stop deferring once per-frame segment cap is reached"); - assert!(cap.has_slot(2, 3), "advancing frame must reset the per-frame defer cap"); - cap.record(2); + assert!(cap.try_reserve(1, 3)); + } + assert!(!cap.try_reserve(1, 3), "must stop deferring once per-frame segment cap is reached"); + // Releasing a failed split frees the slot atomically on the same frame. + cap.release(1); + assert!(cap.try_reserve(1, 3)); + assert!(!cap.try_reserve(1, 3)); + // Advancing frame resets the per-frame defer cap. + assert!(cap.try_reserve(2, 3), "advancing frame must reset the per-frame defer cap"); // Stale lower frame must not disturb frame 2's count. - cap.record(1); - assert!(cap.has_slot(2, 3)); - cap.record(2); - cap.record(2); - assert!(!cap.has_slot(2, 3)); + cap.release(1); + assert!(cap.try_reserve(2, 3)); + assert!(cap.try_reserve(2, 3)); + assert!(!cap.try_reserve(2, 3)); } } diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 39b3535cdc..b63360d839 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -8,9 +8,12 @@ //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +/// Sentinel for `Pending::waited_frame`: no frame has spent graphics wait budget on this PSO yet. +const UNWAITED: u64 = u64::MAX; + struct Pending { /// the build, until a worker – or a bind that cannot wait for the queue – takes it job: Mutex>, @@ -38,6 +41,9 @@ struct Pending { /// heavyweight RT/compute shader (`>= 512 KiB` DXIL / BVH traversal): lower worker queue /// priority than normal/MS PSOs so world-entry draws finish ahead of slow RT compiles deprioritized: std::sync::atomic::AtomicBool, + /// first frame that waited on this graphics PSO within `XCL_PSO_FRAME_BUDGET_MS` (`UNWAITED` + /// if never waited yet): later frames skip waiting while workers finish compiling it + waited_frame: AtomicU64, demand: Mutex, } @@ -337,6 +343,16 @@ impl PsoQueue { fn pop(&self) -> Work { let mut g = self.items.lock().unwrap(); loop { + if let Some(pos) = g.iter().position(|item| { + item.pending.as_ref().is_some_and(|p| { + p.compute + && !p.spared.load(Ordering::Acquire) + && !p.bvh_traversal.load(Ordering::Acquire) + && p.demand.lock().unwrap().wanted + }) + }) { + return g.remove(pos).unwrap().work; + } if let Some(pos) = g.iter().position(|item| item.pending.as_ref().is_some_and(|p| p.demand.lock().unwrap().wanted)) { return g.remove(pos).unwrap().work; } @@ -579,6 +595,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, flag spared: std::sync::atomic::AtomicBool::new(flags.spared), bvh_traversal: std::sync::atomic::AtomicBool::new(flags.bvh_traversal), deprioritized: std::sync::atomic::AtomicBool::new(flags.deprioritized), + waited_frame: AtomicU64::new(UNWAITED), demand: Default::default(), }); PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); @@ -1371,6 +1388,7 @@ pub fn submit_gated(standin: usize, driver: usize) { spared: std::sync::atomic::AtomicBool::new(false), bvh_traversal: std::sync::atomic::AtomicBool::new(true), deprioritized: std::sync::atomic::AtomicBool::new(true), + waited_frame: AtomicU64::new(UNWAITED), demand: Default::default(), }); PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p); @@ -1406,8 +1424,12 @@ pub fn resolve(pso: usize) -> usize { } } -/// `resolve`, waiting for a pipeline still being built within the per-frame wait window -/// (`XCL_PSO_FRAME_BUDGET_MS`, default 12 s per kind per frame). +/// `resolve`, waiting for a pipeline still being built: +/// - non-spared memory-writing producer compute pipelines always wait (never skipped by +/// `XCL_PSO_FRAME_BUDGET_MS`, because skipping a producer compute dispatch corrupts title memory); +/// - graphics pipelines wait within the per-frame graphics window (`XCL_PSO_FRAME_BUDGET_MS`, +/// default 12 s) and stamp `waited_frame` so a slow graphics PSO stalls at most one frame; +/// - `spared` (`image_only`) and `bvh_traversal` compute pipelines use `resolve_spared`. pub fn resolve_wait(pso: usize) -> usize { resolve_wait_for(pso, wait_budget()) } @@ -1484,8 +1506,8 @@ fn set_submit_wait_for_test(most: Option) { SUBMIT_WAIT_FOR_TEST.with(|b| b.set(most)); } -/// `resolve_wait`, waiting at most `budget` per pipeline (and at most the remaining -/// per-frame window for this pipeline's kind). +/// `resolve_wait`, waiting at most `budget` per pipeline (and for graphics pipelines, at most +/// the remaining per-frame graphics window). fn resolve_wait_for(pso: usize, budget: Option) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); @@ -1493,15 +1515,19 @@ fn resolve_wait_for(pso: usize, budget: Option) -> usize { return resolve_spared(&p, pso); } let frame = super::present::presents(); - resolve_wait_in(&p, pso, budget, frame_budget(), frame, kind_frame_budget(p.compute)) + // Memory-writing producer compute PSOs (`!spared && !bvh_traversal`) are never skipped by the + // per-frame graphics wait window: skipping a producer dispatch leaves title memory/tables + // uninitialized and causes Window-3 pointer corruption several frames later. + let fcap = if p.compute { None } else { frame_budget() }; + resolve_wait_in(&p, pso, budget, fcap, frame, &FRAME_BUDGET_GFX) } -/// Default per-frame pipeline wait window (`12 s`) for each kind (`graphics`, `compute`). +/// Default per-frame graphics pipeline wait window (`12 s`). const DEFAULT_FRAME_BUDGET_MS: u64 = 12_000; /// Parses `XCL_PSO_FRAME_BUDGET_MS`: unset/empty defaults to `12_000 ms` (`12 s`), `0` skips /// waiting immediately, `off` / `none` disables the per-frame cap, and a positive integer sets -/// the per-frame window in milliseconds for each kind (`graphics`, `compute`). +/// the per-frame graphics wait window in milliseconds. fn parse_frame_budget(val: Option<&str>) -> Option { let Some(raw) = val.map(str::trim).filter(|s| !s.is_empty()) else { return Some(std::time::Duration::from_millis(DEFAULT_FRAME_BUDGET_MS)); @@ -1521,17 +1547,13 @@ fn frame_budget() -> Option { } static FRAME_BUDGET_GFX: Mutex = Mutex::new(FrameWaitBudget::new()); -static FRAME_BUDGET_CS: Mutex = Mutex::new(FrameWaitBudget::new()); - -fn kind_frame_budget(compute: bool) -> &'static Mutex { - if compute { &FRAME_BUDGET_CS } else { &FRAME_BUDGET_GFX } -} /// Waits for `p` within both an optional per-PSO cap (`budget`) and an optional per-frame -/// per-kind window (`frame_cap` tracked in `frame_state` for `frame`). Builds run on +/// graphics window (`frame_cap` tracked in `frame_state` for `frame`). Builds run on /// `xcl-pso-*` workers (prioritized as `wanted`) so the caller always wakes when the window -/// expires; once a frame's window is spent, remaining unready draws/dispatches return the -/// stand-in for this frame and retry with a fresh window on the next frame. +/// expires; once a graphics PSO has spent budget on a frame (`waited_frame`), subsequent frames +/// skip waiting on it immediately until workers complete it. Non-spared memory-writing producer +/// compute pipelines pass `frame_cap = None` and always wait to completion. fn resolve_wait_in( p: &Arc, pso: usize, @@ -1596,10 +1618,17 @@ fn resolve_wait_in( } return built(p); }; + // A slow graphics PSO that already got its wait turn on an earlier frame keeps compiling in + // the background without re-burning `frame`'s graphics wait window every frame. + let prev_waited = p.waited_frame.load(Ordering::Acquire); + if prev_waited != UNWAITED && prev_waited != frame { + return p.stand(pso); + } let rem = frame_state.lock().unwrap().begin_wait(frame, fcap, std::time::Instant::now()); if rem.is_zero() { return p.stand(pso); } + let _ = p.waited_frame.compare_exchange(UNWAITED, frame, Ordering::AcqRel, Ordering::Acquire); let (wait_for, per_pso_binding) = match budget { Some(b) if b <= rem => (b, true), _ => (rem, false), @@ -1625,15 +1654,11 @@ fn resolve_wait_in( ); } } else { - // Do NOT set `p.late` so the pipeline is retried with a fresh window on the next frame. static N_GFX: AtomicUsize = AtomicUsize::new(0); - static N_CS: AtomicUsize = AtomicUsize::new(0); - let counter = if p.compute { &N_CS } else { &N_GFX }; - let n = counter.fetch_add(1, Ordering::Relaxed); + let n = N_GFX.fetch_add(1, Ordering::Relaxed); if n < 16 || n.is_power_of_two() { - let kind = if p.compute { "compute" } else { "graphics" }; crate::xlog_warn!( - "D3D12.X: {kind} pipeline wait window ({} ms) spent on frame {frame}: skipping remaining unready {kind} work until next frame ({} so far)", + "D3D12.X: graphics pipeline wait window ({} ms) spent on frame {frame}: skipping remaining unready graphics work until next frame ({} so far)", fcap.as_millis(), n + 1 ); @@ -1674,17 +1699,10 @@ pub fn waits_bounded() -> bool { wait_budget().is_some() } -/// Whether per-frame pipeline wait windows (`XCL_PSO_FRAME_BUDGET_MS`) are active. -pub fn frame_budget_enabled() -> bool { - frame_budget().is_some() -} - -/// Whether the current frame's compute pipeline wait window has already been spent. -pub fn compute_frame_budget_spent() -> bool { - frame_budget().is_some_and(|cap| { - let frame = super::present::presents(); - FRAME_BUDGET_CS.lock().unwrap().remaining_at(frame, cap, std::time::Instant::now()).is_zero() - }) +/// `pso` is a stand-in marked `spared` (`image_only`) or `bvh_traversal`, whose dispatches do +/// not block or defer to submit segments. +pub fn is_spared(pso: usize) -> bool { + entry(pso).is_some_and(|p| p.spared.load(Ordering::Acquire) || p.bvh_traversal.load(Ordering::Acquire)) } /// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a @@ -1806,6 +1824,7 @@ impl FrameWaitBudget { self.spent.saturating_add(in_flight) } + #[cfg(test)] fn remaining_at(&mut self, frame: u64, cap: std::time::Duration, now: std::time::Instant) -> std::time::Duration { self.advance(frame, now); cap.saturating_sub(self.effective_spent(now)) @@ -1947,6 +1966,19 @@ pub fn is_stand_in(pso: usize) -> bool { entry(pso).is_some_and(|p| p.real.load(Ordering::Acquire) == 0) } +/// Whether `bound` (returned by `resolve*` for `standin`) is an unbuilt stand-in rather than the +/// real pipeline — remains `true` even if a worker finishes building `standin` between `resolve*` +/// and the caller's check (`#2598`), while returning `false` if the build failed (`real == 0`). +pub fn bound_unbuilt(standin: usize, bound: usize) -> bool { + entry(standin).is_some_and(|p| { + if !*p.done.lock().unwrap() { + return true; + } + let real = p.real.load(Ordering::Acquire); + real != 0 && bound != real + }) +} + /// One of the title's threads is about to wait for `pso`. pub fn want(pso: usize) { if let Some(p) = entry(pso) { @@ -1991,10 +2023,49 @@ mod pso_queue_tests { spared: Default::default(), bvh_traversal: Default::default(), deprioritized: std::sync::atomic::AtomicBool::new(deprioritized), + waited_frame: AtomicU64::new(UNWAITED), + demand: Mutex::new(Demand { wanted, by_submit: false, preload_thread: 0 }), + }) + } + + fn dummy_compute_pending(wanted: bool, spared: bool) -> Arc { + Arc::new(Pending { + job: Mutex::new(None), + sent: std::sync::atomic::AtomicBool::new(true), + real: AtomicUsize::new(0), + driver: AtomicUsize::new(0), + done: Mutex::new(false), + cv: Condvar::new(), + compute: true, + key: 0, + used: Default::default(), + orphan: Default::default(), + late: Default::default(), + spared: std::sync::atomic::AtomicBool::new(spared), + bvh_traversal: Default::default(), + deprioritized: Default::default(), + waited_frame: AtomicU64::new(UNWAITED), demand: Mutex::new(Demand { wanted, by_submit: false, preload_thread: 0 }), }) } + #[test] + fn pso_queue_prioritizes_wanted_producer_compute_over_wanted_graphics() { + let q = PsoQueue::new(); + let order = Arc::new(Mutex::new(Vec::<&'static str>::new())); + let push = |name: &'static str, p: Arc| { + let o = order.clone(); + q.push(Box::new(move || o.lock().unwrap().push(name)), Some(p)); + }; + push("gfx_wanted", dummy_pending(true, false)); + push("cs_spared_wanted", dummy_compute_pending(true, true)); + push("cs_producer_wanted", dummy_compute_pending(true, false)); + for _ in 0..3 { + (q.pop())(); + } + assert_eq!(*order.lock().unwrap(), ["cs_producer_wanted", "gfx_wanted", "cs_spared_wanted"]); + } + #[test] fn pso_queue_dequeues_wanted_then_normal_ahead_of_deprioritized() { let q = PsoQueue::new(); @@ -2123,14 +2194,13 @@ mod pso_queue_tests { } #[test] - fn frame_budget_waits_within_window_skips_rest_of_frame_and_retries_next_frame() { + fn frame_budget_waits_within_window_stamps_slow_gfx_once_and_never_skips_producer_compute() { use std::time::{Duration, Instant}; let gfx_budget = Mutex::new(FrameWaitBudget::new()); - let cs_budget = Mutex::new(FrameWaitBudget::new()); let cap = Some(Duration::from_millis(60)); - let (g_fast, g_slow1, g_slow2, c_fast) = (0x7E57_F001usize, 0x7E57_F002usize, 0x7E57_F003usize, 0x7E57_F004usize); + let (g_fast, g_slow1, g_slow2, c_prod) = (0x7E57_F001usize, 0x7E57_F002usize, 0x7E57_F003usize, 0x7E57_F004usize); let (go_tx, go_rx) = mpsc::channel::<()>(); let (go2_tx, go2_rx) = mpsc::channel::<()>(); submit_lazy(g_fast, false, Box::new(|| { @@ -2145,36 +2215,53 @@ mod pso_queue_tests { let _ = go2_rx.recv(); 0xF103 }), 0); - submit_lazy(c_fast, true, Box::new(|| { - std::thread::sleep(Duration::from_millis(10)); + submit_lazy(c_prod, true, Box::new(|| { + std::thread::sleep(Duration::from_millis(90)); 0xF104 }), 0); + heavy_compute(c_prod); // Frame 1: fast graphics PSO finishes within the 60 ms graphics window. let p_fast = entry(g_fast).unwrap(); assert_eq!(resolve_wait_in(&p_fast, g_fast, None, cap, 1, &gfx_budget), 0xF101); - // Frame 1: slow graphics PSO spends the rest of frame 1's graphics window and skips. + // Frame 1: slow graphics PSO spends the rest of frame 1's graphics window, stamps + // waited_frame = 1, and skips. let p_slow1 = entry(g_slow1).unwrap(); assert_eq!(resolve_wait_in(&p_slow1, g_slow1, None, cap, 1, &gfx_budget), g_slow1); - // Frame 1: second unready graphics PSO sees 0 ms remaining and skips immediately. + // Frame 1: second unready graphics PSO sees 0 ms remaining and skips immediately WITHOUT + // stamping waited_frame (so it gets a fresh turn on Frame 2). let p_slow2 = entry(g_slow2).unwrap(); let t0 = Instant::now(); assert_eq!(resolve_wait_in(&p_slow2, g_slow2, None, cap, 1, &gfx_budget), g_slow2); assert!(t0.elapsed() < Duration::from_millis(25), "spent frame budget must skip immediately ({:?})", t0.elapsed()); + assert_eq!(p_slow2.waited_frame.load(Ordering::Acquire), UNWAITED); - // Frame 1: compute has its own independent per-frame window and completes cleanly! - let p_cs = entry(c_fast).unwrap(); - assert_eq!(resolve_wait_in(&p_cs, c_fast, None, cap, 1, &cs_budget), 0xF104); + // Non-spared producer compute PSO (`!spared`, longer than 60 ms graphics window) MUST wait + // to completion instead of being skipped! + assert!(!is_spared(c_prod)); + assert_eq!(resolve_wait_for(c_prod, None), 0xF104); - // Release both slow graphics workers and retry on Frame 2: both resolve (not stuck `late`)! - go_tx.send(()).unwrap(); + // Frame 2: g_slow1 already spent its wait turn on Frame 1 -> skips immediately without + // burning Frame 2's graphics budget! + let t1 = Instant::now(); + assert_eq!(resolve_wait_in(&p_slow1, g_slow1, None, Some(Duration::from_secs(5)), 2, &gfx_budget), g_slow1); + assert!(t1.elapsed() < Duration::from_millis(25), "already-waited slow graphics PSO must skip immediately on next frame ({:?})", t1.elapsed()); + + // Frame 2: g_slow2 never waited yet, so it gets Frame 2's full window and resolves once ready! go2_tx.send(()).unwrap(); - assert_eq!(resolve_wait_in(&p_slow1, g_slow1, None, Some(Duration::from_secs(5)), 2, &gfx_budget), 0xF102); assert_eq!(resolve_wait_in(&p_slow2, g_slow2, None, Some(Duration::from_secs(5)), 2, &gfx_budget), 0xF103); - for s in [g_fast, g_slow1, g_slow2, c_fast] { + // Once g_slow1's worker completes, it immediately resolves to its real pipeline! + go_tx.send(()).unwrap(); + let wait_start = Instant::now(); + while is_pending(g_slow1) && wait_start.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!(resolve_wait_in(&p_slow1, g_slow1, None, Some(Duration::from_secs(5)), 3, &gfx_budget), 0xF102); + + for s in [g_fast, g_slow1, g_slow2, c_prod] { let _ = released(s); } } @@ -2207,4 +2294,37 @@ mod pso_queue_tests { b.end_wait(1468, cap, t0 + Duration::from_secs(14), false); assert_eq!(b.remaining_at(1468, cap, t0 + Duration::from_secs(14)), Duration::from_secs(11)); } + + #[test] + fn bound_unbuilt_detects_standin_even_after_worker_finishes() { + let (standin_ok, standin_fail, native) = (0x7E57_9801usize, 0x7E57_9802usize, 0x7E57_9803usize); + let (tx, rx) = mpsc::channel::<()>(); + submit_lazy(standin_ok, false, Box::new(move || { + let _ = rx.recv(); + 0x9801 + }), 0); + // While pending: bound stand-in is unbuilt. + assert!(bound_unbuilt(standin_ok, standin_ok)); + // Finish the build after the caller already got `standin_ok`. + let _ = resolve(standin_ok); + tx.send(()).unwrap(); + let t0 = std::time::Instant::now(); + while is_pending(standin_ok) && t0.elapsed() < std::time::Duration::from_secs(5) { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!(!is_pending(standin_ok)); + assert!(bound_unbuilt(standin_ok, standin_ok), "stale stand-in must still read unbuilt after worker completes"); + assert!(!bound_unbuilt(standin_ok, 0x9801), "resolved real pipeline must not read unbuilt"); + + // Failed build (real == 0) is not treated as an in-flight unbuilt stand-in. + submit(standin_fail, true, Box::new(|| 0)); + assert_eq!(resolve_wait(standin_fail), standin_fail); + assert!(!bound_unbuilt(standin_fail, standin_fail)); + + // Unknown / native PC pipeline is never unbuilt. + assert!(!bound_unbuilt(native, native)); + + let _ = released(standin_ok); + let _ = released(standin_fail); + } } From b5c0275f82689e38f0c37e121ef37407e4cbb3e2 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:36:47 +0100 Subject: [PATCH 174/258] D3D12.X: scan table CBVs, fallback UNKNOWN view formats, and support 8x4 grids in ambient Wave 16e diagnostics showed both TemporalResolve ([320, 360, 1]) and ReflectionHistory ([0, 0, 0]) reached ambient::after_compute_dispatch with tables=3, view_heap=0x4c610000, indices=16 (meaning zero root constants/CBVs and all bindings inside the two Param::Table descriptor tables). Fix all four remaining lookup gaps: - Decode CBV V# buffer descriptors (w3 >> 28 < 8, dst_sel 0xFAC) in slots 0..32 of every bound Param::Table and scan their readable constant-buffer bytes (up to 2048 B) for bindless view-heap indices. - Probe direct image T# descriptors across slots 0..64 of every bound Param::Table (previously capped at 0..16). - Resolve DXGI_FORMAT_UNKNOWN (0) in dev_create_uav_x and dev_create_srv_x to rd.Format.0 before calling ambient::note_descriptor so views that inherit the resource format are never dropped. - Score Wave32 [8, 4, 1] and [4, 2, 1] dispatch grids alongside [8, 8, 1] and lower min_w/min_h to (groups/2).max(64) so [320, 360, 1] matches 2560x1440, 1280x720, and half-res probe targets. Verified with cargo check -p xcl --lib and hle::d3d12x::ambient::tests (5 passed, 0 failed). Assisted-by: Antigravity (Gemini 4 Neon High) --- crates/xcl/src/hle/d3d12x/ambient.rs | 215 ++++++++++++++++++--------- crates/xcl/src/hle/d3d12x/real.rs | 6 +- 2 files changed, 152 insertions(+), 69 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index fcc3aac59f..07c0f00943 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -347,14 +347,20 @@ fn score_dispatch_target(rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; } let max_w = groups[0].saturating_mul(64); let max_h = groups[1].saturating_mul(64); - let min_w = groups[0].saturating_mul(2); - let min_h = groups[1].saturating_mul(2); + let min_w = (groups[0] / 2).max(64); + let min_h = (groups[1] / 2).max(64); if w < min_w || w > max_w || h < min_h || h > max_h { return None; } - let ideal_w = groups[0].saturating_mul(8) as i64; - let ideal_h = groups[1].saturating_mul(8) as i64; - Some((w as i64 - ideal_w).unsigned_abs() + (h as i64 - ideal_h).unsigned_abs()) + // Console compute shaders commonly use [8, 8, 1] or Wave32 [8, 4, 1] thread groups + // (e.g. [320, 360, 1] -> 2560x1440 at 8x4 or 1280x720 at 4x2); score by closest fit. + let d88 = (w as i64 - groups[0].saturating_mul(8) as i64).unsigned_abs() + + (h as i64 - groups[1].saturating_mul(8) as i64).unsigned_abs(); + let d84 = (w as i64 - groups[0].saturating_mul(8) as i64).unsigned_abs() + + (h as i64 - groups[1].saturating_mul(4) as i64).unsigned_abs(); + let d42 = (w as i64 - groups[0].saturating_mul(4) as i64).unsigned_abs() + + (h as i64 - groups[1].saturating_mul(2) as i64).unsigned_abs(); + Some(d88.min(d84).min(d42)) } #[cfg(test)] @@ -840,17 +846,59 @@ pub(super) unsafe fn after_draw(list: *mut c_void, pso_resolved: usize) { /// (covers >1.24M-slot console shader-visible view heaps). const MAX_SLOT_INDEX: u32 = 2_000_000; +/// Decode a CBV / buffer `V#` descriptor (`gpu::desc::cbv_words` / `buffer_words`) into +/// `(va, byte_len)` if it is a readable buffer descriptor (`w3 >> 28 < 8` and dst_sel `0xFAC`). +fn decode_cbv_vsharp(w: [u32; 4]) -> Option<(usize, usize)> { + if (w[3] >> 28) >= 8 || (w[3] & 0xFFF) != 0xFAC { + return None; + } + let va = (w[0] as u64 | ((w[1] as u64 & 0xFFFF) << 32)) as usize; + if va == 0 { + return None; + } + let stride = ((w[1] >> 16) & 0x3FFF) as usize; + let records = w[2] as usize; + let bytes = if stride == 0 { records } else { records.saturating_mul(stride) }; + (bytes >= 4).then_some((va, bytes.min(2048))) +} + +/// Scan up to `max_bytes` (capped at 2048 B) of readable constant-buffer memory at `va` in +/// 256-byte chunks and feed candidate bindless descriptor indices `< MAX_SLOT_INDEX` into `push_idx`. +unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMut(u32)) { + if va == 0 || max_bytes < 4 { + return; + } + let total = max_bytes.min(2048); + let mut off = 0usize; + while off < total { + let chunk = (total - off).min(256); + let base = va + off; + if !crate::gpu::shader::readable(base, chunk) { + break; + } + let words = chunk / 4; + for k in 0..words { + let v = ((base + 4 * k) as *const u32).read_unaligned(); + if v != 0 { + push_idx(v); + } + } + off += chunk; + } +} + /// Inspect a compute dispatch's bound descriptor tables, SM 6.6 directly-indexed view heap -/// (`view_heap_base`), and root constants/CBVs to locate its output screen-space float UAV +/// (`view_heap_base`), and root/table CBVs to locate its output screen-space float UAV /// (and optional depth SRV for crease AO). unsafe fn find_dispatch_views( layout: &Layout, args: &[u8], groups: [u32; 3], view_heap_base: u32, -) -> (Option<(usize, i32, u32, u32)>, Option<(usize, i32, u32, u32)>, usize, usize) { - let Some(u) = crate::gpu::uma::get() else { return (None, None, 0, 0) }; +) -> (Option<(usize, i32, u32, u32)>, Option<(usize, i32, u32, u32)>, usize, usize, usize) { + let Some(u) = crate::gpu::uma::get() else { return (None, None, 0, 0, 0) }; let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); + let mut param_tables: Vec = Vec::new(); let mut tables: Vec = Vec::new(); let mut indices: Vec = Vec::new(); let mut seen: HashSet = HashSet::new(); @@ -875,83 +923,104 @@ unsafe fn find_dispatch_views( let lo = word(at as usize).unwrap_or(0) as u64; let hi = word(at as usize + 4).unwrap_or(0) as u64; let va = (lo | (hi << 32)) as usize; - if va != 0 { - // Scan up to 2048 bytes (512 u32s) in 256-byte readable chunks so bindless - // pass/frame CBVs larger than 256 bytes are covered safely. - for chunk in 0..8usize { - let base = va + chunk * 256; - if !crate::gpu::shader::readable(base, 256) { - break; - } - for k in 0..64usize { - let v = ((base + 4 * k) as *const u32).read_unaligned(); - if v != 0 { - push_idx(v); - } - } - } - } + scan_cbv_indices(va, 2048, &mut push_idx); } Param::Table { at } => { if let Some(t) = word(at as usize) { - if t != 0 && !tables.contains(&t) { - tables.push(t); + if t != 0 { + if !param_tables.contains(&t) { + param_tables.push(t); + } + if !tables.contains(&t) { + tables.push(t); + } } } } } } - // Also probe direct table slots 0..16 in case descriptors are bound directly without bindless indices. - for k in 0..16u32 { - push_idx(k); + + // Scan direct slots `0..64` of every bound `Param::Table` for BOTH direct image T# descriptors + // and CBV V# descriptors (whose buffer contents often carry bindless indices into `view_heap`). + let mut table_cbvs = 0usize; + let mut direct_addrs: Vec = Vec::new(); + for &t in ¶m_tables { + for k in 0..64usize { + let Some(off) = (t as usize).checked_add(32 * k) else { break }; + let Some(addr) = u.base().checked_add(off) else { break }; + if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { + break; + } + let w = [ + (addr as *const u32).read_unaligned(), + ((addr + 4) as *const u32).read_unaligned(), + ((addr + 8) as *const u32).read_unaligned(), + ((addr + 12) as *const u32).read_unaligned(), + ]; + if (w[3] >> 28) >= 8 { + direct_addrs.push(addr); + } else if k < 32 { + if let Some((cbv_va, cbv_len)) = decode_cbv_vsharp(w) { + table_cbvs += 1; + scan_cbv_indices(cbv_va, cbv_len, &mut push_idx); + } + } + } } let mut uav_hit: Option<(u64, usize, i32, u32, u32)> = None; let mut depth_hit: Option<(usize, i32, u32, u32)> = None; let slots = VIEW_SLOTS.read().unwrap(); - let Some(vs) = slots.as_ref() else { return (None, None, tables.len(), indices.len()) }; + let Some(vs) = slots.as_ref() else { return (None, None, tables.len(), indices.len(), table_cbvs) }; + let mut check_slot = |addr: usize| { + if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { + return; + } + let w0 = (addr as *const u32).read_unaligned(); + let w3 = ((addr + 12) as *const u32).read_unaligned(); + // Image T# descriptors have type >= 8 in bits [31:28] of word 3. + if (w3 >> 28) < 8 { + return; + } + let Some(&ve) = vs + .by_addr + .get(&addr) + .or_else(|| (w0 != 0).then(|| vs.by_idx.get(&w0)).flatten()) + else { + return; + }; + let ptr = ve.res as *mut c_void; + let Some(res) = ID3D12Resource::from_raw_borrowed(&ptr) else { return }; + let rd = res.GetDesc(); + if ve.is_uav { + if let Some(score) = score_dispatch_target(&rd, ve.fmt, groups) { + if uav_hit.is_none_or(|(best, _, _, _, _)| score < best) { + uav_hit = Some((score, ve.res, ve.fmt, rd.Width as u32, rd.Height)); + } + } + } else if depth_hit.is_none() + && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D + && rd.DepthOrArraySize == 1 + && rd.SampleDesc.Count == 1 + && rd.Width >= 64 + && rd.Height >= 64 + { + depth_hit = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height)); + } + }; + + for addr in direct_addrs { + check_slot(addr); + } for &t in &tables { for &idx in &indices { let Some(off) = (t as usize).checked_add(32usize.saturating_mul(idx as usize)) else { continue }; let Some(addr) = u.base().checked_add(off) else { continue }; - if !u.contains(addr) || !crate::gpu::shader::readable(addr, 16) { - continue; - } - let w0 = (addr as *const u32).read_unaligned(); - let w3 = ((addr + 12) as *const u32).read_unaligned(); - // Image T# descriptors have type >= 8 in bits [31:28] of word 3. - if (w3 >> 28) < 8 { - continue; - } - let Some(&ve) = vs - .by_addr - .get(&addr) - .or_else(|| (w0 != 0).then(|| vs.by_idx.get(&w0)).flatten()) - else { - continue; - }; - let ptr = ve.res as *mut c_void; - let Some(res) = ID3D12Resource::from_raw_borrowed(&ptr) else { continue }; - let rd = res.GetDesc(); - if ve.is_uav { - if let Some(score) = score_dispatch_target(&rd, ve.fmt, groups) { - if uav_hit.is_none_or(|(best, _, _, _, _)| score < best) { - uav_hit = Some((score, ve.res, ve.fmt, rd.Width as u32, rd.Height)); - } - } - } else if depth_hit.is_none() - && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D - && rd.DepthOrArraySize == 1 - && rd.SampleDesc.Count == 1 - && rd.Width >= 64 - && rd.Height >= 64 - { - depth_hit = Some((ve.res, ve.fmt, rd.Width as u32, rd.Height)); - } + check_slot(addr); } } - (uav_hit.map(|(_, r, f, w, h)| (r, f, w, h)), depth_hit, tables.len(), indices.len()) + (uav_hit.map(|(_, r, f, w, h)| (r, f, w, h)), depth_hit, tables.len(), indices.len(), table_cbvs) } /// Called right after a translated compute dispatch completes: when RT is gated off and a sky @@ -992,12 +1061,12 @@ pub(super) unsafe fn after_compute_dispatch( return; } - let (uav_opt, depth_opt, n_tables, n_indices) = find_dispatch_views(layout, args, groups, view_heap_base); + let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(layout, args, groups, view_heap_base); let Some((uav_res, uav_fmt, w, h)) = uav_opt else { static MISS: AtomicU64 = AtomicU64::new(0); if MISS.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_info!( - "D3D12.X: ambient: {role:?} ({groups:?}) found no matching UAV (tables={n_tables}, view_heap={view_heap_base:#x}, indices={n_indices})" + "D3D12.X: ambient: {role:?} ({groups:?}) found no matching UAV (tables={n_tables}, view_heap={view_heap_base:#x}, table_cbvs={n_cbvs}, indices={n_indices})" ); } return; @@ -1176,6 +1245,18 @@ mod tests { let arr = D3D12_RESOURCE_DESC { DepthOrArraySize: 4, ..typeless }; assert!(score_dispatch_target(&arr, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [240, 135, 1]).is_none()); + // [320, 360, 1] Wave32 [8, 4, 1] / half-res probe grid matches 2560x1440, 1280x720, and 640x360. + let qhd = D3D12_RESOURCE_DESC { Width: 2560, Height: 1440, ..typeless }; + let half = D3D12_RESOURCE_DESC { Width: 640, Height: 360, ..typeless }; + assert_eq!(score_dispatch_target(&qhd, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [320, 360, 1]), Some(0)); + assert!(score_dispatch_target(&half, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [320, 360, 1]).is_some()); + + // CBV V# in a descriptor table decodes back to its buffer VA and byte size. + let cbv = crate::gpu::desc::cbv_words(0x7_1234_5600, 512); + assert_eq!(decode_cbv_vsharp(cbv), Some((0x7_1234_5600, 512))); + let img = crate::gpu::desc::xcl_image_for_view(42, 0, crate::gpu::desc::ImageType::D2, 64, 64, 1, 1); + assert_eq!(decode_cbv_vsharp([img[0], img[1], img[2], img[3]]), None); + // Two distinct CPU-only heap slots (`global_index == 0`) at different addresses must not collide // before being copied to the shader-visible heap. let cpu_slot_a = 0x7F00_0000_0020usize; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 49a93efc04..1783fe8c10 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2908,7 +2908,8 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; return super::console_heap::write(&slot, &buffer_view(res as usize, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, true)); } - super::ambient::note_descriptor(slot.at, amb_idx, res as usize, desc.as_ref().map_or(rdesc.Format.0, |v| v.Format.0), rdesc.Format.0, false); + let amb_fmt = desc.as_ref().map(|v| v.Format.0).filter(|&f| f != 0).unwrap_or(rdesc.Format.0); + super::ambient::note_descriptor(slot.at, amb_idx, res as usize, amb_fmt, rdesc.Format.0, false); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { Some(t) => super::console_heap::write(&slot, &t), None => { @@ -3343,7 +3344,8 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } None => (rd.Format, resource_dim_to_view(&rd), rd.DepthOrArraySize as u32, 0), }; - super::ambient::note_descriptor(slot.at, amb_idx, uav_res as usize, format.0, rd.Format.0, true); + let amb_fmt = if format.0 != 0 { format.0 } else { rd.Format.0 }; + super::ambient::note_descriptor(slot.at, amb_idx, uav_res as usize, amb_fmt, rd.Format.0, true); let Some((fmt, ty, w, h, d, _)) = view_shape(r, format, dim, array, 1) else { note_buffer_view(); return super::console_heap::write(&slot, &[0; 8]); From 7706e0f8188621a9df3a4d910e099cddf5bc3c05 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:52:35 +0300 Subject: [PATCH 175/258] Shaders: include HEAP_FLAT in offline precompile runtime_windows --- crates/xcl/src/shaders.rs | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 239fda9448..2b186d10e9 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -906,6 +906,14 @@ fn parse_args(args: &[String]) -> Result { Ok(opts) } +fn runtime_windows_flags(windows: u32, heap_windows: bool, heap_flat: bool) -> u32 { + if windows > 1 && heap_windows { + windows | recomp::HEAP_WINDOWS | if heap_flat { recomp::HEAP_FLAT } else { 0 } + } else { + windows + } +} + pub fn run(path: &Path, args: &[String]) -> i32 { let opts = match parse_args(args) { Ok(o) => o, @@ -915,11 +923,8 @@ pub fn run(path: &Path, args: &[String]) -> i32 { } }; // the runtime's memory windows: from the descriptor heap with `XCL_HEAP_WINDOWS=1` - // (`pso::mem_windows`), as `--precompile` - let runtime_windows = || { - let windows = opts.windows; - if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows } - }; + // and flat access with `XCL_HEAP_FLAT=1` (`pso::mem_windows`), as `--precompile` + let runtime_windows = || runtime_windows_flags(opts.windows, recomp::pso::heap_windows(), recomp::pso::heap_flat()); let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -1092,8 +1097,10 @@ fn export_hlsl(input: &Input, dir: &Path, min_kb: usize, count: usize, windows: println!( "{written} program(s) written to {} (split wave64: {split}, {} windows{}, {failures} failure(s))", dir.display(), - windows & !recomp::HEAP_WINDOWS, - if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" } + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), + if windows & recomp::HEAP_WINDOWS != 0 { + if windows & recomp::HEAP_FLAT != 0 { " from the descriptor heap (flat)" } else { " from the descriptor heap" } + } else { "" } ); if written == wanted { 0 } else { eprintln!("xcl shaders --export-hlsl: requested {wanted} program(s), wrote {written}"); @@ -1727,8 +1734,10 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), - windows & !recomp::HEAP_WINDOWS, - if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), + if windows & recomp::HEAP_WINDOWS != 0 { + if windows & recomp::HEAP_FLAT != 0 { " from the descriptor heap (flat)" } else { " from the descriptor heap" } + } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); std::thread::scope(|s| { @@ -2221,6 +2230,16 @@ mod tests { sample(5, &[compute]) } + #[test] + fn offline_runtime_windows_includes_heap_flat_when_enabled() { + assert_eq!(runtime_windows_flags(1, true, true), 1); + assert_eq!(runtime_windows_flags(4, false, true), 4); + assert_eq!(runtime_windows_flags(4, true, false), 4 | recomp::HEAP_WINDOWS); + let flat = runtime_windows_flags(4, true, true); + assert_eq!(flat, 4 | recomp::HEAP_WINDOWS | recomp::HEAP_FLAT); + assert_eq!(flat & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), 4); + } + #[test] fn record_hash_is_strict_hex() { assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB); From 4ab2a42186c00ac7f3be815cedcc3d1afd46316f Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:37:54 +0300 Subject: [PATCH 176/258] Shaders: omit (flat) label from --export-hlsl summary --- crates/xcl/src/shaders.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 2b186d10e9..eacbe52019 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1098,9 +1098,7 @@ fn export_hlsl(input: &Input, dir: &Path, min_kb: usize, count: usize, windows: "{written} program(s) written to {} (split wave64: {split}, {} windows{}, {failures} failure(s))", dir.display(), windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), - if windows & recomp::HEAP_WINDOWS != 0 { - if windows & recomp::HEAP_FLAT != 0 { " from the descriptor heap (flat)" } else { " from the descriptor heap" } - } else { "" } + if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" } ); if written == wanted { 0 } else { eprintln!("xcl shaders --export-hlsl: requested {wanted} program(s), wrote {written}"); From 24c41644b388eadce0cbb9fb74569fcac12b718f Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:52:02 +0300 Subject: [PATCH 177/258] D3D12.X: drop overflow pooled resources and preludes outside bind locks --- crates/xcl/src/hle/d3d12x/bind.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 6d2bc04f0b..2b35aca413 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -331,15 +331,24 @@ fn hold_prelude_until_reset(allocator: usize, entry: Option) { } pub(super) fn release_allocator_res(allocator: usize) { + // Drop overflow COM objects outside the pool locks: releasing an adopted prelude + // `ID3D12CommandAllocator` (or resource) re-enters `real::alloc_release` -> + // `console_list::allocator_reset` -> `release_allocator_res`, which would self-deadlock if + // `FREE_PRELUDE` / `FREE_RES` / `FREE_IO` were still held. + let mut drop_res = Vec::new(); if let Some(bufs) = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { let mut free = FREE_RES.lock().unwrap(); for b in bufs { let held: u64 = free.iter().map(|f| f.1).sum(); if pool_keeps(free.len(), held, b.1) { free.push(b); + } else { + drop_res.push(b); } } } + drop(drop_res); + let mut drop_io = Vec::new(); if let Some(blocks) = ALLOC_IO.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { let mut free = FREE_IO.lock().unwrap(); for mut b in blocks { @@ -347,17 +356,24 @@ pub(super) fn release_allocator_res(allocator: usize) { let held: u64 = free.iter().map(|f| f.cap).sum(); if io_pool_keeps(held, b.cap) { free.push(b); + } else { + drop_io.push(b); } } } + drop(drop_io); + let mut drop_prelude = Vec::new(); if let Some(entries) = ALLOC_PRELUDE.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { let mut free = FREE_PRELUDE.lock().unwrap(); for e in entries { if free.len() < FREE_PRELUDE_CAP { free.push(e); + } else { + drop_prelude.push(e); } } } + drop(drop_prelude); } /// Whether `FREE_RES`, holding `count` buffers of `held` bytes, keeps one of `bytes` more. From 80d0ead082cb64883fee1a9324ff1e61c0b99855 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:12:01 +0300 Subject: [PATCH 178/258] D3D12.X: split bind pool lock scopes and add overflow drop-outside-lock test --- crates/xcl/src/hle/d3d12x/bind.rs | 103 +++++++++++++++++++----------- 1 file changed, 67 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 2b35aca413..33eba4b359 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -330,50 +330,50 @@ fn hold_prelude_until_reset(allocator: usize, entry: Option) { ALLOC_PRELUDE.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().push(entry); } -pub(super) fn release_allocator_res(allocator: usize) { - // Drop overflow COM objects outside the pool locks: releasing an adopted prelude - // `ID3D12CommandAllocator` (or resource) re-enters `real::alloc_release` -> - // `console_list::allocator_reset` -> `release_allocator_res`, which would self-deadlock if - // `FREE_PRELUDE` / `FREE_RES` / `FREE_IO` were still held. - let mut drop_res = Vec::new(); - if let Some(bufs) = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { - let mut free = FREE_RES.lock().unwrap(); - for b in bufs { - let held: u64 = free.iter().map(|f| f.1).sum(); - if pool_keeps(free.len(), held, b.1) { - free.push(b); +/// Return `items` into `free` whenever `keep(&pool, &item)` holds, dropping overflow items +/// *after* releasing `free` so COM `Release` hooks that re-enter `release_allocator_res` +/// cannot self-deadlock on the pool mutex. +fn recycle_into_pool(free: &Mutex>, items: Vec, mut keep: impl FnMut(&[T], &T) -> bool) { + let mut overflow = Vec::new(); + { + let mut pool = free.lock().unwrap(); + for item in items { + if keep(&pool, &item) { + pool.push(item); } else { - drop_res.push(b); + overflow.push(item); } } } - drop(drop_res); - let mut drop_io = Vec::new(); - if let Some(blocks) = ALLOC_IO.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { - let mut free = FREE_IO.lock().unwrap(); - for mut b in blocks { + drop(overflow); +} + +pub(super) fn release_allocator_res(allocator: usize) { + // Bind each removed entry before locking the free pool (avoiding nested `ALLOC_* -> FREE_*` + // lock holding from `if let` temporary lifetimes) and drop overflow COM objects outside both + // locks so re-entrant `real::alloc_release` -> `console_list::allocator_reset` -> + // `release_allocator_res` cannot self-deadlock. + let bufs = ALLOC_RES.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + if let Some(bufs) = bufs { + recycle_into_pool(&FREE_RES, bufs, |pool, b| { + let held: u64 = pool.iter().map(|f| f.1).sum(); + pool_keeps(pool.len(), held, b.1) + }); + } + let blocks = ALLOC_IO.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + if let Some(mut blocks) = blocks { + for b in &mut blocks { b.used = 0; - let held: u64 = free.iter().map(|f| f.cap).sum(); - if io_pool_keeps(held, b.cap) { - free.push(b); - } else { - drop_io.push(b); - } } + recycle_into_pool(&FREE_IO, blocks, |pool, b| { + let held: u64 = pool.iter().map(|f| f.cap).sum(); + io_pool_keeps(held, b.cap) + }); } - drop(drop_io); - let mut drop_prelude = Vec::new(); - if let Some(entries) = ALLOC_PRELUDE.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)) { - let mut free = FREE_PRELUDE.lock().unwrap(); - for e in entries { - if free.len() < FREE_PRELUDE_CAP { - free.push(e); - } else { - drop_prelude.push(e); - } - } + let entries = ALLOC_PRELUDE.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + if let Some(entries) = entries { + recycle_into_pool(&FREE_PRELUDE, entries, |pool, _| pool.len() < FREE_PRELUDE_CAP); } - drop(drop_prelude); } /// Whether `FREE_RES`, holding `count` buffers of `held` bytes, keeps one of `bytes` more. @@ -6714,4 +6714,35 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) note_draw_signature(sig, None); assert_eq!(draw_sig_of(sig), None); } + + #[test] + fn recycle_into_pool_drops_overflow_outside_pool_lock() { + struct ReentrantDrop { + pool: Arc>>, + drops_outside_lock: Arc, + } + impl Drop for ReentrantDrop { + fn drop(&mut self) { + // Mirrors COM Release re-entering `release_allocator_res`: fails immediately if + // overflow drops while `pool` is still locked (would self-deadlock on `.lock()`). + let _guard = self + .pool + .try_lock() + .expect("overflow item must be dropped after releasing the pool mutex"); + self.drops_outside_lock.fetch_add(1, Ordering::SeqCst); + } + } + + let pool: Arc>> = Arc::new(Mutex::new(Vec::new())); + let drops = Arc::new(AtomicU64::new(0)); + let items: Vec<_> = (0..4) + .map(|_| ReentrantDrop { pool: Arc::clone(&pool), drops_outside_lock: Arc::clone(&drops) }) + .collect(); + recycle_into_pool(&pool, items, |p, _| p.len() < 2); + assert_eq!(drops.load(Ordering::SeqCst), 2, "both overflow items must drop outside the lock"); + assert_eq!(pool.lock().unwrap().len(), 2); + let kept = std::mem::take(&mut *pool.lock().unwrap()); + drop(kept); + assert_eq!(drops.load(Ordering::SeqCst), 4); + } } From 09e23b089a20c8f7b2cae529149b38160649fdf6 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:37:55 +0300 Subject: [PATCH 179/258] D3D12.X: gate 128-256 KiB compute driver compiles in MEDIUM_COMPILES --- crates/xcl/src/hle/d3d12x/real.rs | 77 ++++++++++++++++++++++++++++--- 1 file changed, 71 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 1783fe8c10..2ec03a58f4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -4824,15 +4824,28 @@ impl Drop for WantedWaiterGuard { } } +/// Compute DXIL compiles (`128 KiB..256 KiB`, e.g. per-instruction fallback CS) take tens of +/// seconds and >1 GiB each in `amdxc64` when 16 `xcl-pso*` workers compile them simultaneously; +/// gate them into `MEDIUM_COMPILES` while keeping `huge_pso_bytes()` (default `256 KiB`) for +/// graphics pipelines and title-thread deferral. +const MEDIUM_COMPUTE_DRIVER_COMPILE: usize = 128 << 10; const LARGE_DRIVER_COMPILE: usize = 512 << 10; static MEDIUM_COMPILES: Slots = Slots { n: Mutex::new(0), wanted_waiters: AtomicUsize::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Medium }; static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), wanted_waiters: AtomicUsize::new(0), cv: std::sync::Condvar::new(), limit: SlotLimit::Big }; /// True giant DXIL shaders (`>= 900 KiB`, e.g. >1 MiB RT/compute shaders that can take >60-140s /// in the driver compiler) get their own dedicated 1-slot lane so they never starve `MEDIUM_COMPILES` -/// (`256-512 KiB`) or `BIG_COMPILES` (`512-900 KiB`). +/// (`128-512 KiB`) or `BIG_COMPILES` (`512-900 KiB`). const GIANT_DRIVER_COMPILE: usize = 900 << 10; static GIANT_COMPILES: Slots = Slots::fixed(1, 1); +fn driver_compile_gate_bytes(kind: &str, huge_bytes: usize) -> usize { + if kind == "compute" || kind == "compute retry" { + huge_bytes.min(MEDIUM_COMPUTE_DRIVER_COMPILE) + } else { + huge_bytes + } +} + fn is_preload_worker() -> bool { std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso-pre-")) } @@ -4873,13 +4886,15 @@ fn pso_trace() -> bool { /// `[SHADER]` lines and `xcl shaders --measure-pso`) and whether a driver blob was supplied. /// Also returns the time spent in the driver alone (not waiting for a slot). fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Option<(u64, bool)>, build: impl FnOnce() -> R) -> (R, std::time::Duration) { - let huge = gate && bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let huge_bytes = huge_pso_bytes(); + let gate_bytes = driver_compile_gate_bytes(kind, huge_bytes); + let gated = gate && bytes >= gate_bytes && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); - let _slot = huge.then(|| big_compile_turn_with(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted, is_preload_worker())); + let _slot = gated.then(|| big_compile_turn_with(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted, is_preload_worker())); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; - let log = pso_trace() || bytes >= huge_pso_bytes(); + let log = pso_trace() || bytes >= huge_bytes; if log { let record = record.map_or_else(String::new, |(hash, cached)| { format!(", record {hash:016x}, driver blob {}", if cached { "supplied" } else { "absent" }) @@ -4890,7 +4905,7 @@ fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Op let r = build(); let took = started.elapsed(); if log { - crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_pso_bytes(), huge, waited)); + crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_bytes || gated, gated, waited)); } (r, took) } @@ -5201,8 +5216,11 @@ mod big_compile_tests { assert_eq!(*S.n.lock().unwrap(), 0); } + static GLOBAL_SLOTS_TEST_LOCK: Mutex<()> = Mutex::new(()); + #[test] fn small_and_title_thread_compiles_bypass_the_gate() { + let _lock = GLOBAL_SLOTS_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); // every slot taken: a small compile on a worker, and a huge one on an unnamed (title) // thread, both go on at once // (all three lanes: a huge compile of any size would block on a gate it should bypass) @@ -5222,6 +5240,51 @@ mod big_compile_tests { drop(held); } + #[test] + fn medium_compute_gate_threshold_applies_only_to_compute() { + assert_eq!(driver_compile_gate_bytes("compute", 256 << 10), MEDIUM_COMPUTE_DRIVER_COMPILE); + assert_eq!(driver_compile_gate_bytes("compute retry", 256 << 10), MEDIUM_COMPUTE_DRIVER_COMPILE); + assert_eq!(driver_compile_gate_bytes("compute", 64 << 10), 64 << 10); + assert_eq!(driver_compile_gate_bytes("graphics", 256 << 10), 256 << 10); + assert_eq!(driver_compile_gate_bytes("test", 256 << 10), 256 << 10); + assert!(std::ptr::eq(compile_slots(128 << 10), &MEDIUM_COMPILES)); + assert!(std::ptr::eq(compile_slots(179 << 10), &MEDIUM_COMPILES)); + assert!(std::ptr::eq(compile_slots(217 << 10), &MEDIUM_COMPILES)); + } + + #[test] + fn medium_compute_worker_compiles_are_gated_in_medium_lane() { + let _lock = GLOBAL_SLOTS_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let held: Vec<_> = (0..medium_pso_concurrency()) + .map(|_| big_compile_turn(&MEDIUM_COMPILES, || true, || false)) + .collect(); + + // < 128 KiB compute, cached (`gate = false`) 180 KiB compute, and title-thread 180 KiB + // compute all bypass `MEDIUM_COMPILES` immediately. + let small_cs = std::thread::Builder::new() + .name("xcl-pso-test".into()) + .spawn(|| driver_compile("compute", MEDIUM_COMPUTE_DRIVER_COMPILE - 1, true, || 11)) + .unwrap(); + let cached_cs = std::thread::Builder::new() + .name("xcl-pso-test".into()) + .spawn(|| driver_compile("compute", 180 << 10, false, || 12)) + .unwrap(); + let title_cs = std::thread::spawn(|| driver_compile("compute", 180 << 10, true, || 13)); + assert_eq!(small_cs.join().unwrap(), 11); + assert_eq!(cached_cs.join().unwrap(), 12); + assert_eq!(title_cs.join().unwrap(), 13); + + // A cold 180 KiB compute compile on an `xcl-pso*` worker waits until a `MEDIUM_COMPILES` slot frees. + let gated_cs = std::thread::Builder::new() + .name("xcl-pso-test".into()) + .spawn(|| driver_compile("compute", 180 << 10, true, || 14)) + .unwrap(); + std::thread::sleep(Duration::from_millis(120)); + assert!(!gated_cs.is_finished(), "cold 180 KiB compute worker compile must wait on MEDIUM_COMPILES"); + drop(held); + assert_eq!(gated_cs.join().unwrap(), 14); + } + #[test] fn headroom_is_the_3_gb_floor_until_512_times_the_dxil_exceeds_it() { // the class from huge_pso_bytes() up to 6 MiB of DXIL: the floor, unchanged @@ -7231,7 +7294,9 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: } // At least one half missed the pipeline library: take one turn for the cold compile(s). let bytes = stream.shader_bytes() + tp.cs.len(); - let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let huge_bytes = huge_pso_bytes(); + let gate = (bytes >= huge_bytes || tp.cs.len() >= driver_compile_gate_bytes("compute", huge_bytes)) + && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); let _slot = gate.then(|| big_compile_turn_with(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted, is_preload_worker())); if gate { From 1fe2c8f076f861c92ddbc905087e94b7d3b1d066 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:37:55 +0300 Subject: [PATCH 180/258] D3D12.X: resolve GPU-view CBVs, accept typeless sky domes, and add pre-sky fallback in ambient --- crates/xcl/src/hle/d3d12x/ambient.rs | 76 +++++++++++++++++++++++----- crates/xcl/src/hle/d3d12x/real.rs | 6 +-- 2 files changed, 65 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 07c0f00943..9bcec5e1b3 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -154,6 +154,12 @@ pub(super) fn note_graphics_pso(pso: usize, ps: Option<&[u8]>) { } } +/// Whether a compute shader blob belongs to a pass handled by stand-in ambient lighting +/// (`CS_ScreenProbes_TemporalResolve` / `CS_UpdateHistory`). +pub(super) fn is_ambient_compute(blob: &[u8]) -> bool { + classify_cs(blob).is_some() +} + pub(super) fn note_compute_pso(pso: usize, cs: &[u8]) { if pso == 0 || !enabled() { return; @@ -316,7 +322,7 @@ fn is_sky_dome_target(rd: &D3D12_RESOURCE_DESC) -> bool { rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && rd.Width == 128 && rd.Height == 128 - && rd.Format == DXGI_FORMAT_R16G16B16A16_FLOAT + && matches!(rd.Format, DXGI_FORMAT_R16G16B16A16_FLOAT | DXGI_FORMAT_R16G16B16A16_TYPELESS) && rd.SampleDesc.Count == 1 } @@ -489,13 +495,13 @@ cbuffer C : register(b0) { uint depth_h; uint has_depth; float ao_strength; - float _p6; - float _p7; + uint sky_ready; + float fallback_level; }; [numthreads(8, 8, 1)] void main(uint3 tid : SV_DispatchThreadID) { if (tid.x >= width || tid.y >= height) return; - float3 amb = sky_level[0].rgb; + float3 amb = (sky_ready != 0) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); float ao = 1.0; if (has_depth != 0 && depth_w > 0 && depth_h > 0) { int2 dc = int2( @@ -862,9 +868,25 @@ fn decode_cbv_vsharp(w: [u32; 4]) -> Option<(usize, usize)> { (bytes >= 4).then_some((va, bytes.min(2048))) } +/// Resolve a GPU VA to a CPU-readable host address when it lives in a `PAGE_NOACCESS` GPU mirror view. +fn resolve_cbv_va(va: usize) -> usize { + if va == 0 { + return 0; + } + if crate::gpu::shader::readable(va, 4) { + return va; + } + match crate::hle::kernelx::mirrors::mapped_source(va) { + Some(Some(backing)) => backing, + Some(None) => 0, + None => crate::hle::kernelx::mirrors::source(va).unwrap_or(va), + } +} + /// Scan up to `max_bytes` (capped at 2048 B) of readable constant-buffer memory at `va` in /// 256-byte chunks and feed candidate bindless descriptor indices `< MAX_SLOT_INDEX` into `push_idx`. unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMut(u32)) { + let va = resolve_cbv_va(va); if va == 0 || max_bytes < 4 { return; } @@ -959,11 +981,9 @@ unsafe fn find_dispatch_views( ]; if (w[3] >> 28) >= 8 { direct_addrs.push(addr); - } else if k < 32 { - if let Some((cbv_va, cbv_len)) = decode_cbv_vsharp(w) { - table_cbvs += 1; - scan_cbv_indices(cbv_va, cbv_len, &mut push_idx); - } + } else if let Some((cbv_va, cbv_len)) = decode_cbv_vsharp(w) { + table_cbvs += 1; + scan_cbv_indices(cbv_va, cbv_len, &mut push_idx); } } } @@ -1043,9 +1063,19 @@ pub(super) unsafe fn after_compute_dispatch( } let ty = list_x::tracked_list_type(list); if !matches!(ty, Some(D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE)) { + static BAD_TY: AtomicU64 = AtomicU64::new(0); + if BAD_TY.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_info!("D3D12.X: ambient: {role:?} skipped on unsupported list type {ty:?}"); + } return; } - let Some(layout) = layout else { return }; + let Some(layout) = layout else { + static NO_LAYOUT: AtomicU64 = AtomicU64::new(0); + if NO_LAYOUT.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_info!("D3D12.X: ambient: {role:?} skipped (no compute root-signature layout)"); + } + return; + }; let Some(cl) = ID3D12GraphicsCommandList::from_raw_borrowed(&list) else { return }; let mut dev: Option = None; if cl.GetDevice(&mut dev).is_err() { @@ -1053,12 +1083,18 @@ pub(super) unsafe fn after_compute_dispatch( } let Some(dev) = dev else { return }; let Some(ad) = get_device(&dev) else { return }; - if !ad.sky_ready.load(Ordering::Acquire) { + let sky_ready = ad.sky_ready.load(Ordering::Acquire); + if !sky_ready { static NO_SKY: AtomicU64 = AtomicU64::new(0); if NO_SKY.fetch_add(1, Ordering::Relaxed) < 2 { - crate::xlog_info!("D3D12.X: ambient: {role:?} dispatched ({groups:?}) before sky dome capture"); + crate::xlog_info!( + "D3D12.X: ambient: {role:?} dispatched ({groups:?}) before sky dome capture ({})", + if role == PassRole::TemporalResolve { "using least fallback" } else { "skipping" } + ); + } + if role != PassRole::TemporalResolve { + return; } - return; } let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(layout, args, groups, view_heap_base); @@ -1072,6 +1108,10 @@ pub(super) unsafe fn after_compute_dispatch( return; }; if role == PassRole::ReflectionHistory && !typed_uav_load_supported(&dev, DXGI_FORMAT(uav_fmt)) { + static NO_LOAD: AtomicU64 = AtomicU64::new(0); + if NO_LOAD.fetch_add(1, Ordering::Relaxed) < 2 { + crate::xlog_info!("D3D12.X: ambient: {role:?} skipped (typed UAV load unsupported for fmt {uav_fmt})"); + } return; } @@ -1127,7 +1167,7 @@ pub(super) unsafe fn after_compute_dispatch( let (pso, consts) = match role { PassRole::TemporalResolve => ( ad.fill_pso.as_raw(), - [w, h, depth_w, depth_h, has_depth, cfg.ao.to_bits(), 0, 0], + [w, h, depth_w, depth_h, has_depth, cfg.ao.to_bits(), sky_ready as u32, cfg.least.to_bits()], ), PassRole::ReflectionHistory => ( ad.reflect_pso.as_raw(), @@ -1187,6 +1227,10 @@ mod tests { }; assert!(is_sky_dome_target(&rd)); + // Typeless 128x128 RGBA16 render targets are copy-compatible with R16G16B16A16_FLOAT. + rd.Format = DXGI_FORMAT_R16G16B16A16_TYPELESS; + assert!(is_sky_dome_target(&rd)); + // Must ignore the brighter 128x128 R11G11B10_FLOAT pass to prevent frame flicker. rd.Format = DXGI_FORMAT_R11G11B10_FLOAT; assert!(!is_sky_dome_target(&rd)); @@ -1194,6 +1238,10 @@ mod tests { rd.Format = DXGI_FORMAT_R16G16B16A16_FLOAT; rd.Width = 256; assert!(!is_sky_dome_target(&rd)); + + assert!(is_ambient_compute(b"ILDN\0CS_ScreenProbes_TemporalResolve\0")); + assert!(is_ambient_compute(b"ILDN\0CS_UpdateHistory_16\0")); + assert!(!is_ambient_compute(b"ILDN\0CS_CullInstances\0")); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2ec03a58f4..d0d42ecef9 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6825,6 +6825,7 @@ unsafe fn go_background( let heavy_compute = compute && super::pso_async::async_heavy_compute() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::compute_code_len(b).is_some_and(|n| n >= crate::gpu::effects::HEAVY_CODE))); + let ambient_cs = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| super::ambient::is_ambient_compute(b))); if compute { if let OwnedDesc::Compute(_, b) = &owned { if let Some(cs) = b.first() { @@ -6845,10 +6846,9 @@ unsafe fn go_background( }); // Only pure image-writing compute shaders (zero buffer/global/GDS writes) or BVH RT traversal // shaders may ever be spared/skipped while building. Heavy producer compute shaders that write - // memory are deprioritized onto gated workers (`deprioritized`) and excluded from speculative - // low-priority preloading, but NEVER skipped when bound. + // memory and stand-in ambient resolve/reflection passes are never skipped when bound. let flags = super::pso_async::SubmitFlags { - spared: image_only || (heavy_compute && big_image_only), + spared: !ambient_cs && (image_only || (heavy_compute && big_image_only)), bvh_traversal: bvh_trav && bvh_gate_enabled(), deprioritized: heavy_compute || (bvh_trav && bvh_gate_enabled()), }; From 2d1a8703e4ccd78252542fd43c82165bebcf94e7 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:31:53 +0300 Subject: [PATCH 181/258] D3D12.X: resolve CBV mirror chunks independently across 64 KiB page boundaries --- crates/xcl/src/hle/d3d12x/ambient.rs | 68 +++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 9bcec5e1b3..4c4949aa44 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -883,19 +883,27 @@ fn resolve_cbv_va(va: usize) -> usize { } } -/// Scan up to `max_bytes` (capped at 2048 B) of readable constant-buffer memory at `va` in -/// 256-byte chunks and feed candidate bindless descriptor indices `< MAX_SLOT_INDEX` into `push_idx`. -unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMut(u32)) { - let va = resolve_cbv_va(va); +/// Scan up to `max_bytes` (capped at 2048 B) of readable constant-buffer memory at `va`, +/// resolving each chunk (capped at 256 B and never crossing a 64 KiB mirror page boundary) +/// through `resolve`, and feed candidate bindless descriptor indices `< MAX_SLOT_INDEX` into `push_idx`. +unsafe fn scan_cbv_indices_with( + va: usize, + max_bytes: usize, + mut resolve: impl FnMut(usize) -> usize, + push_idx: &mut impl FnMut(u32), +) { if va == 0 || max_bytes < 4 { return; } + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; let total = max_bytes.min(2048); let mut off = 0usize; while off < total { - let chunk = (total - off).min(256); - let base = va + off; - if !crate::gpu::shader::readable(base, chunk) { + let Some(cur_va) = va.checked_add(off) else { break }; + let to_page_end = PAGE - (cur_va & (PAGE - 1)); + let chunk = (total - off).min(256).min(to_page_end); + let base = resolve(cur_va); + if base == 0 || !crate::gpu::shader::readable(base, chunk) { break; } let words = chunk / 4; @@ -909,6 +917,12 @@ unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMu } } +/// Scan up to `max_bytes` (capped at 2048 B) of readable constant-buffer memory at `va` in +/// page-bounded chunks and feed candidate bindless descriptor indices `< MAX_SLOT_INDEX` into `push_idx`. +unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMut(u32)) { + scan_cbv_indices_with(va, max_bytes, resolve_cbv_va, push_idx); +} + /// Inspect a compute dispatch's bound descriptor tables, SM 6.6 directly-indexed view heap /// (`view_heap_base`), and root/table CBVs to locate its output screen-space float UAV /// (and optional depth SRV for crease AO). @@ -1324,4 +1338,44 @@ mod tests { forget_resource(res_a); note_descriptor(cpu_slot_b, 0, 0, 0, 0, false); } + + #[test] + fn scan_cbv_indices_resolves_each_64k_mirror_page_independently() { + const PAGE: usize = crate::hle::kernelx::mirrors::PAGE; + // Backing page 0 sits right before a readable decoy slice; backing page 1 is separate. + let mut backing0_and_decoy = vec![0u32; 128]; + backing0_and_decoy[0] = 101_001; // sentinel in page 0 (last 256 B of GPU page 0) + backing0_and_decoy[64] = 999_999; // decoy immediately after backing 0 (must NEVER be read) + let mut backing1 = vec![0u32; 64]; + backing1[0] = 202_002; // sentinel in page 1 (first 256 B of GPU page 1) + + let gpu_page0 = 0x5000_0000usize; + let gpu_page1 = gpu_page0 + PAGE; + let cbv_start = gpu_page0 + (PAGE - 256); // 0xff00: spans 256 B on page 0 + 256 B on page 1 + let p0_base = backing0_and_decoy.as_ptr() as usize; + let p1_base = backing1.as_ptr() as usize; + + let mut seen = Vec::new(); + unsafe { + scan_cbv_indices_with( + cbv_start, + 512, + |va| { + if va >= gpu_page0 && va < gpu_page1 { + p0_base + (va - cbv_start) + } else if va >= gpu_page1 && va < gpu_page1 + 256 { + p1_base + (va - gpu_page1) + } else { + 0 + } + }, + &mut |v| seen.push(v), + ); + } + assert!(seen.contains(&101_001), "first 64 KiB page sentinel must be read"); + assert!(seen.contains(&202_002), "second 64 KiB page sentinel must be resolved independently"); + assert!(!seen.contains(&999_999), "readable decoy past backing 0 must never be read across 64 KiB boundary"); + assert_eq!(resolve_cbv_va(0), 0); + assert_eq!(resolve_cbv_va(p1_base), p1_base); + } } From 85523e468beff6dd8003fffc768f08346eca3705 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:19:01 +0300 Subject: [PATCH 182/258] D3D12.X: clear rebind state, raise scratch pool cap, name UAV scratch for DRED, and bind active backing on CreateCommandList --- crates/xcl/src/hle/d3d12x/bind.rs | 71 ++++++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/device_x.rs | 5 +- 2 files changed, 68 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 33eba4b359..db51faf6ef 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -378,7 +378,7 @@ pub(super) fn release_allocator_res(allocator: usize) { /// Whether `FREE_RES`, holding `count` buffers of `held` bytes, keeps one of `bytes` more. fn pool_keeps(count: usize, held: u64, bytes: u64) -> bool { - count < 16 && held + bytes <= FREE_RES_CAP + count < 256 && held + bytes <= FREE_RES_CAP } /// Whether `FREE_IO`, holding `held` bytes of VRAM `io` slabs, keeps one of `bytes` more. @@ -668,7 +668,16 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { let backing = backing_allocator(list, allocator); let (old, blocks, res_bufs, io_blocks, prelude) = with(list, |s| { + s.heaps_ensured = false; + s.pc_abi_gfx = AbiBound::default(); + s.pc_abi_cs = AbiBound::default(); + s.arg_order_clean = false; + s.inline_guard = None; + s.prelude_built = None; if s.allocator == backing { + for sl in &mut s.scratch { + sl.state = D3D12_RESOURCE_STATE_COMMON; + } return (0, Vec::new(), Vec::new(), Vec::new(), None); } let old = std::mem::replace(&mut s.allocator, backing); @@ -682,8 +691,6 @@ pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { s.prelude_scales.clear(); s.prelude_draws.clear(); let prelude = s.prelude_owned.take(); - s.prelude_built = None; - s.inline_guard = None; s.dummy_res_va = 0; s.dummy_table_p = 0; s.io_cache_gfx = None; @@ -754,8 +761,12 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.io_cache_cs = None; s.io_cache_tp_cs = None; s.io_cache_tp_ms = None; + let mut res_bufs = std::mem::take(&mut s.res_retired); + if let Some(b) = s.res_buf.take() { + res_bufs.push(b); + } let io_blocks = std::mem::take(&mut s.io_blocks); - (old, std::mem::take(&mut s.uma), std::mem::take(&mut s.res_retired), io_blocks, prelude) + (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude) }); console_list::hold_until_reset(old, blocks); hold_res_until_reset(old, res_bufs); @@ -1190,7 +1201,11 @@ unsafe fn default_uav_buffer(dev: &ID3D12Device, bytes: u64, what: &str) -> Resu &mut res, ) .map_err(|e| format!("{what} ({bytes:#x} B): {e}"))?; - res.ok_or_else(|| format!("null {what}")) + let res = res.ok_or_else(|| format!("null {what}"))?; + if super::real::dred_on() { + super::real::name_resource(res.as_raw(), what); + } + Ok(res) } /// Groups of a two-pass dispatch that have a record: one record a group in `cap_bytes` of @@ -5717,7 +5732,8 @@ void main(uint t : SV_GroupIndex) { assert!(pool_keeps(0, 0, 128 << 20)); assert!(pool_keeps(1, 128 << 20, 128 << 20)); assert!(!pool_keeps(2, 256 << 20, 4 << 20)); - assert!(!pool_keeps(16, 0, 1 << 20)); + assert!(pool_keeps(16, 0, 1 << 20)); + assert!(!pool_keeps(256, 0, 1 << 20)); } /// A second queue for two-pass draws is told from the first one. @@ -6486,6 +6502,49 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) super::super::alloc_pool::forget_list(list as usize); } + #[test] + fn rebind_allocator_clears_per_recording_state_even_on_same_backing() { + let list = 0x7E57_9101usize as *mut c_void; + let title_alloc = 0x7E57_9110usize; + let backing_a = 0x7E57_9120usize; + let backing_b = 0x7E57_9130usize; + super::super::alloc_pool::created_on(list as usize, backing_a, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + reset(list, title_alloc, 0); + with(list, |s| { + s.heaps_ensured = true; + s.arg_order_clean = true; + s.pc_abi_gfx.rs = 0x1111; + s.pc_abi_cs.rs = 0x2222; + s.scratch[0].state = GUARDED_ARGS_STATE; + s.uma.push(0xBEEF_1000); + }); + + // Same backing: per-recording native-reset state must clear while UMA blocks stay pinned. + rebind_allocator(list, title_alloc); + with(list, |s| { + assert_eq!(s.allocator, backing_a); + assert!(!s.heaps_ensured); + assert!(!s.arg_order_clean); + assert_eq!(s.pc_abi_gfx.rs, 0); + assert_eq!(s.pc_abi_cs.rs, 0); + assert_eq!(s.scratch[0].state, D3D12_RESOURCE_STATE_COMMON); + assert_eq!(s.uma, vec![0xBEEF_1000]); + }); + + // Rotated backing: per-recording state clears and prior UMA blocks retire onto `backing_a`. + with(list, |s| s.heaps_ensured = true); + super::super::alloc_pool::created_on(list as usize, backing_b, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + rebind_allocator(list, title_alloc); + with(list, |s| { + assert_eq!(s.allocator, backing_b); + assert!(!s.heaps_ensured); + assert!(s.uma.is_empty()); + }); + assert_eq!(console_list::take_pending_for_test(backing_a), vec![0xBEEF_1000]); + forget(list); + super::super::alloc_pool::forget_list(list as usize); + } + /// `SCALE_ARGS_HEAP_HLSL` and `GUARD_ARGS_HEAP_HLSL` read from a real 4 GiB reserved buffer's /// raw UAV in `ResourceDescriptorHeap`: a mapped tile produces exact scaled/folded outputs, /// while an unmapped NULL tile reads safely as zero with no GPU page fault. diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 20f4ad06e6..ea740c1b97 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -97,9 +97,10 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) } else { let resolved_pso = super::pso_async::resolve(pso); - let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_pso, riid, ppv); + let pc_alloc = super::alloc_pool::current(alloc); + let hr = real::dev_create_command_list(this, node, ty, pc_alloc, resolved_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - super::list_x::on_create(*ppv, alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::on_create(*ppv, pc_alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); super::dred::reset(*ppv); if pso != 0 { super::dred::mark_pipeline(*ppv, pso, resolved_pso); From fbe1e2d266ec6a22d829e673f6cba20edc8839a5 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:33:00 +0300 Subject: [PATCH 183/258] D3D12.X: retire preludes on same-backing rebind and keep title allocator in ListState on create --- crates/xcl/src/hle/d3d12x/bind.rs | 14 +++++++------- crates/xcl/src/hle/d3d12x/device_x.rs | 2 +- crates/xcl/src/hle/d3d12x/list_x.rs | 14 ++++++++++++-- 3 files changed, 20 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index db51faf6ef..684302b84b 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -673,24 +673,24 @@ pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { s.pc_abi_cs = AbiBound::default(); s.arg_order_clean = false; s.inline_guard = None; + s.prelude_scratch = Default::default(); + s.prelude_bufs.clear(); + s.prelude_guards.clear(); + s.prelude_scales.clear(); + s.prelude_draws.clear(); + let prelude = s.prelude_owned.take(); s.prelude_built = None; if s.allocator == backing { for sl in &mut s.scratch { sl.state = D3D12_RESOURCE_STATE_COMMON; } - return (0, Vec::new(), Vec::new(), Vec::new(), None); + return (backing, Vec::new(), Vec::new(), Vec::new(), prelude); } let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.scratch = Default::default(); s.scratch_next = 0; s.scratch_taken = 0; - s.prelude_scratch = Default::default(); - s.prelude_bufs.clear(); - s.prelude_guards.clear(); - s.prelude_scales.clear(); - s.prelude_draws.clear(); - let prelude = s.prelude_owned.take(); s.dummy_res_va = 0; s.dummy_table_p = 0; s.io_cache_gfx = None; diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index ea740c1b97..aecb7276a3 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -100,7 +100,7 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: let pc_alloc = super::alloc_pool::current(alloc); let hr = real::dev_create_command_list(this, node, ty, pc_alloc, resolved_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - super::list_x::on_create(*ppv, pc_alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::on_create_with_backing(*ppv, alloc, pc_alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); super::dred::reset(*ppv); if pso != 0 { super::dred::mark_pipeline(*ppv, pso, resolved_pso); diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 3b4667a184..0908ec1fa3 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1152,6 +1152,16 @@ unsafe fn try_native_depth_bias(list: *mut c_void, bias: DepthBias) -> bool { /// # Safety /// `list` must be null or a valid `ID3D12GraphicsCommandList` COM pointer. pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { + on_create_with_backing(list, alloc, alloc, pso, ty); +} + +pub unsafe fn on_create_with_backing( + list: *mut c_void, + title_alloc: usize, + pc_alloc: usize, + pso: usize, + ty: D3D12_COMMAND_LIST_TYPE, +) { if list.is_null() { return; } @@ -1174,8 +1184,8 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); } } - super::alloc_pool::created_on(key, alloc, ty.0); - m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); + super::alloc_pool::created_on(key, pc_alloc, ty.0); + m.insert(key, ListState { allocator: title_alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); old }; drop(old); From b3931948a615a64351b8f2b3a4b04378181e733b Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:54:27 +0300 Subject: [PATCH 184/258] D3D12.X: bypass title hooks for own_work ExecuteCommandLists --- crates/xcl/src/hle/d3d12x/real.rs | 77 ++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index d0d42ecef9..5fd17acf41 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8825,7 +8825,12 @@ unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists"))); - if n == 0 || lists.is_null() { + // Internal XCL submits (`sparse` uploads/readbacks, `title_textures` uploads, tile zeroing) + // run inside `own_work()` — sometimes while holding internal locks (`sparse::STATE`, + // `vram::PAGES`). Forwarding them straight to PC `ExecuteCommandLists` skips + // `present::note_execute` -> `late_release::drain_known` -> `vram::recycle_ready`, preventing + // re-entrant lock self-deadlocks and keeping internal queues out of `present::QUEUES`. + if n == 0 || lists.is_null() || super::title_textures::is_own_work() { f(this, n, lists); stop_if_device_removed(); return; @@ -9592,6 +9597,76 @@ mod queue_tests { assert!(NEWER_LIST_SLOTS.contains(&(129, 127)), "DispatchMesh must map to newer slot #129"); assert!(!NEWER_LIST_SLOTS.iter().any(|&(newer, _)| newer == 128), "newer slot #128 must not map to DispatchMesh"); } + + #[test] + fn own_work_execute_command_lists_bypasses_note_execute_and_drain() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + static CALLED: AtomicUsize = AtomicUsize::new(0); + unsafe extern "system" fn fake_qi(_this: *mut c_void, _iid: *const GUID, out: *mut *mut c_void) -> HRESULT { + if !out.is_null() { + *out = std::ptr::null_mut(); + } + -2147467262 // E_NOINTERFACE + } + unsafe extern "system" fn fake_ref(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn fake_noop(_this: *mut c_void) {} + unsafe extern "system" fn fake_execute(_this: *mut c_void, n: u32, _lists: *const *mut c_void) { + CALLED.fetch_add(n as usize, Ordering::SeqCst); + } + + let iface = layout::find("ID3D12CommandQueue").expect("ID3D12CommandQueue layout"); + let exec_slot = layout::slot(iface, "ExecuteCommandLists").expect("ExecuteCommandLists slot"); + let n = iface.methods.len(); + let mut fake_vtbl = vec![fake_noop as usize; n + 1]; + fake_vtbl[0] = fake_qi as usize; + fake_vtbl[1] = fake_ref as usize; + fake_vtbl[2] = fake_ref as usize; + fake_vtbl[exec_slot] = fake_execute as usize; + fake_vtbl[n] = 0; + let orig = fake_vtbl.as_ptr() as usize; + + struct ClassCleanup(usize); + impl Drop for ClassCleanup { + fn drop(&mut self) { + let mut exts = Vec::new(); + CLASSES.lock().unwrap().retain(|c| { + if c.orig == self.0 { + exts.push(c.ext); + false + } else { + true + } + }); + if let Some(set) = EXTS.lock().unwrap().as_mut() { + for e in exts { + set.remove(&e); + } + } + } + } + let _cleanup = ClassCleanup(orig); + + let mut obj = orig; + let obj_ptr = &mut obj as *mut usize as *mut c_void; + let ext = unsafe { class_for(obj_ptr, orig, Kind::CommandQueue) }; + unsafe { *(obj_ptr as *mut usize) = ext; } + + let mut dummy_list = std::ptr::null_mut::(); + let queues_before = crate::hle::d3d12x::present::known_queues(); + let before_called = CALLED.load(Ordering::SeqCst); + unsafe { + crate::hle::d3d12x::title_textures::own_work(|| { + q_execute_command_lists(obj_ptr, 1, &mut dummy_list as *mut *mut c_void); + }); + } + assert_eq!(CALLED.load(Ordering::SeqCst), before_called + 1, "original ExecuteCommandLists must still run"); + assert!( + !crate::hle::d3d12x::present::known_queues().contains(&(obj_ptr as usize)), + "own_work submit must not register queue in present::QUEUES" + ); + assert_eq!(crate::hle::d3d12x::present::known_queues().len(), queues_before.len()); + } } #[cfg(test)] From c5951d21f13bd23a740f71dc68c23ce1d5b0a811 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:48:38 +0300 Subject: [PATCH 185/258] D3D12.X: detach retired segments and reclaim idle aside allocators --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 335 +++++++++++++++++++++++- crates/xcl/src/hle/d3d12x/title_list.rs | 6 + 2 files changed, 328 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..b3124a95c5 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -28,6 +28,8 @@ struct Backing { users: HashSet, /// queue → (fence, value after the last submit of one of them) marks: HashMap, + /// true once this backing has been PC-reset while idle and no new recording/submit has touched it + already_reset: bool, } impl Backing { @@ -81,7 +83,24 @@ fn move_list(s: &mut State, list: usize, backing: usize) { } } } - s.backings.entry(backing).or_default().users.insert(list); + let b = s.backings.entry(backing).or_default(); + b.users.insert(list); + b.already_reset = false; +} + +/// A split segment or stand-in PC list has been retired into `title_list`'s spare pool (or +/// superseded by a new recording on `wrapper`): it will not be submitted again until a future +/// `Reset` binds it to a new backing. Removing it from `users` lets its old backing become +/// reusable once its already-submitted GPU `marks` complete, while keeping `last_submit` so +/// `in_flight(list)` still prevents premature reuse. +pub(super) fn retire_recording(list: usize) { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if let Some(backing) = s.of_list.remove(&list) { + if let Some(b) = s.backings.get_mut(&backing) { + b.users.remove(&list); + } + } } /// The PC list's final Release ended its recording. Submitted work still holds the backing @@ -211,7 +230,9 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { }; for &l in lists { if let Some(&b) = s.of_list.get(&(l as usize)) { - s.backings.entry(b).or_default().marks.insert(key, (fence.clone(), value)); + let entry = s.backings.entry(b).or_default(); + entry.marks.insert(key, (fence.clone(), value)); + entry.already_reset = false; } let recording = s.recordings.get(&(l as usize)).copied().unwrap_or(0); s.last_submit.insert(l as usize, LastSubmit { queue: key, fence: fence.clone(), value, recording }); @@ -258,44 +279,267 @@ pub unsafe fn forget(alloc: usize) { } } +/// Pop idle put-aside backings of title allocator `a` whose lists and GPU work have finished +/// so the caller can reset them OUTSIDE `STATE` (preventing re-entrant deadlocks if resetting +/// an allocator drops a prelude `ID3D12CommandAllocator` whose `Release` calls `forget`). +unsafe fn take_free_aside(s: &mut State, a: usize) -> Vec { + let Some(v) = s.aside.get_mut(&a) else { + return Vec::new(); + }; + let mut ready = Vec::new(); + let mut i = 0; + while i < v.len() { + let f = v[i]; + if s.backings.get(&f).is_some_and(|b| !b.already_reset && b.free()) { + ready.push(v.remove(i)); + } else { + i += 1; + } + } + ready +} + +unsafe fn restore_aside(s: &mut State, a: usize, f: usize, ok: bool) -> bool { + if ok { + if let Some(b) = s.backings.get_mut(&f) { + b.marks.clear(); + b.already_reset = true; + } + } + if s.types.contains_key(&a) { + s.aside.entry(a).or_default().push(f); + true + } else { + false + } +} + /// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a /// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put /// aside with its recordings and another one took its place. +/// +/// Releases `STATE` before every `reset_pc_allocator` call so COM callbacks triggered while +/// releasing per-allocator resources (e.g. prelude `ID3D12CommandAllocator::Release` -> `forget`) +/// can never self-deadlock on `STATE`. pub unsafe fn title_reset(alloc: *mut c_void) -> Option { if !enabled() { return None; } - let mut g = STATE.lock().unwrap(); - let s = g.get_or_insert_with(State::default); - title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)) + let a = alloc as usize; + enum Action { + CleanPrimary { aside: Vec }, + ResetCurrent { cur: usize, aside: Vec }, + SwapReuse { cur: usize, spare: usize, needs_reset: bool, aside: Vec }, + SwapNew { cur: usize, ty: i32, aside: Vec }, + } + let action = { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + let c = s.cur.get(&a).copied().unwrap_or(a); + if s.backings.get(&c).is_none_or(|b| b.free()) { + let aside = take_free_aside(s, a); + if c == a { + if let Some(b) = s.backings.get_mut(&c) { + b.marks.clear(); + b.already_reset = true; + } + Action::CleanPrimary { aside } + } else { + Action::ResetCurrent { cur: c, aside } + } + } else { + let ty = *s.types.get(&a)?; + let reuse_idx = s.aside.get(&a).and_then(|v| v.iter().position(|f| s.backings.get(f).is_none_or(|b| b.free()))); + match reuse_idx { + Some(idx) => { + let spare = s.aside.get_mut(&a).unwrap().remove(idx); + let needs_reset = s.backings.get(&spare).is_none_or(|b| !b.already_reset); + let aside = take_free_aside(s, a); + Action::SwapReuse { cur: c, spare, needs_reset, aside } + } + None => { + let aside = take_free_aside(s, a); + Action::SwapNew { cur: c, ty, aside } + } + } + } + }; + + let finish_aside = |aside: Vec| { + if aside.is_empty() { + return; + } + let mut results = Vec::with_capacity(aside.len()); + for f in aside { + let hr = super::real::reset_pc_allocator(f as *mut c_void); + results.push((f, hr >= 0)); + } + let mut orphans = Vec::new(); + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + for (f, ok) in results { + if !restore_aside(s, a, f, ok) && f != a { + orphans.push(f); + } + } + } + } + for f in orphans { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + }; + + match action { + Action::CleanPrimary { aside } => { + finish_aside(aside); + None + } + Action::ResetCurrent { cur, aside } => { + let hr = super::real::reset_pc_allocator(cur as *mut c_void); + if hr >= 0 { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + if let Some(b) = s.backings.get_mut(&cur) { + b.marks.clear(); + b.already_reset = true; + } + } + } + finish_aside(aside); + Some(hr) + } + Action::SwapReuse { cur, spare, needs_reset, aside } => { + let hr = if needs_reset { super::real::reset_pc_allocator(spare as *mut c_void) } else { 0 }; + let mut orphan = None; + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + if hr < 0 { + if !restore_aside(s, a, spare, false) && spare != a { + orphan = Some(spare); + } + } else { + if let Some(b) = s.backings.get_mut(&spare) { + b.marks.clear(); + b.already_reset = true; + } + if s.types.contains_key(&a) { + s.aside.entry(a).or_default().push(cur); + s.cur.insert(a, spare); + s.swaps += 1; + if s.swaps.is_power_of_two() { + let aside_n: usize = s.aside.values().map(|v| v.len()).sum(); + crate::xlog_info!( + "D3D12.X: {} allocator resets so far with recordings still held or on the GPU – another PC allocator took its place ({} made, {aside_n} put aside now)", + s.swaps, + s.made + ); + } + } else if spare != a { + orphan = Some(spare); + } + } + } + } + if let Some(f) = orphan { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + finish_aside(aside); + Some(hr) + } + Action::SwapNew { cur, ty, aside } => { + let this = ID3D12CommandAllocator::from_raw_borrowed(&alloc)?; + let mut dev: Option = None; + this.GetDevice(&mut dev).ok()?; + let made: ID3D12CommandAllocator = dev?.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(ty)).ok()?; + let raw = made.into_raw(); + if !super::real::is_adopted(raw) { + super::real::adopt(raw, super::real::Kind::CommandAllocator); + } + let mut orphan = None; + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + if s.types.contains_key(&a) { + s.made += 1; + s.aside.entry(a).or_default().push(cur); + s.cur.insert(a, raw as usize); + s.swaps += 1; + if s.swaps.is_power_of_two() { + let aside_n: usize = s.aside.values().map(|v| v.len()).sum(); + crate::xlog_info!( + "D3D12.X: {} allocator resets so far with recordings still held or on the GPU – another PC allocator took its place ({} made, {aside_n} put aside now)", + s.swaps, + s.made + ); + } + } else { + orphan = Some(raw as usize); + } + } + } + if let Some(f) = orphan { + drop(ID3D12CommandAllocator::from_raw(f as *mut c_void)); + } + finish_aside(aside); + Some(0) + } + } +} + +/// Reset idle put-aside backings of title allocator `a` whose lists and GPU work have finished +/// (used by lock-free unit tests via `title_reset_in`). +#[cfg(test)] +unsafe fn reclaim_free_aside(s: &mut State, a: usize, reset: &mut impl FnMut(*mut c_void) -> HRESULT) { + let ready = take_free_aside(s, a); + for f in ready { + let ok = reset(f as *mut c_void) >= 0; + let _ = restore_aside(s, a, f, ok); + } } /// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests. +#[cfg(test)] unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMut(*mut c_void) -> HRESULT) -> Option { let a = alloc as usize; let c = s.cur.get(&a).copied().unwrap_or(a); if s.backings.get(&c).is_none_or(|b| b.free()) { - if let Some(b) = s.backings.get_mut(&c) { - b.marks.clear(); - } + #[cfg(test)] + reclaim_free_aside(s, a, &mut reset); if c == a { + if let Some(b) = s.backings.get_mut(&c) { + b.marks.clear(); + b.already_reset = true; + } return None; } - return Some(reset(c as *mut c_void)); + let hr = reset(c as *mut c_void); + if hr >= 0 { + if let Some(b) = s.backings.get_mut(&c) { + b.marks.clear(); + b.already_reset = true; + } + } + return Some(hr); } let ty = *s.types.get(&a)?; // one put aside earlier that nothing uses any more, or a new one let reuse = s.aside.get(&a).and_then(|v| v.iter().copied().find(|f| s.backings.get(f).is_none_or(|b| b.free()))); let next = match reuse { Some(f) => { - // Keep ownership until Reset succeeds so a failure can be retried. - let hr = reset(f as *mut c_void); - if hr < 0 { - return Some(hr); + let needs = s.backings.get(&f).is_none_or(|b| !b.already_reset); + if needs { + // Keep ownership until Reset succeeds so a failure can be retried. + let hr = reset(f as *mut c_void); + if hr < 0 { + return Some(hr); + } } s.aside.get_mut(&a).unwrap().retain(|&x| x != f); if let Some(b) = s.backings.get_mut(&f) { b.marks.clear(); + b.already_reset = true; } f } @@ -315,6 +559,8 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu }; s.aside.entry(a).or_default().push(c); s.cur.insert(a, next); + #[cfg(test)] + reclaim_free_aside(s, a, &mut reset); s.swaps += 1; if s.swaps.is_power_of_two() { let aside: usize = s.aside.values().map(|v| v.len()).sum(); @@ -550,4 +796,67 @@ mod tests { assert_eq!(after_forget, 0, "a forgotten list has no previous submit"); } } + + #[test] + fn retired_segment_releases_backing_after_gpu_completes_while_preserving_in_flight() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut ids = Box::new([0u8; 3]); + let alloc = ids.as_mut_ptr() as usize; + let seg = alloc + 1; + let queue = alloc + 2; + created_on(seg, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.backings.entry(alloc).or_default().marks.insert(queue, (fence.clone(), 1)); + let recording = s.recordings[&seg]; + s.last_submit.insert(seg, LastSubmit { queue, fence: fence.clone(), value: 1, recording }); + } + + // Retiring the segment into `title_list`'s spare pool detaches it from `users` + // while keeping GPU fence `marks` and `in_flight(seg)` intact until completion. + retire_recording(seg); + assert!(in_flight(seg), "retired segment must stay in_flight until GPU finishes"); + { + let g = STATE.lock().unwrap(); + let b = &g.as_ref().unwrap().backings[&alloc]; + assert!(b.users.is_empty(), "retired segment must no longer pin backing.users"); + assert!(!b.free(), "GPU mark must still hold the backing until signaled"); + } + + fence.Signal(1).unwrap(); + assert!(!in_flight(seg)); + { + let g = STATE.lock().unwrap(); + assert!(g.as_ref().unwrap().backings[&alloc].free(), "backing must become free once GPU completes"); + } + forget_list(seg); + forget(alloc); + } + } + + #[test] + fn clean_title_reset_reclaims_idle_aside_backings_once() { + let (alloc, spare1, spare2) = (0x7E57_1000usize, 0x7E57_2000usize, 0x7E57_3000usize); + let mut s = State::default(); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.aside.insert(alloc, vec![spare1, spare2]); + s.backings.insert(spare1, Backing::default()); + s.backings.insert(spare2, Backing::default()); + let mut resets = Vec::new(); + + unsafe { + assert_eq!(title_reset_in(&mut s, alloc as *mut c_void, |r| { resets.push(r as usize); 0 }), None); + assert_eq!(resets, vec![spare1, spare2], "clean reset must reclaim all idle aside backings"); + + // A second clean reset must not redundantly reset already-reclaimed aside backings. + resets.clear(); + assert_eq!(title_reset_in(&mut s, alloc as *mut c_void, |r| { resets.push(r as usize); 0 }), None); + assert!(resets.is_empty(), "already-reset aside backings should not be reset again"); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index bcb184cb08..0e27833a32 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -237,6 +237,11 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: for seg in moved { super::bind::reset(seg as *mut c_void, 0, 0); super::list_x::clear_segment_state(seg); + super::alloc_pool::retire_recording(seg); + } + if stand_in.is_some() { + super::bind::reset(primary, 0, 0); + super::alloc_pool::retire_recording(primary as usize); } } *((this as usize + F_RING_AT) as *mut usize) = 0; @@ -351,6 +356,7 @@ pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { /// Give back to `wrapper`'s spare pool a closed PC command list that did not become a segment. pub(super) fn put_spare(wrapper: *mut c_void, pc: *mut c_void) { + super::alloc_pool::retire_recording(pc as usize); let mut sg = SEGMENTS.lock().unwrap(); sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().spares.push(pc as usize); } From 9d4017e7030497d037a1f5609274c2206d91280b Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Thu, 26 Nov 2026 07:50:18 +0300 Subject: [PATCH 186/258] D3D12.X: drop global FENCES lock across GetCompletedValue and scope CPU-signal refreshes to the signalled fence Encapsulate fence_x tracking in `FenceTable` (`State { map, cells }`) backed by `Arc` (`Box` on its own 64-byte cache line for `monitorx`/`mwaitx` plus a per-fence `refresh_lock: Mutex` live guard). `refresh()`, `note_cpu_signal()`, `pending_summary()`, and `completed_value_address()` now drop the global mutex before any `ID3D12Fence::GetCompletedValue()` COM call; `note_cpu_signal()` and `completed_value_address()` refresh only the target fence rather than scanning all tracked fences; `refresh()` visits only cell-backed fences; and `refresh_lock` serializes concurrent per-fence updates and guards test fence teardown against UAF. Part of #1833 Part of #1773 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/hle/d3d12x/fence_x.rs | 327 +++++++++++++++++++++------ 1 file changed, 264 insertions(+), 63 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index f67967345e..c2a33259b9 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -6,7 +6,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D12::ID3D12Fence; @@ -16,17 +16,130 @@ use windows_sys::Win32::System::Threading as th; #[repr(C, align(64))] struct Cell(AtomicU64); +/// Heap-isolated cell plus per-fence refresh lock (`true` = live, `false` = retired). +/// Keeping `Box` off the lock's cache line avoids false-sharing `monitorx`/`mwaitx` wakes. +struct CellMirror { + cell: Box, + refresh_lock: Mutex, +} + #[derive(Default)] struct Fence { - cell: Option<&'static Cell>, + cell: Option>, /// the highest value a queue was told to signal signalled: u64, /// the highest value a queue was told to wait for waited: u64, } -/// (fences are never freed: XCL holds a reference to each) -static FENCES: Mutex>> = Mutex::new(None); +#[derive(Default)] +struct State { + map: HashMap, + cells: Vec<(usize, Arc)>, +} + +/// (fences are never freed in production: XCL holds a reference to each) +struct FenceTable { + inner: Mutex, +} + +impl FenceTable { + fn new() -> Self { + Self { inner: Mutex::new(State::default()) } + } + + fn refresh_one(fence: usize, mirror: &CellMirror) { + let live = mirror.refresh_lock.lock().unwrap_or_else(|e| e.into_inner()); + if !*live { + return; + } + if let Some(v) = unsafe { borrowed(fence, |f| f.GetCompletedValue()) } { + mirror.cell.0.store(v, Ordering::Release); + } + } + + fn refresh(&self) { + let cells = self.inner.lock().unwrap_or_else(|e| e.into_inner()).cells.clone(); + for (p, mirror) in cells { + Self::refresh_one(p, &mirror); + } + } + + fn note_queue_signal(&self, fence: usize, value: u64) -> bool { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let f = g.map.entry(fence).or_default(); + f.signalled = f.signalled.max(value); + f.cell.is_some() + } + + fn note_queue_wait(&self, fence: usize, value: u64) { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let f = g.map.entry(fence).or_default(); + f.waited = f.waited.max(value); + } + + fn note_cpu_signal(&self, fence: usize) { + let mirror = self.inner.lock().unwrap_or_else(|e| e.into_inner()).map.get(&fence).and_then(|f| f.cell.clone()); + if let Some(mirror) = mirror { + Self::refresh_one(fence, &mirror); + } + } + + fn pending_summary(&self) -> String { + let snap: Vec<(usize, u64, u64, bool)> = { + let g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.map.iter().map(|(&p, f)| (p, f.signalled, f.waited, f.cell.is_some())).collect() + }; + let mut parts = Vec::new(); + for (p, signalled, waited, has_cell) in snap { + let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); + if done < signalled || done < waited { + parts.push(format!("{p:#x}(done={done:#x}/sig={signalled:#x}/wait={waited:#x},cell={has_cell})")); + } + } + if parts.is_empty() { "none".into() } else { parts.join(", ") } + } + + fn completed_value_address_with(&self, this: *mut c_void, arm_fn: impl FnOnce(usize, u64)) -> *const u64 { + let key = this as usize; + let (mirror, pending) = { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.map.get(&key).and_then(|f| f.cell.as_ref()) { + return m.cell.0.as_ptr(); + } + let m = Arc::new(CellMirror { cell: Box::new(Cell(AtomicU64::new(0))), refresh_lock: Mutex::new(true) }); + let pending = { + let f = g.map.entry(key).or_default(); + f.cell = Some(Arc::clone(&m)); + f.signalled + }; + g.cells.push((key, Arc::clone(&m))); + (m, pending) + }; + if pending > 0 { + arm_fn(key, pending); + } + Self::refresh_one(key, &mirror); + mirror.cell.0.as_ptr() + } + + #[cfg(test)] + fn forget_fence(&self, fence: usize) { + let removed = { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.cells.retain(|(p, _)| *p != fence); + g.map.remove(&fence).and_then(|f| f.cell) + }; + if let Some(mirror) = removed { + *mirror.refresh_lock.lock().unwrap_or_else(|e| e.into_inner()) = false; + } + } +} + +fn table() -> &'static FenceTable { + static T: OnceLock = OnceLock::new(); + T.get_or_init(FenceTable::new) +} /// the event a completion sets (auto-reset); the first use starts the thread that follows it fn event() -> usize { @@ -35,7 +148,7 @@ fn event() -> usize { let e = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize; let spawned = std::thread::Builder::new().name("xcl-fences".into()).spawn(move || loop { th::WaitForSingleObject(e as _, th::INFINITE); - refresh(); + table().refresh(); }); if let Err(err) = spawned { crate::xlog_error!("D3D12.X: no thread for the fences' completed values: {err}"); @@ -49,17 +162,6 @@ unsafe fn borrowed(fence: usize, f: impl FnOnce(&ID3D12Fence) -> R) -> Option ID3D12Fence::from_raw_borrowed(&p).map(f) } -fn refresh() { - let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - for (&p, f) in g.iter().flatten() { - if let Some(c) = f.cell { - if let Some(v) = unsafe { borrowed(p, |f| f.GetCompletedValue()) } { - c.0.store(v, Ordering::Release); - } - } - } -} - unsafe fn arm(fence: usize, value: u64) { if let Some(Err(e)) = borrowed(fence, |f| f.SetEventOnCompletion(value, HANDLE(event() as *mut c_void))) { crate::xlog_warn!("D3D12.X: fence {fence:#x}: SetEventOnCompletion({value:#x}): {e}"); @@ -68,76 +170,35 @@ unsafe fn arm(fence: usize, value: u64) { /// A queue was told to signal `fence` (one of the title's) with `value`. pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) { - let cell = { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); - f.signalled = f.signalled.max(value); - f.cell.is_some() - }; - if cell { + if table().note_queue_signal(fence, value) { arm(fence, value); } } /// A queue was told to wait for `fence` (one of the title's) to reach `value`. pub(super) fn note_queue_wait(fence: usize, value: u64) { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); - f.waited = f.waited.max(value); + table().note_queue_wait(fence, value); } /// The CPU signalled `fence`. pub(super) fn note_cpu_signal(fence: usize) { - let known = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.get(&fence).is_some_and(|f| f.cell.is_some())); - if known { - refresh(); - } + table().note_cpu_signal(fence); } /// Diagnostic summary of title fences whose completed value lags their signalled or waited value. pub(super) fn pending_summary() -> String { - let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let mut parts = Vec::new(); - for (&p, f) in g.iter().flatten() { - let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); - if done < f.signalled || done < f.waited { - parts.push(format!("{p:#x}(done={done:#x}/sig={:#x}/wait={:#x},cell={})", f.signalled, f.waited, f.cell.is_some())); - } - } - if parts.is_empty() { - "none".into() - } else { - parts.join(", ") - } + table().pending_summary() } /// fence #12: the address of its completed value pub(super) unsafe extern "system" fn completed_value_address(this: *mut c_void) -> *const u64 { - let (cell, pending) = { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); - match f.cell { - Some(c) => return c.0.as_ptr(), - None => { - let c: &'static Cell = Box::leak(Box::new(Cell(AtomicU64::new(0)))); - f.cell = Some(c); - (c, f.signalled) - } - } - }; - if pending > 0 { - arm(this as usize, pending); - } - refresh(); - cell.0.as_ptr() + table().completed_value_address_with(this, |f, v| arm(f, v)) } /// Remove a synthetic test fence from `FENCES` before it is dropped. #[cfg(test)] pub(super) fn forget_fence_for_test(fence: usize) { - if let Some(m) = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { - m.remove(&fence); - } + table().forget_fence(fence); } #[cfg(test)] @@ -183,4 +244,144 @@ mod tests { std::mem::forget(fence); // the map keeps its address } } + + struct Gate { + entered: Arc, + release: Arc, + } + + #[repr(C)] + struct MockFence { + vtable: *const usize, + val: AtomicU64, + calls: std::sync::atomic::AtomicUsize, + gate: Mutex>, + } + unsafe impl Send for MockFence {} + unsafe impl Sync for MockFence {} + + impl MockFence { + fn new(val: u64) -> Box { + use std::mem::{offset_of, size_of}; + unsafe extern "system" fn get_val(this: *mut c_void) -> u64 { + let f = &*this.cast::(); + f.calls.fetch_add(1, Ordering::AcqRel); + let v = f.val.load(Ordering::Acquire); + if let Some(g) = f.gate.lock().unwrap().take() { + g.entered.wait(); + g.release.wait(); + } + v + } + extern "system" fn unexpected() { std::process::abort(); } + const SLOT: usize = size_of::(); + const LEN: usize = size_of::() / SLOT; + static VT: OnceLock<[usize; LEN]> = OnceLock::new(); + let vt = VT.get_or_init(|| { + let mut t = [unexpected as usize; LEN]; + t[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = get_val as usize; + t + }); + Box::new(Self { vtable: vt.as_ptr(), val: AtomicU64::new(val), calls: Default::default(), gate: Mutex::new(None) }) + } + fn as_ptr(&self) -> *mut c_void { std::ptr::from_ref(self) as *mut c_void } + fn arm_gate(&self) -> (Arc, Arc) { + let (e, r) = (Arc::new(std::sync::Barrier::new(2)), Arc::new(std::sync::Barrier::new(2))); + *self.gate.lock().unwrap() = Some(Gate { entered: e.clone(), release: r.clone() }); + (e, r) + } + } + + #[test] + fn refresh_and_pending_summary_do_not_block_concurrent_queue_and_cpu_signals() { + let table = Arc::new(FenceTable::new()); + let (a, b) = (MockFence::new(1), MockFence::new(2)); + let (pa, pb) = (a.as_ptr(), b.as_ptr()); + let _cell_a = table.completed_value_address_with(pa, |_, _| {}); + let cell_b = table.completed_value_address_with(pb, |_, _| {}); + assert!(table.note_queue_signal(pa as usize, 10)); + + // 1. refresh() must not hold global lock across GetCompletedValue(). + let (entered, release) = a.arm_gate(); + let t1 = Arc::clone(&table); + let h1 = std::thread::spawn(move || t1.refresh()); + entered.wait(); + b.val.store(4, Ordering::Release); + assert!(table.note_queue_signal(pb as usize, 4)); + table.note_queue_wait(pb as usize, 4); + table.note_cpu_signal(pb as usize); + assert_eq!(unsafe { (*(cell_b as *const AtomicU64)).load(Ordering::Acquire) }, 4); + release.wait(); + h1.join().unwrap(); + + // 2. pending_summary() must not hold global lock across GetCompletedValue(). + let (entered, release) = a.arm_gate(); + let t2 = Arc::clone(&table); + let h2 = std::thread::spawn(move || t2.pending_summary()); + entered.wait(); + b.val.store(7, Ordering::Release); + assert!(table.note_queue_signal(pb as usize, 7)); + table.note_queue_wait(pb as usize, 7); + table.note_cpu_signal(pb as usize); + assert_eq!(unsafe { (*(cell_b as *const AtomicU64)).load(Ordering::Acquire) }, 7); + release.wait(); + let summary = h2.join().unwrap(); + assert!(summary.contains("done=0x1/sig=0xa/"), "unexpected summary: {summary}"); + } + + #[test] + fn note_cpu_signal_and_refresh_avoid_unrelated_and_non_cell_fences() { + let table = FenceTable::new(); + let (a, b) = (MockFence::new(3), MockFence::new(5)); + let non_cells: Vec> = (0..64).map(|i| MockFence::new(i)).collect(); + let (pa, pb) = (a.as_ptr(), b.as_ptr()); + let _ = table.completed_value_address_with(pa, |_, _| {}); + let _ = table.completed_value_address_with(pb, |_, _| {}); + for f in &non_cells { + assert!(!table.note_queue_signal(f.as_ptr() as usize, 10)); + table.note_queue_wait(f.as_ptr() as usize, 10); + } + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.note_cpu_signal(pb as usize); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (0, 1)); + assert!(non_cells.iter().all(|f| f.calls.load(Ordering::Acquire) == 0)); + + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.refresh(); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (1, 1)); + assert!(non_cells.iter().all(|f| f.calls.load(Ordering::Acquire) == 0)); + + table.forget_fence(pa as usize); + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.refresh(); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (0, 1)); + } + + #[test] + fn per_cell_lock_prevents_stale_refresh_overwrite() { + let table = Arc::new(FenceTable::new()); + let a = MockFence::new(10); + let pa = a.as_ptr(); + let cell = table.completed_value_address_with(pa, |_, _| {}); + a.calls.store(0, Ordering::Release); + + let (entered, release) = a.arm_gate(); + let t1 = Arc::clone(&table); + let h1 = std::thread::spawn(move || t1.refresh()); + entered.wait(); + a.val.store(11, Ordering::Release); + let t2 = Arc::clone(&table); + let pa_addr = pa as usize; + let h2 = std::thread::spawn(move || t2.note_cpu_signal(pa_addr)); + std::thread::sleep(std::time::Duration::from_millis(20)); + assert_eq!(a.calls.load(Ordering::Acquire), 1, "note_cpu_signal must serialize behind in-flight refresh_lock"); + release.wait(); + h1.join().unwrap(); + h2.join().unwrap(); + assert_eq!(a.calls.load(Ordering::Acquire), 2); + assert_eq!(unsafe { (*(cell as *const AtomicU64)).load(Ordering::Acquire) }, 11); + } } From 558d10a5d60ed4f7c1106450066e374446841046 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:00:28 +0300 Subject: [PATCH 187/258] BCPack: replace bit-packing loops with compile-time LUTs and precomputed masks in victory Per-block BCPack decoding on the DirectStorage texture decompression path repeated inner bit-spread/deinterleave loops (`interleave`, `nibbles`, `bc6` `wide`), recomputed dynamic bit masks in `plain`, scanned anchor slices on every pixel in `bc7_pack`, and indexed unsized slices inside the 16-pixel `bc1_color` and `bc4_alpha` packing loops. - Add compile-time `SPREAD4`, `SPREAD8`, and `NIBBLES` lookup tables with `#[inline(always)]` `interleave`, `wide_interleave`, and `nibbles` helpers replacing the per-call bit-spread and deinterleave loops. - Precompute `ep_mask`, `ep_len`, `ix_mask`, and `ix_len` in `Widths` and use exact active endpoint/index masking loops (with a fixed 16-byte SIMD fast path for BC1/BC4) in `plain`, removing 40 dynamic shifts per block. - Narrow `quads`, `bc1_color`, and `bc4_alpha` to fixed-size array references (`[u8; 4]`, `[u8; 6]`, `[u8; 16]`, `[u8; 8]`), use `as_chunks_mut::<2>()` in `pairs`, write `bc1_color` in a single `u64::to_le_bytes()` store, and inline `zz`, `add_index`, and `Bits::put` (using a 64-bit mask before widening to `u128`). - Replace `anchors.contains(...)` slice scans in `bc7_pack` and per-pixel anchor branches in `bc6` with a precomputed `u16` `anchor_mask` bitmask. - Add pure-CPU unit tests exhaustively verifying `interleave`, `wide_interleave`, `nibbles`, `Widths` masks/lengths, BC7/BC6H `anchor_mask`, `Bits::put`, all 12 valid shipped `tests/data/bcpack` fixtures against unmodified `origin/main` hashes, `bc1_color`/`bc4_alpha`, and all 14 BC6H modes + all 8 BC7 modes. Part of #1833 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/hle/bcpack/victory.rs | 375 ++++++++++++++++++++++----- 1 file changed, 316 insertions(+), 59 deletions(-) diff --git a/crates/xcl/src/hle/bcpack/victory.rs b/crates/xcl/src/hle/bcpack/victory.rs index 20b8fa5129..9886e914d9 100644 --- a/crates/xcl/src/hle/bcpack/victory.rs +++ b/crates/xcl/src/hle/bcpack/victory.rs @@ -331,10 +331,39 @@ fn references(s: &[u8], paired: bool) -> (usize, usize) { (usize::from(ix.wrapping_add(delta)), usize::from(ix)) } +/// Spreads a 4-bit symbol onto even bit positions `0, 2, 4, 6`. +const SPREAD4: [u8; 16] = [ + 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15, + 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55, +]; + +/// Spreads an 8-bit symbol onto even bit positions `0, 2, ..., 14`. +const SPREAD8: [u16; 256] = { + let mut t = [0u16; 256]; + let mut v = 0usize; + while v < 256 { + let mut out = 0u16; + let mut k = 0; + while k < 8 { + out |= (((v >> k) & 1) as u16) << (2 * k); + k += 1; + } + t[v] = out; + v += 1; + } + t +}; + /// Two 4-bit symbols, the first on the even bits. +#[inline(always)] fn interleave(a: u8, b: u8) -> u8 { - let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); - spread(a) | spread(b) << 1 + SPREAD4[usize::from(a & 15)] | (SPREAD4[usize::from(b & 15)] << 1) +} + +/// Two 8-bit symbols, the first on the even bits. +#[inline(always)] +fn wide_interleave(a: u8, b: u8) -> u16 { + SPREAD8[usize::from(a)] | (SPREAD8[usize::from(b)] << 1) } /// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first @@ -348,26 +377,40 @@ fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: } /// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits. +#[inline(always)] fn zz(v: u8, bits: u32) -> u8 { let mask = ((1u32 << bits) - 1) as u8; ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask } -/// Element widths of the plain formats' endpoints and indices. +/// Element masks and active counts of the plain formats' endpoints and indices. struct Widths { - ep: [u8; 8], - ix: [u8; 32], + ep_mask: [u8; 8], + ep_len: usize, + ix_mask: [u8; 32], + ix_len: usize, paired: bool, } const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { - let mut ix = [0; 32]; + let mut ep_mask = [0u8; 8]; + let mut ep_len = 0; let mut k = 0; - while k < ix3 + ix2 { - ix[k] = if k < ix3 { 3 } else { 2 }; + while k < 8 { + if ep[k] != 0 { + ep_mask[k] = ((1u16 << ep[k]) - 1) as u8; + ep_len = k + 1; + } k += 1; } - Widths { ep, ix, paired } + let mut ix_mask = [0u8; 32]; + let ix_len = ix3 + ix2; + let mut k = 0; + while k < ix_len { + ix_mask[k] = if k < ix3 { 7 } else { 3 }; + k += 1; + } + Widths { ep_mask, ep_len, ix_mask, ix_len, paired } } const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); @@ -390,11 +433,17 @@ fn plain<'a>( let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; let mut v = residual(s); - for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { - *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; + for ((v, &r), &mask) in v.ep[..w.ep_len].iter_mut().zip(ep_ref).zip(&w.ep_mask) { + *v = v.wrapping_add(r) & mask; } - for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { - *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + if w.ix_len == 16 { + for ((v, &r), &mask) in v.ix[..16].iter_mut().zip(&ix_ref[..16]).zip(&w.ix_mask[..16]) { + *v = v.wrapping_add(r) & mask; + } + } else { + for ((v, &r), &mask) in v.ix[..w.ix_len].iter_mut().zip(ix_ref).zip(&w.ix_mask) { + *v = v.wrapping_add(r) & mask; + } } history[i % HISTORY] = v; pack(&v, block); @@ -403,22 +452,26 @@ fn plain<'a>( } /// 2-bit index residuals: one symbol per 2x2 quad. -fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { +#[inline(always)] +fn quads(rank: &[u8; 256], s: &[u8; 4], ix: &mut [u8; 16]) { for (q, &sym) in s.iter().enumerate() { let v = rank[usize::from(sym)]; let base = (q >> 1) * 8 + (q & 1) * 2; - for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { - ix[base + p] = v >> (2 * k) & 3; - } + ix[base] = v & 3; + ix[base + 1] = (v >> 2) & 3; + ix[base + 4] = (v >> 4) & 3; + ix[base + 5] = (v >> 6) & 3; } } /// 3-bit index residuals: one symbol per two pixels in raster order. +#[inline(always)] fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { - for (k, &sym) in s.iter().enumerate() { + let (chunks, _) = ix.as_chunks_mut::<2>(); + for (&sym, dst) in s.iter().zip(chunks) { let v = rank[usize::from(sym & 63)]; - ix[2 * k] = v & 7; - ix[2 * k + 1] = v >> 4 & 7; + dst[0] = v & 7; + dst[1] = (v >> 4) & 7; } } @@ -427,7 +480,7 @@ fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { v.ep[k] = zz(s[2 + k], bits); } - quads(&t.rank1, &s[8..12], &mut v.ix); + quads(t.rank1, s[8..12].try_into().unwrap(), (&mut v.ix[..16]).try_into().unwrap()); v } @@ -447,7 +500,7 @@ fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { ..Default::default() }; pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); - quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); + quads(t.rank3c, s[20..24].try_into().unwrap(), (&mut v.ix[16..]).try_into().unwrap()); v } @@ -471,54 +524,88 @@ fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; -fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { +#[inline(always)] +fn bc1_color(ep: &[u8; 6], ix: &[u8; 16], out: &mut [u8; 8]) { let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); - let bits = (0..16).fold(0, |acc, p| { - acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) - }); - out[..2].copy_from_slice(&c0.to_le_bytes()); - out[2..4].copy_from_slice(&c1.to_le_bytes()); - out[4..8].copy_from_slice(&bits.to_le_bytes()); + let mut bits = 0u32; + for (p, &val) in ix.iter().enumerate() { + bits |= BC1_CODE[usize::from(val & 3)] << (2 * p); + } + let word = u64::from(c0) | (u64::from(c1) << 16) | (u64::from(bits) << 32); + *out = word.to_le_bytes(); } /// BC4 half: endpoints are kept 128 below their stored value. -fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { - let bits = (0..16).fold(0u64, |acc, p| { - acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) - }); +#[inline(always)] +fn bc4_alpha(e0: u8, e1: u8, ix: &[u8; 16], out: &mut [u8; 8]) { + let mut bits = 0u64; + for (p, &val) in ix.iter().enumerate() { + bits |= BC4_CODE[usize::from(val & 7)] << (16 + 3 * p); + } let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; - out[..8].copy_from_slice(&v.to_le_bytes()); + *out = v.to_le_bytes(); } fn bc1_pack(v: &Plain, out: &mut [u8]) { - bc1_color(&v.ep, &v.ix, out); + bc1_color( + v.ep[..6].try_into().unwrap(), + v.ix[..16].try_into().unwrap(), + (&mut out[..8]).try_into().unwrap(), + ); } fn bc3_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]); - bc1_color(&v.ep, &v.ix[16..], &mut out[8..]); + let (a, c) = out.split_at_mut(8); + bc4_alpha(v.ep[6], v.ep[7], v.ix[..16].try_into().unwrap(), a.try_into().unwrap()); + bc1_color( + v.ep[..6].try_into().unwrap(), + v.ix[16..].try_into().unwrap(), + (&mut c[..8]).try_into().unwrap(), + ); } fn bc4_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix, out); + bc4_alpha(v.ep[0], v.ep[1], v.ix[..16].try_into().unwrap(), (&mut out[..8]).try_into().unwrap()); } fn bc5_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); - bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); + let (a, b) = out.split_at_mut(8); + bc4_alpha(v.ep[0], v.ep[1], v.ix[..16].try_into().unwrap(), a.try_into().unwrap()); + bc4_alpha(v.ep[2], v.ep[3], v.ix[16..].try_into().unwrap(), (&mut b[..8]).try_into().unwrap()); } +/// Even and odd bit nibbles of every byte, zigzag-decoded to signed 4-bit residuals. +const NIBBLES: [[i16; 2]; 256] = { + let mut t = [[0i16; 2]; 256]; + let mut b = 0usize; + while b < 256 { + let mut even = 0u8; + let mut odd = 0u8; + let mut k = 0; + while k < 4 { + even |= (((b as u8) >> (2 * k)) & 1) << k; + odd |= (((b as u8) >> (2 * k + 1)) & 1) << k; + k += 1; + } + let ze = (even >> 1) as i16 ^ -((even & 1) as i16); + let zo = (odd >> 1) as i16 ^ -((odd & 1) as i16); + t[b] = [ze, zo]; + b += 1; + } + t +}; + /// A byte's even and odd bits as two zigzag-coded 4-bit residuals. +#[inline(always)] fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { - let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); - let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); - let (even, odd) = (z(half(b)), z(half(b >> 1))); + let [even, odd] = NIBBLES[usize::from(b)]; if odd_first { [odd, even] } else { [even, odd] } } /// Index residual plus reference, both left-aligned to 16 bits at their own /// widths, back to `bits` bits (signed). +#[inline(always)] fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { let up = |v: i16, b: u8| { if b == 0 || b > 16 { @@ -539,9 +626,11 @@ struct Bits { } impl Bits { + #[inline(always)] fn put(&mut self, value: u64, n: u32) { if n > 0 && self.at < 128 { - self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; + let masked = if n < 64 { value & ((1u64 << n) - 1) } else { value }; + self.v |= u128::from(masked) << self.at; } self.at += n; } @@ -735,15 +824,15 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), _ => {} } - let anchors: &[u8] = match subsets { - 2 => &[0, ANCHOR2[part]], - 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], - _ => &[0], + let anchor_mask: u16 = match subsets { + 2 => 1 | (1 << ANCHOR2[part]), + 3 => 1 | (1 << ANCHOR3A[part]) | (1 << ANCHOR3B[part]), + _ => 1, }; let mut indices = |set: usize| { - let bits = ix.bits[set]; + let bits = u32::from(ix.bits[set]); for (p, &v) in ix.ix[set].iter().enumerate() { - let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + let n = bits - u32::from((anchor_mask >> p) & 1); w.put(u64::from(v as u16), n); } }; @@ -920,11 +1009,7 @@ fn bc6<'a>( }, ); let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); - let wide = |a: u8, b: u8| { - (0..8).fold(0u16, |acc, k| { - acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) - }) - }; + let wide = wide_interleave; for (i, (s, block)) in records.zip(out).enumerate() { let (ep_ref, ix_ref) = references(s, true); let mode = s[30].wrapping_add(1); @@ -999,14 +1084,186 @@ fn bc6<'a>( ); } } - let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; + let anchor_mask: u16 = if two { 1 | (1 << ANCHOR2[usize::from(part)]) } else { 1 }; + let bias = 1u16 << (bits - 1); for (p, &v) in ix.ix.iter().enumerate() { - let short = p == 0 || p == usize::from(anchor); - let v = (v as u16).wrapping_add(1 << (bits - 1)); - w.put(v.into(), u32::from(bits) - u32::from(short)); + let v = (v as u16).wrapping_add(bias); + w.put(v.into(), u32::from(bits) - u32::from((anchor_mask >> p) & 1)); } block.copy_from_slice(&w.v.to_le_bytes()); } Ok(()) } +#[cfg(test)] +mod tests { + use super::*; + + fn fnv1a(bytes: &[u8]) -> u64 { + let mut h = 0xcbf29ce484222325u64; + for &b in bytes { + h ^= u64::from(b); + h = h.wrapping_mul(0x100000001b3); + } + h + } + + #[test] + fn lut_helpers_match_scalar_reference_exhaustively() { + let spread4 = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> k) & 1) << (2 * k)); + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> (2 * k)) & 1) << k); + let z4 = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + for a in 0..=255u8 { + let (even, odd) = (z4(half(a)), z4(half(a >> 1))); + assert_eq!(nibbles(a, false), [even, odd]); + assert_eq!(nibbles(a, true), [odd, even]); + for b in 0..=255u8 { + assert_eq!(interleave(a, b), spread4(a) | (spread4(b) << 1)); + let wide_ref = (0..8).fold(0u16, |acc, k| { + acc | (u16::from((a >> k) & 1) << (2 * k)) | (u16::from((b >> k) & 1) << (2 * k + 1)) + }); + assert_eq!(wide_interleave(a, b), wide_ref); + } + } + + // Precomputed Widths masks and active lengths for BC1/BC3/BC4/BC5. + for (w, ep_bits, ix3, ix2) in [ + (&BC1, [5u8, 6, 5, 5, 6, 5, 0, 0], 0usize, 16usize), + (&BC3, [5, 6, 5, 5, 6, 5, 8, 8], 16, 16), + (&BC4, [8, 8, 0, 0, 0, 0, 0, 0], 16, 0), + (&BC5, [8, 8, 8, 8, 0, 0, 0, 0], 32, 0), + ] { + let want_ep_len = ep_bits.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + assert_eq!(w.ep_len, want_ep_len); + assert_eq!(w.ix_len, ix3 + ix2); + for (k, &bits) in ep_bits.iter().enumerate() { + assert_eq!(w.ep_mask[k], ((1u16 << bits) - 1) as u8); + } + for (k, &mask) in w.ix_mask.iter().enumerate() { + let bits = if k < ix3 { 3 } else if k < ix3 + ix2 { 2 } else { 0 }; + assert_eq!(mask, (1u8 << bits) - 1); + } + } + + // BC7 and BC6H u16 anchor bitmasks match slice/branch anchor predicates. + for part in 0..64usize { + for subsets in [1usize, 2, 3] { + let anchors: &[u8] = match subsets { + 2 => &[0, ANCHOR2[part]], + 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], + _ => &[0], + }; + let mask: u16 = match subsets { + 2 => 1 | (1 << ANCHOR2[part]), + 3 => 1 | (1 << ANCHOR3A[part]) | (1 << ANCHOR3B[part]), + _ => 1, + }; + for p in 0..16usize { + assert_eq!(((mask >> p) & 1) != 0, anchors.contains(&(p as u8))); + } + } + if part < 32 { + for two in [false, true] { + let anchor = if two { ANCHOR2[part] } else { 0 }; + let mask: u16 = if two { 1 | (1 << ANCHOR2[part]) } else { 1 }; + for p in 0..16usize { + assert_eq!(((mask >> p) & 1) != 0, p == 0 || p == usize::from(anchor)); + } + } + } + } + + // Bits::put matches u128 reference across n = 0, small widths, 64, and overflow past 128. + let mut got = Bits::default(); + let mut ref_v = 0u128; + let mut ref_at = 0u32; + for (val, n) in [(0xFFFFu64, 0u32), (0x55, 5), (0xDEAD_BEEF_CAFE_BABE, 64), (0x3FF, 10), (0xFFFF, 60)] { + got.put(val, n); + if n > 0 && ref_at < 128 { + ref_v |= (u128::from(val) & ((1u128 << n) - 1)) << ref_at; + } + ref_at += n; + assert_eq!((got.v, got.at), (ref_v, ref_at)); + } + } + + #[test] + fn all_bc_fixtures_and_packers_match_baseline() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/bcpack"); + let tables = Tables::builtin(); + let cases: [(&str, u8, usize, u64); 12] = [ + ("bc1-2-0", 1, 2 * 8, 0x00241ed045f935b7), + ("bc1-16-1", 1, 16 * 8, 0xaa27d5c23c617a11), + ("bc1-16-9", 1, 16 * 8, 0x5af81e16cde0f88b), + ("bc1-700-2", 1, 700 * 8, 0x6c1294776a5e0f7f), + ("bc1-8192-3", 1, 8192 * 8, 0xa0d8a27ea25cb660), + ("bc3-16-1", 3, 16 * 8, 0xc9b128a6e1beda7b), + ("bc4-16-1", 4, 16 * 8, 0x80173d43d3e12784), + ("bc5-16-1", 5, 16 * 8, 0x4338d58b289e83fc), + ("bc6-16-1", 6, 16 * 8, 0x4312c31241f68f5f), + ("bc7-2-0", 7, 2 * 8, 0xb3e3f4cd147b0999), + ("bc7-16-1", 7, 16 * 8, 0x013a7ec1ceec8b71), + ("bc7-8192-3", 7, 8192 * 8, 0x0b54870998ec2325), + ]; + for (stem, mode, out_len, want_hash) in cases { + let src = std::fs::read(dir.join(format!("{stem}.bin"))).unwrap(); + let mut dst = vec![0u8; out_len]; + decode(mode, &src, &mut dst, tables).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(fnv1a(&dst), want_hash, "{stem} output diverged from baseline"); + } + let bad_src = std::fs::read(dir.join("bc7-700-2.bin")).unwrap(); + let mut bad_dst = vec![0u8; 700 * 8]; + assert_eq!(decode(7, &bad_src, &mut bad_dst, tables), Err(Error("unused BC7 control code"))); + + // Verify fixed-size bc1_color/bc4_alpha and every BC6H mode 1..=14 / BC7 mode 0..=7. + let ep6 = [19u8, 45, 7, 29, 12, 31]; + let ix16: [u8; 16] = std::array::from_fn(|p| ((p * 5 + 3) & 7) as u8); + let (mut got1, mut got4) = ([0u8; 8], [0u8; 8]); + bc1_color(&ep6, &ix16, &mut got1); + let c0 = u16::from(ep6[0]) << 11 | u16::from(ep6[1]) << 5 | u16::from(ep6[2]); + let c1 = u16::from(ep6[3]) << 11 | u16::from(ep6[4]) << 5 | u16::from(ep6[5]); + let ref_bits1 = (0..16).fold(0u32, |acc, p| acc | (BC1_CODE[usize::from(ix16[p] & 3)] << (2 * p))); + assert_eq!(&got1[..2], &c0.to_le_bytes()); + assert_eq!(&got1[2..4], &c1.to_le_bytes()); + assert_eq!(&got1[4..8], &ref_bits1.to_le_bytes()); + bc4_alpha(0x2A, 0xD5, &ix16, &mut got4); + let ref_v4 = u64::from(0x2Au8 ^ 0x80) + | (u64::from(0xD5u8 ^ 0x80) << 8) + | (0..16).fold(0u64, |acc, p| acc | (BC4_CODE[usize::from(ix16[p] & 7)] << (16 + 3 * p))); + assert_eq!(got4, ref_v4.to_le_bytes()); + + // Exercise all 14 BC6H modes (1..=14) and all 8 BC7 modes (0..=7) end-to-end. + let bc6_recs: Vec<[u8; 32]> = (1u8..=14) + .map(|m| { + let mut r = [0u8; 32]; + for (k, slot) in r.iter_mut().enumerate().take(30) { + *slot = (m.wrapping_mul(17).wrapping_add((k as u8).wrapping_mul(11))) & 0x7F; + } + r[30] = m - 1; + r[31] = (m * 3) & 31; + r + }) + .collect(); + let mut bc6_out = [[0u8; 16]; 14]; + bc6(bc6_recs.iter().map(|r| &r[..]), bc6_out.iter_mut().map(|b| &mut b[..]), tables.bc6).unwrap(); + assert!(bc6_out.iter().all(|b| b.iter().any(|&x| x != 0))); + + let mut bc7_recs = Vec::new(); + for mode in 0u16..8 { + let idx = tables.ctrl7.iter().position(|&c| c != 0 && (c & 7) == mode).unwrap(); + let mut r = [0u8; 32]; + for (k, slot) in r.iter_mut().enumerate().take(30) { + *slot = ((mode as u8 + 1).wrapping_mul(13).wrapping_add((k as u8).wrapping_mul(7))) & 0x3F; + } + r[30] = (idx & 31) as u8; + r[31] = ((idx >> 5) & 15) as u8; + bc7_recs.push(r); + } + let mut bc7_out = [[0u8; 16]; 8]; + bc7(bc7_recs.iter().map(|r| &r[..]), bc7_out.iter_mut().map(|b| &mut b[..]), tables).unwrap(); + for (mode, block) in bc7_out.iter().enumerate() { + assert_eq!(block[0].trailing_zeros() as usize, mode, "BC7 mode {mode} header bit"); + } + } +} + From 65b278404464824bd3068dfb2fe69c61d81950da Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:23:17 -0500 Subject: [PATCH 188/258] D3D12.X: a 3D render target keeps off the pages of the title's next texture The size of a 3D render target on the console is not modelled, and without a size every PC tile of the reserved texture went on the title's pages from its address on. The PC's texture has more tiles than the console's takes (18 for 33x33x33 texels of 8 bytes), so the last ones were the first pages of the texture the title placed behind it (512 KiB on): two such textures wrote over each other. A title's run-time colour-grading volumes are placed like that. Two of the three the tone-mapping pass reads held slabs of their neighbours: the picture came out teal and close to a negative. With the texels of the first level as the least the texture takes, it has those pages at its address and its own tiles for the rest. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/vram.rs | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 2fd19148d9..f0488df7af 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2769,6 +2769,16 @@ fn console_has_packed_3d_mips(desc: &D3D12_RESOURCE_DESC) -> bool { .unwrap_or(false) } +/// The least a 3D texture of `desc` takes on the console – the texels of its first level, one +/// after the other – for a 3D texture whose size there is not known: the pages it has to itself +/// at its address. None: not a 3D texture. The PC's tiles past those pages are its own +/// (`owned_pages`), not the pages of what the title placed behind it. +fn least_volume_bytes(desc: &D3D12_RESOURCE_DESC) -> Option { + (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) + .then(|| desc.Width * desc.Height as u64 * desc.DepthOrArraySize as u64 * super::targets::texel_bytes(desc.Format) as u64) + .filter(|&b| b != 0) +} + /// A GPU-owned texture of the title at `va` (`desc`: the PC description, `console_bytes` its /// size on the console): on the title's pages there, else in the arena for that address (None: /// neither – the caller makes a resource of its own). @@ -2779,6 +2789,10 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st if !tier2(dev) { return None; } + // (a 3D render target's size on the console is not modelled: without one, every PC tile of + // it went on the title's pages from `va` on – more of them than the console's texture takes, + // so the last ones were the first pages of the title's next texture) + let console_bytes = console_bytes.or_else(|| least_volume_bytes(desc)); if std::env::var_os("XCL_VRAM_ARENAS").is_none() { if let Some(hr) = place_on_pages(dev, this, va, desc, state, clear, console_bytes, true, false, riid, ppv) { return Some(hr); @@ -3247,6 +3261,36 @@ mod tests { } } + /// Title textures placed one behind the other, 512 KiB apart: 3D render targets of 33 texels + /// a side with 8-byte texels, whose size on the console XCL does not model. Each has the pages + /// of its own texels and no page of the next one, however many tiles the PC's texture has + /// (18 here: with all of them on the title's pages, the tenth to the eighteenth were the + /// next texture's first pages, and two such textures wrote over each other). + #[test] + fn a_3d_texture_of_unknown_console_size_keeps_off_the_next_textures_pages() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D, + Width: 33, + Height: 33, + DepthOrArraySize: 33, + MipLevels: 1, + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R16G16B16A16_FLOAT, + ..Default::default() + }; + let bytes = least_volume_bytes(&desc); + assert_eq!(bytes, Some(33 * 33 * 33 * 8)); + let (a, b, pc_tiles) = (0x12_31f1_0000usize, 0x12_31f9_0000usize, 18); + let (first_a, n_a) = owned_pages(a, bytes, pc_tiles).unwrap(); + let (first_b, _) = owned_pages(b, bytes, pc_tiles).unwrap(); + assert_eq!((first_a, n_a), (a, 5)); + assert!(first_a + n_a * PAGE <= first_b, "the first texture's pages end before the second's"); + // as it was: every tile on the title's pages + let (_, all) = owned_pages(a, None, pc_tiles).unwrap(); + assert!(a + all * PAGE > b); + // a 2D texture's size is the caller's to know + assert_eq!(least_volume_bytes(&D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, ..desc }), None); + } + /// Reserved only with TILED support, and for MSAA a tiled sample count (#940: the driver /// refused R32G8X24_TYPELESS reserved, at 1 and 4 samples, and the debug layer said so). #[test] From ca427a52b4169c9e27cede92b4e8eb35fe0fcf57 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:35:30 +0100 Subject: [PATCH 189/258] D3D12.X / KernelX: fix Window-3 buffer_delta UAV corruption, depth_uav two-plane sync, dispatch_chain RS cache, late UMA free, and pso_async wait --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 84 ++- crates/xcl/src/hle/d3d12x/console_heap.rs | 571 ++++++++++++--- crates/xcl/src/hle/d3d12x/console_list.rs | 37 +- crates/xcl/src/hle/d3d12x/depth_uav.rs | 411 ++++++++++- crates/xcl/src/hle/d3d12x/late_release.rs | 112 ++- crates/xcl/src/hle/d3d12x/list_x.rs | 16 +- crates/xcl/src/hle/d3d12x/pso_async.rs | 668 +++++++++++++++++- crates/xcl/src/hle/d3d12x/real.rs | 609 ++++++++++++++-- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 535 ++++++++++++-- crates/xcl/src/hle/d3d12x/sparse.rs | 444 +++++++++--- crates/xcl/src/hle/d3d12x/vram.rs | 46 +- crates/xcl/src/hle/kernelx.rs | 40 +- 12 files changed, 3212 insertions(+), 361 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index b3124a95c5..0368c4898b 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -329,7 +329,7 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { enum Action { CleanPrimary { aside: Vec }, ResetCurrent { cur: usize, aside: Vec }, - SwapReuse { cur: usize, spare: usize, needs_reset: bool, aside: Vec }, + SwapReuse { cur: usize, owner: usize, spare: usize, needs_reset: bool, aside: Vec }, SwapNew { cur: usize, ty: i32, aside: Vec }, } let action = { @@ -349,13 +349,30 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { } } else { let ty = *s.types.get(&a)?; - let reuse_idx = s.aside.get(&a).and_then(|v| v.iter().position(|f| s.backings.get(f).is_none_or(|b| b.free()))); - match reuse_idx { - Some(idx) => { - let spare = s.aside.get_mut(&a).unwrap().remove(idx); + let reuse = s + .aside + .get(&a) + .and_then(|v| v.iter().position(|f| s.backings.get(f).is_none_or(|b| b.free()))) + .map(|idx| (a, idx)) + // … also one another title allocator of the type put aside: a title that resets many + // allocators while lists hold their recordings would otherwise make a PC allocator for each, + // and keep it (only one made here: the title's own allocator goes with the title's Release) + .or_else(|| { + s.aside + .iter() + .filter(|(o, _)| **o != a && s.types.get(o) == Some(&ty)) + .find_map(|(o, v)| { + v.iter() + .position(|f| f != o && s.backings.get(f).is_none_or(|b| b.free())) + .map(|idx| (*o, idx)) + }) + }); + match reuse { + Some((owner, idx)) => { + let spare = s.aside.get_mut(&owner).unwrap().remove(idx); let needs_reset = s.backings.get(&spare).is_none_or(|b| !b.already_reset); let aside = take_free_aside(s, a); - Action::SwapReuse { cur: c, spare, needs_reset, aside } + Action::SwapReuse { cur: c, owner, spare, needs_reset, aside } } None => { let aside = take_free_aside(s, a); @@ -409,14 +426,14 @@ pub unsafe fn title_reset(alloc: *mut c_void) -> Option { finish_aside(aside); Some(hr) } - Action::SwapReuse { cur, spare, needs_reset, aside } => { + Action::SwapReuse { cur, owner, spare, needs_reset, aside } => { let hr = if needs_reset { super::real::reset_pc_allocator(spare as *mut c_void) } else { 0 }; let mut orphan = None; { let mut g = STATE.lock().unwrap(); if let Some(s) = g.as_mut() { if hr < 0 { - if !restore_aside(s, a, spare, false) && spare != a { + if !restore_aside(s, owner, spare, false) && spare != owner { orphan = Some(spare); } } else { @@ -525,9 +542,21 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu } let ty = *s.types.get(&a)?; // one put aside earlier that nothing uses any more, or a new one - let reuse = s.aside.get(&a).and_then(|v| v.iter().copied().find(|f| s.backings.get(f).is_none_or(|b| b.free()))); + let reuse = s + .aside + .get(&a) + .and_then(|v| v.iter().copied().find(|f| s.backings.get(f).is_none_or(|b| b.free()))) + .map(|f| (a, f)); + // … also one another title allocator of the type put aside: a title that resets many + // allocators while lists hold their recordings would otherwise make a PC allocator for each, + // and keep it (only one made here: the title's own allocator goes with the title's Release) + let reuse = reuse.or_else(|| { + s.aside.iter().filter(|(o, _)| **o != a && s.types.get(o) == Some(&ty)).find_map(|(o, v)| { + v.iter().copied().find(|f| f != o && s.backings.get(f).is_none_or(|b| b.free())).map(|f| (*o, f)) + }) + }); let next = match reuse { - Some(f) => { + Some((owner, f)) => { let needs = s.backings.get(&f).is_none_or(|b| !b.already_reset); if needs { // Keep ownership until Reset succeeds so a failure can be retried. @@ -536,7 +565,7 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu return Some(hr); } } - s.aside.get_mut(&a).unwrap().retain(|&x| x != f); + s.aside.get_mut(&owner).unwrap().retain(|&x| x != f); if let Some(b) = s.backings.get_mut(&f) { b.marks.clear(); b.already_reset = true; @@ -616,6 +645,39 @@ mod tests { assert_eq!((s.made, s.swaps), (0, 1)); } + /// A title allocator that has no free one of its own takes one another of the type put aside, + /// but never another title allocator itself, nor one still in use, nor one of another type. + #[test] + fn a_free_spare_another_title_allocator_put_aside_is_taken() { + let (a, b, c, list) = (0x1000usize, 0x4000usize, 0x6000usize, 0x3000usize); + let (spare_b, busy_c, other_type) = (0x5000usize, 0x7000usize, 0x8000usize); + let mut s = State::default(); + s.types.insert(a, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.types.insert(b, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.types.insert(c, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.types.insert(0x9000, D3D12_COMMAND_LIST_TYPE_COMPUTE.0); + move_list(&mut s, list, a); + s.aside.insert(b, vec![b, spare_b]); + s.aside.insert(c, vec![busy_c]); + s.aside.insert(0x9000, vec![other_type]); + move_list(&mut s, 0x7100, busy_c); + let mut calls = Vec::new(); + let hr = unsafe { + title_reset_in(&mut s, a as *mut c_void, |raw| { + calls.push(raw as usize); + 0 + }) + }; + assert_eq!(hr, Some(0)); + assert_eq!(calls, vec![spare_b]); + assert_eq!(s.cur.get(&a), Some(&spare_b)); + assert_eq!(s.aside.get(&b), Some(&vec![b]), "the title's own allocator stays with it"); + assert_eq!(s.aside.get(&a), Some(&vec![a])); + assert_eq!((s.made, s.swaps), (0, 1)); + // (now a's: it goes with a, not with b) + assert!(!s.aside.values().flatten().any(|&f| f == spare_b)); + } + /// Final-release cleanup drops only the recording's hold: another live list and a pending /// GPU fence each still prevent reuse, then completion makes the backing reusable. #[test] diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 59e1b97ed4..ff64e8c11c 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -76,6 +76,106 @@ impl Heap { static HEAPS: RwLock> = RwLock::new(Vec::new()); +/// Active destination descriptor leases for lock-free `CopyDescriptorsSimple` calls and any +/// freed ranges whose return to `free` is deferred until overlapping copies complete. +#[derive(Default)] +struct LeasePool { + leased: Vec<(u32, u32)>, + deferred: Vec<(u32, u32)>, +} + +fn ranges_overlap(a: (u32, u32), b: (u32, u32)) -> bool { + a.0 < b.0.saturating_add(b.1) && b.0 < a.0.saturating_add(a.1) +} + +impl LeasePool { + fn acquire(&mut self, first: u32, count: u32) { + if count > 0 { + self.leased.push((first, count)); + } + } + + fn release_or_defer(&mut self, free: &mut Vec<(u32, u32)>, first: u32, count: u32) -> bool { + if self.leased.iter().any(|&l| ranges_overlap(l, (first, count))) { + self.deferred.push((first, count)); + false + } else { + merge_release(free, first, count); + true + } + } + + fn end_leases(&mut self, free: &mut Vec<(u32, u32)>, ranges: &[(u32, u32)]) -> bool { + for &r in ranges { + if let Some(i) = self.leased.iter().position(|&x| x == r) { + self.leased.swap_remove(i); + } + } + let mut promoted = false; + let mut i = 0; + while i < self.deferred.len() { + let r = self.deferred[i]; + if !self.leased.iter().any(|&l| ranges_overlap(l, r)) { + self.deferred.swap_remove(i); + merge_release(free, r.0, r.1); + promoted = true; + } else { + i += 1; + } + } + promoted + } +} + +struct SingleLease { + sampler: bool, + first: u32, + count: u32, +} + +impl Drop for SingleLease { + fn drop(&mut self) { + if self.count == 0 { + return; + } + if self.sampler { + if let Some(s) = GLOBAL_SAMPLER.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + if s.leases.end_leases(&mut s.free, &[(self.first, self.count)]) { + s.smallest_failed = u32::MAX; + } + } + } else if let Some(s) = GLOBAL.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + if s.leases.end_leases(&mut s.free, &[(self.first, self.count)]) { + s.smallest_failed = u32::MAX; + } + } + } +} + +struct RangeLease { + sampler: bool, + ranges: Vec<(u32, u32)>, +} + +impl Drop for RangeLease { + fn drop(&mut self) { + if self.ranges.is_empty() { + return; + } + if self.sampler { + if let Some(s) = GLOBAL_SAMPLER.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + if s.leases.end_leases(&mut s.free, &self.ranges) { + s.smallest_failed = u32::MAX; + } + } + } else if let Some(s) = GLOBAL.write().unwrap_or_else(|e| e.into_inner()).as_mut() { + if s.leases.end_leases(&mut s.free, &self.ranges) { + s.smallest_failed = u32::MAX; + } + } + } +} + /// Released descriptor range in `GLOBAL` or `GLOBAL_SAMPLER` awaiting active GPU queues before /// being returned to `free` (prevents overwriting shader-visible descriptors still read in flight). struct RetiredRange { @@ -88,6 +188,7 @@ struct RetiredRange { fn drain_retired_ranges( retired: &mut VecDeque>, free: &mut Vec<(u32, u32)>, + leases: &mut LeasePool, mut completed: impl FnMut(&F) -> u64, ) -> bool { let mut drained = false; @@ -96,8 +197,9 @@ fn drain_retired_ranges( .is_some_and(|r| r.marks.as_ref().is_some_and(|m| m.iter().all(|(f, v)| completed(f) >= *v))) { if let Some(r) = retired.pop_front() { - merge_release(free, r.first, r.count); - drained = true; + if leases.release_or_defer(free, r.first, r.count) { + drained = true; + } } } drained @@ -162,6 +264,7 @@ struct Global { free: Vec<(u32, u32)>, /// released ranges awaiting live GPU queue completion before entering `free` retired: VecDeque>, + leases: LeasePool, /// smallest allocation size that recently failed on a full/fragmented heap (`u32::MAX` = none) smallest_failed: u32, } @@ -273,6 +376,7 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), retired: VecDeque::new(), + leases: LeasePool::default(), smallest_failed: u32::MAX, }); } @@ -367,7 +471,7 @@ unsafe fn set_window_views_checked(dev: &ID3D12Device, windows: &[(usize, usize) fn reserve_global(count: u32) -> Option { let mut g = GLOBAL.write().unwrap(); let s = g.as_mut()?; - if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) } { + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, &mut s.leases, |f| f.GetCompletedValue()) } { s.smallest_failed = u32::MAX; } if count >= s.smallest_failed { @@ -408,7 +512,8 @@ fn page_of(h: &Heap, k: u32) -> Option<(u32, u32)> { } /// The shared range starting at `first` (`count` descriptors) is quarantined behind active GPU -/// queues before returning to `free`, preventing overwrites of live shader-visible descriptors. +/// queues (and any in-flight `publish` / `publish_range` destination leases) before returning to +/// `free`, preventing overwrites of live shader-visible descriptors. pub fn release_global(first: u32, count: u32) { if count == 0 { return; @@ -418,12 +523,13 @@ pub fn release_global(first: u32, count: u32) { let marks = unsafe { signal_live_queues_for(&dev) }; if let Some(s) = GLOBAL.write().unwrap().as_mut() { if marks.as_ref().is_some_and(Vec::is_empty) { - merge_release(&mut s.free, first, count); - s.smallest_failed = u32::MAX; + if s.leases.release_or_defer(&mut s.free, first, count) { + s.smallest_failed = u32::MAX; + } } else { s.retired.push_back(RetiredRange { first, count, marks }); } - if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) } { + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, &mut s.leases, |f| f.GetCompletedValue()) } { s.smallest_failed = u32::MAX; } } @@ -544,29 +650,39 @@ pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: /// The heap object was released for good: its slots go back to unified memory. pub fn unregister(obj: usize) { - let gone = { - let mut heaps = HEAPS.write().unwrap(); - heaps.iter().position(|h| h.obj == obj).map(|i| heaps.remove(i)) - }; - if let Some(h) = gone { - for (p, f) in h.pages.iter().enumerate().map(|(p, a)| (p, a.load(Ordering::Relaxed))).filter(|&(_, f)| f != UNMAPPED) { - if h.sampler { - release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); - } else { - release_global(f, page_descriptors(h.n, p as u32)); - } + if let Some(h) = take(obj) { + free(h); + } +} + +/// A heap `take` removed: `free` gives its slots and shadow memory back. +pub struct Taken(Heap); + +/// `unregister`'s first half: the heap is no longer found by its object's address. +pub fn take(obj: usize) -> Option { + let mut heaps = HEAPS.write().unwrap(); + heaps.iter().position(|h| h.obj == obj).map(|i| Taken(heaps.remove(i))) +} + +/// `unregister`'s second half. +pub fn free(Taken(h): Taken) { + for (p, f) in h.pages.iter().enumerate().map(|(p, a)| (p, a.load(Ordering::Relaxed))).filter(|&(_, f)| f != UNMAPPED) { + if h.sampler { + release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); + } else { + release_global(f, page_descriptors(h.n, p as u32)); } - match h.memory { - Memory::Sparse => { - unsafe { super::sparse::free(h.shadow) }; - } - Memory::Uma => { - if let Some(u) = crate::gpu::uma::get() { - u.free(h.shadow); - } + } + match h.memory { + Memory::Sparse => { + unsafe { super::sparse::free(h.shadow) }; + } + Memory::Uma => { + if let Some(u) = crate::gpu::uma::get() { + u.free(h.shadow); } - Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) }, } + Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) }, } } @@ -649,58 +765,123 @@ pub unsafe fn publish(s: &Slot, uav: bool) { return; } if s.sampler { - let dev = GLOBAL_SAMPLER.read().unwrap().as_ref().map(|g| g.dev.clone()); - if let Some(dev) = dev { - dev.CopyDescriptorsSimple( - 1, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - ); - } + let Some((dev, lease)) = GLOBAL_SAMPLER.write().unwrap().as_mut().map(|g| { + let lease = if g.inc > 0 && s.shared_srv >= g.cpu { + let idx = ((s.shared_srv - g.cpu) / g.inc as u64) as u32; + g.leases.acquire(idx, 1); + SingleLease { sampler: true, first: idx, count: 1 } + } else { + SingleLease { sampler: true, first: 0, count: 0 } + }; + (g.dev.clone(), lease) + }) else { + return; + }; + let _lease = lease; + dev.CopyDescriptorsSimple( + 1, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + ); return; } - let target = GLOBAL.read().unwrap().as_ref().map(|g| (g.dev.clone(), g.inc)); - if let Some((dev, inc)) = target { - let (dst, src) = if uav { (s.shared_srv + inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) }; - dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - } + let Some((dev, dst, src, lease)) = GLOBAL.write().unwrap().as_mut().map(|g| { + let (dst, src) = if uav { (s.shared_srv + g.inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) }; + let lease = if g.inc > 0 && dst >= g.cpu { + let idx = ((dst - g.cpu) / g.inc as u64) as u32; + g.leases.acquire(idx, 1); + SingleLease { sampler: false, first: idx, count: 1 } + } else { + SingleLease { sampler: false, first: 0, count: 0 } + }; + (g.dev.clone(), dst, src, lease) + }) else { + return; + }; + let _lease = lease; + dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); } /// `n` view or sampler slots from `first` were copied (in the title's heap): they go to the shared heap, -/// a run per page (a heap's pages lie apart there). +/// a run per page (a heap's pages lie apart there), clamped to the heap's bounds. pub unsafe fn publish_range(first: &Slot, n: u32) { + if n == 0 { + return; + } + let mul = if first.sampler { 1u32 } else { 2u32 }; let page_slots = if first.sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; - let step = if first.sampler { SAMPLER_SLOT } else { SLOT }; - let dev = if first.sampler { - GLOBAL_SAMPLER.read().unwrap().as_ref().map(|g| g.dev.clone()) - } else { - GLOBAL.read().unwrap().as_ref().map(|g| g.dev.clone()) - }; - let Some(dev) = dev else { return }; - let mut done = 0; - while done < n { - let s = if done == 0 { Some(*first) } else { slot((first.at + (done * step) as usize) as u64) }; - let Some(s) = s else { return }; - let run = (page_slots - s.k % page_slots).min(n - done); - if s.shared_srv != 0 { - if s.sampler { - dev.CopyDescriptorsSimple( - run, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - ); - } else { - dev.CopyDescriptorsSimple( - 2 * run, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - ); + let mut runs: Vec<(u32, u64, u32)> = Vec::new(); + let mut leased_ranges: Vec<(u32, u32)> = Vec::new(); + // Hold `HEAPS` while acquiring leases under `GLOBAL*` (strict `HEAPS -> GLOBAL*` lock order) + // so `unregister` cannot release and recycle these destination ranges before the leases exist. + let (dev, g_cpu, g_inc) = { + let heaps = HEAPS.read().unwrap(); + let mut standalone: Option<(u64, u64, u32)> = None; + if let Some(h) = find_heap_by_addr(&heaps, first.at as u64).filter(|h| h.sampler == first.sampler) { + let start_k = ((first.at - h.shadow) / h.slot_bytes() as usize) as u32; + let limit = n.min(h.n.saturating_sub(start_k)); + let mut done = 0u32; + while done < limit { + let k = start_k + done; + let run = (page_slots - k % page_slots).min(limit - done); + let page = if h.sampler { sampler_page_of(h, k) } else { page_of(h, k) }; + if let Some((first_idx, k0)) = page { + let dst_idx = first_idx + mul * (k - k0); + let src = h.pc_cpu + (mul as u64 * k as u64) * h.inc as u64; + runs.push((dst_idx, src, mul * run)); + } + done += run; } + } else if first.shared_srv != 0 { + let run = (page_slots - first.k % page_slots).min(n); + standalone = Some((first.shared_srv, first.pc_srv, mul * run)); } - done += run; + if runs.is_empty() && standalone.is_none() { + return; + } + let snap = if first.sampler { + GLOBAL_SAMPLER.write().unwrap().as_mut().map(|g| { + if let Some((dst_ptr, src, cnt)) = standalone { + if g.inc > 0 && dst_ptr >= g.cpu { + runs.push((((dst_ptr - g.cpu) / g.inc as u64) as u32, src, cnt)); + } + } + for &(idx, _, cnt) in &runs { + g.leases.acquire(idx, cnt); + leased_ranges.push((idx, cnt)); + } + (g.dev.clone(), g.cpu, g.inc) + }) + } else { + GLOBAL.write().unwrap().as_mut().map(|g| { + if let Some((dst_ptr, src, cnt)) = standalone { + if g.inc > 0 && dst_ptr >= g.cpu { + runs.push((((dst_ptr - g.cpu) / g.inc as u64) as u32, src, cnt)); + } + } + for &(idx, _, cnt) in &runs { + g.leases.acquire(idx, cnt); + leased_ranges.push((idx, cnt)); + } + (g.dev.clone(), g.cpu, g.inc) + }) + }; + let Some(snap) = snap else { + return; + }; + snap + }; + let _lease = RangeLease { sampler: first.sampler, ranges: leased_ranges }; + let heap_ty = if first.sampler { D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER } else { D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV }; + for (dst_idx, src, count) in runs { + let dst = g_cpu + (dst_idx as u64) * (g_inc as u64); + dev.CopyDescriptorsSimple( + count, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, + heap_ty, + ); } } @@ -949,6 +1130,7 @@ struct GlobalSampler { next: u32, free: Vec<(u32, u32)>, retired: VecDeque>, + leases: LeasePool, smallest_failed: u32, } @@ -1018,6 +1200,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { next: 1, free: Vec::new(), retired: VecDeque::new(), + leases: LeasePool::default(), smallest_failed: u32::MAX, }); } @@ -1027,7 +1210,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { fn reserve_global_sampler(count: u32) -> Option { let mut g = GLOBAL_SAMPLER.write().unwrap(); let s = g.as_mut()?; - if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) } { + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, &mut s.leases, |f| f.GetCompletedValue()) } { s.smallest_failed = u32::MAX; } if count >= s.smallest_failed { @@ -1073,12 +1256,13 @@ fn release_global_sampler(first: u32, count: u32) { let marks = unsafe { signal_live_queues_for(&dev) }; if let Some(s) = GLOBAL_SAMPLER.write().unwrap().as_mut() { if marks.as_ref().is_some_and(Vec::is_empty) { - merge_release(&mut s.free, first, count); - s.smallest_failed = u32::MAX; + if s.leases.release_or_defer(&mut s.free, first, count) { + s.smallest_failed = u32::MAX; + } } else { s.retired.push_back(RetiredRange { first, count, marks }); } - if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, |f| f.GetCompletedValue()) } { + if unsafe { drain_retired_ranges(&mut s.retired, &mut s.free, &mut s.leases, |f| f.GetCompletedValue()) } { s.smallest_failed = u32::MAX; } } @@ -1194,7 +1378,7 @@ mod tests { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, - next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), retired: VecDeque::new(), smallest_failed: u32::MAX, + next: crate::gpu::recomp::MEM_HEAP_NULL + 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX, }); let window = (&mut resource as *mut _ as usize, 0x10000); assert!(set_window_views_checked(&dev, &[window], true)); @@ -1389,7 +1573,7 @@ mod tests { *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), - cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), smallest_failed: u32::MAX, + cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX, }); assert_eq!(reserve_global_sampler(4), Some(1)); assert_eq!(reserve_global_sampler(4), Some(5)); @@ -1449,12 +1633,12 @@ mod tests { *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), - cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), retired: VecDeque::new(), smallest_failed: u32::MAX, + cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX, }); *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), - cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), smallest_failed: u32::MAX, + cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX, }); if crate::gpu::uma::get().is_some() { assert!(register(0xC100, 16, 0x9000, 0, 16, true, true, true)); @@ -1523,24 +1707,25 @@ mod tests { let f2 = Arc::new(AtomicU64::new(0)); let mut retired: VecDeque>> = VecDeque::new(); let mut free: Vec<(u32, u32)> = Vec::new(); + let mut leases = LeasePool::default(); retired.push_back(RetiredRange { first: 64, count: 16, marks: Some(vec![(f1.clone(), 1), (f2.clone(), 1)]) }); retired.push_back(RetiredRange { first: 80, count: 16, marks: Some(vec![(f1.clone(), 2), (f2.clone(), 1)]) }); retired.push_back(RetiredRange { first: 96, count: 16, marks: None }); // While f2 is still pending, neither range may re-enter `free`. f1.store(1, Ordering::SeqCst); - drain_retired_ranges(&mut retired, &mut free, |f| f.load(Ordering::SeqCst)); + drain_retired_ranges(&mut retired, &mut free, &mut leases, |f| f.load(Ordering::SeqCst)); assert!(free.is_empty() && retired.len() == 3); // Once both queues pass mark 1, only range 1 returns; range 2 waits for f1 == 2. f2.store(1, Ordering::SeqCst); - drain_retired_ranges(&mut retired, &mut free, |f| f.load(Ordering::SeqCst)); + drain_retired_ranges(&mut retired, &mut free, &mut leases, |f| f.load(Ordering::SeqCst)); assert_eq!(free, vec![(64, 16)]); assert_eq!(retired.len(), 2); // Passing mark 2 coalesces [80, 96) with [64, 80); failed-signal range stays quarantined. f1.store(2, Ordering::SeqCst); - drain_retired_ranges(&mut retired, &mut free, |f| f.load(Ordering::SeqCst)); + drain_retired_ranges(&mut retired, &mut free, &mut leases, |f| f.load(Ordering::SeqCst)); assert_eq!(free, vec![(64, 32)]); assert_eq!(retired.len(), 1); } @@ -1569,4 +1754,228 @@ mod tests { unregister(0xD100); unregister(0xD101); } + + #[test] + fn publish_and_publish_range_do_not_hold_locks_during_device_calls() { + const CHILD: &str = "XCL_TEST_PUBLISH_LOCKS_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::publish_and_publish_range_do_not_hold_locks_during_device_calls", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, Ordering}; + static UNLOCKED: AtomicBool = AtomicBool::new(true); + static CALLS: Mutex> = Mutex::new(Vec::new()); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn copy_simple(_this: *mut c_void, n: u32, dst: D3D12_CPU_DESCRIPTOR_HANDLE, src: D3D12_CPU_DESCRIPTOR_HANDLE, ty: D3D12_DESCRIPTOR_HEAP_TYPE) { + let ok = GLOBAL.try_write().is_ok() && GLOBAL_SAMPLER.try_write().is_ok() && HEAPS.try_write().is_ok(); + UNLOCKED.fetch_and(ok, Ordering::Relaxed); + CALLS.lock().unwrap().push((n, dst.ptr as u64, src.ptr as u64, ty.0)); + } + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + vt[24] = copy_simple as usize; + let (mut device, mut vheap, mut sheap) = (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let view_shadow = vec![0u8; (260 * SLOT) as usize]; + let samp_shadow = vec![0u8; (12 * SAMPLER_SLOT) as usize]; + unsafe { + let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); + *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut vheap as *mut _ as *mut c_void), cpu: 0x10_0000, gpu: 0x18_0000, inc: 32, cap: 4096, next: 64, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sheap as *mut _ as *mut c_void), cpu: 0x20_0000, inc: 16, cap: 256, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + { + let mut heaps = HEAPS.write().unwrap(); + heaps.push(Heap { obj: 0xA1, shadow: view_shadow.as_ptr() as usize, n: 260, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: (0..2).map(|_| AtomicU32::new(UNMAPPED)).collect(), visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xA2, shadow: samp_shadow.as_ptr() as usize, n: 12, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: (0..2).map(|_| AtomicU32::new(UNMAPPED)).collect(), visible: true, memory: Memory::Uma }); + heaps.sort_by_key(|h| h.shadow); + } + let vs = slot(view_shadow.as_ptr() as u64).unwrap(); + let ss = slot(samp_shadow.as_ptr() as u64).unwrap(); + publish(&vs, false); + publish(&vs, true); + publish(&ss, false); + let v250 = slot(view_shadow.as_ptr() as u64 + (250 * SLOT) as u64).unwrap(); + publish_range(&v250, 10); + let s6 = slot(samp_shadow.as_ptr() as u64 + (6 * SAMPLER_SLOT) as u64).unwrap(); + publish_range(&s6, 6); + HEAPS.write().unwrap().clear(); + *GLOBAL_SAMPLER.write().unwrap() = None; + *GLOBAL.write().unwrap() = None; + } + assert!(UNLOCKED.load(Ordering::Relaxed), "CopyDescriptorsSimple ran while GLOBAL, GLOBAL_SAMPLER, or HEAPS was locked"); + let calls = CALLS.lock().unwrap(); + assert_eq!(calls.len(), 7, "3 single publish + 2 view pages + 2 sampler pages"); + assert_eq!(calls[0], (1, 0x10_0000 + 64 * 32, 0x30_0000, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0)); + assert_eq!(calls[1], (1, 0x10_0000 + 65 * 32, 0x30_0000 + 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0)); + assert_eq!(calls[2], (1, 0x20_0000 + 16, 0x40_0000, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0)); + assert_eq!(calls[3], (12, 0x10_0000 + (64 + 500) * 32, 0x30_0000 + 500 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0)); + assert_eq!(calls[4], (8, 0x10_0000 + (64 + 512) * 32, 0x30_0000 + 512 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0)); + assert_eq!(calls[5], (2, 0x20_0000 + 7 * 16, 0x40_0000 + 6 * 16, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0)); + assert_eq!(calls[6], (4, 0x20_0000 + 9 * 16, 0x40_0000 + 8 * 16, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0)); + } + + #[test] + fn publish_range_clamps_to_heap_bounds_without_overrunning_tail_pages() { + const CHILD: &str = "XCL_TEST_PUBLISH_BOUNDS_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::publish_range_clamps_to_heap_bounds_without_overrunning_tail_pages", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + static CALLS: Mutex> = Mutex::new(Vec::new()); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn copy_simple(_this: *mut c_void, n: u32, dst: D3D12_CPU_DESCRIPTOR_HANDLE, src: D3D12_CPU_DESCRIPTOR_HANDLE, ty: D3D12_DESCRIPTOR_HEAP_TYPE) { + CALLS.lock().unwrap().push((n, dst.ptr as u64, src.ptr as u64, ty.0)); + } + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + vt[24] = copy_simple as usize; + let (mut device, mut vheap, mut sheap) = (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let v4_shadow = vec![0u8; (4 * SLOT) as usize]; + let s3_shadow = vec![0u8; (3 * SAMPLER_SLOT) as usize]; + let v260_shadow = vec![0u8; (260 * SLOT) as usize]; + unsafe { + let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); + *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut vheap as *mut _ as *mut c_void), cpu: 0x10_0000, gpu: 0x18_0000, inc: 32, cap: 4096, next: 64, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sheap as *mut _ as *mut c_void), cpu: 0x20_0000, inc: 16, cap: 256, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + { + let mut heaps = HEAPS.write().unwrap(); + heaps.push(Heap { obj: 0xB1, shadow: v4_shadow.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xB2, shadow: s3_shadow.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xB3, shadow: v260_shadow.as_ptr() as usize, n: 260, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, pages: (0..2).map(|_| AtomicU32::new(UNMAPPED)).collect(), visible: true, memory: Memory::Uma }); + heaps.sort_by_key(|h| h.shadow); + } + let v4_s1 = slot(v4_shadow.as_ptr() as u64 + SLOT as u64).unwrap(); + publish_range(&v4_s1, 0); + publish_range(&v4_s1, 10); + let s3_s1 = slot(s3_shadow.as_ptr() as u64 + SAMPLER_SLOT as u64).unwrap(); + publish_range(&s3_s1, 10); + let v260_s250 = slot(v260_shadow.as_ptr() as u64 + (250 * SLOT) as u64).unwrap(); + publish_range(&v260_s250, 20); + HEAPS.write().unwrap().clear(); + *GLOBAL_SAMPLER.write().unwrap() = None; + *GLOBAL.write().unwrap() = None; + } + let calls = CALLS.lock().unwrap(); + assert_eq!( + *calls, + vec![ + // 4-slot view heap (allocated 64..72): k=1..4 => 6 descriptors (ending at 72, 0 overrun) + (6, 0x10_0000 + 66 * 32, 0x30_0000 + 2 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + // 3-slot sampler heap (allocated 1..4): k=1..3 => 2 descriptors (ending at 4, 0 overrun) + (2, 0x20_0000 + 2 * 16, 0x40_0000 + 16, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0), + // 260-slot view heap: page 0 (72..584) k=250..256 => 12 descs; tail page 1 (584..592) k=256..260 => 8 descs + (12, 0x10_0000 + (72 + 500) * 32, 0x50_0000 + 500 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + (8, 0x10_0000 + 584 * 32, 0x50_0000 + 512 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + ], + "publish_range must clamp strictly to heap bounds with 0 tail-page overrun" + ); + } + + #[test] + fn publish_leases_prevent_unregister_range_reuse_while_copy_in_flight() { + const CHILD: &str = "XCL_TEST_PUBLISH_LEASES_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::publish_leases_prevent_unregister_range_reuse_while_copy_in_flight", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + use std::sync::{Arc, Barrier, OnceLock}; + static GATE: OnceLock<(Arc, Arc)> = OnceLock::new(); + static LOCKS_FREE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn blocking_copy(_this: *mut c_void, _n: u32, _dst: D3D12_CPU_DESCRIPTOR_HANDLE, _src: D3D12_CPU_DESCRIPTOR_HANDLE, _ty: D3D12_DESCRIPTOR_HEAP_TYPE) { + let ok = GLOBAL.try_write().is_ok() && GLOBAL_SAMPLER.try_write().is_ok() && HEAPS.try_write().is_ok(); + LOCKS_FREE.fetch_and(ok, std::sync::atomic::Ordering::Relaxed); + let (entered, release) = GATE.get().unwrap(); + entered.wait(); + release.wait(); + } + let entered = Arc::new(Barrier::new(2)); + let release = Arc::new(Barrier::new(2)); + GATE.set((entered.clone(), release.clone())).ok(); + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + vt[24] = blocking_copy as usize; + let (mut device, mut vheap, mut sheap) = (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let v1_shadow = vec![0u8; (4 * SLOT) as usize]; + let v2_shadow = vec![0u8; (4 * SLOT) as usize]; + let s1_shadow = vec![0u8; (3 * SAMPLER_SLOT) as usize]; + unsafe { + let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); + *GLOBAL.write().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut vheap as *mut _ as *mut c_void), cpu: 0x10_0000, gpu: 0x18_0000, inc: 32, cap: 4096, next: 64, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + *GLOBAL_SAMPLER.write().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sheap as *mut _ as *mut c_void), cpu: 0x20_0000, inc: 16, cap: 256, next: 1, free: Vec::new(), retired: VecDeque::new(), leases: LeasePool::default(), smallest_failed: u32::MAX }); + { + let mut heaps = HEAPS.write().unwrap(); + heaps.push(Heap { obj: 0xD1, shadow: v1_shadow.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xD2, shadow: v2_shadow.as_ptr() as usize, n: 4, pc_cpu: 0x31_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.push(Heap { obj: 0xD3, shadow: s1_shadow.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![AtomicU32::new(UNMAPPED)], visible: true, memory: Memory::Uma }); + heaps.sort_by_key(|h| h.shadow); + } + // 1. Single `publish` holds a lease until CopyDescriptorsSimple returns. + let vs1 = slot(v1_shadow.as_ptr() as u64).unwrap(); + assert_eq!(vs1.index, 64); + let t1 = std::thread::spawn(move || publish(&vs1, false)); + entered.wait(); + unregister(0xD1); + let new_v = reserve_global(8).unwrap(); + assert!(!ranges_overlap((new_v, 8), (64, 8)), "new heap reused leased publish range [64, 72): got {new_v}"); + release.wait(); + t1.join().unwrap(); + assert_eq!(reserve_global(8), Some(64), "deferred view range must return to free once publish completes"); + release_global(64, 8); + + // 2. `publish_range` (view) holds leases across unregister and releases them on completion. + let vs2 = slot(v2_shadow.as_ptr() as u64).unwrap(); + assert_eq!(vs2.index, 64); + let t2 = std::thread::spawn(move || publish_range(&vs2, 4)); + entered.wait(); + unregister(0xD2); + let new_v2 = reserve_global(8).unwrap(); + assert!(!ranges_overlap((new_v2, 8), (64, 8)), "new heap reused leased publish_range view range [64, 72): got {new_v2}"); + release.wait(); + t2.join().unwrap(); + assert_eq!(reserve_global(8), Some(64), "deferred publish_range view range must return to free on completion"); + + // 3. `publish_range` (sampler) holds leases across unregister and releases them on completion. + let ss1 = slot(s1_shadow.as_ptr() as u64).unwrap(); + assert_eq!(ss1.index, 1); + let t3 = std::thread::spawn(move || publish_range(&ss1, 3)); + entered.wait(); + unregister(0xD3); + let new_s = reserve_global_sampler(3).unwrap(); + assert!(!ranges_overlap((new_s, 3), (1, 3)), "new sampler heap reused leased range [1, 4): got {new_s}"); + release.wait(); + t3.join().unwrap(); + assert_eq!(reserve_global_sampler(3), Some(1), "deferred sampler range must return to free on completion"); + + HEAPS.write().unwrap().clear(); + *GLOBAL_SAMPLER.write().unwrap() = None; + *GLOBAL.write().unwrap() = None; + } + assert!(LOCKS_FREE.load(std::sync::atomic::Ordering::Relaxed), "CopyDescriptorsSimple must still run with all locks released"); + } } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index bc50666e32..c5fb014b9e 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -915,7 +915,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let q = |k: usize| get(1 + 2 * k) as u64 | (get(2 + 2 * k) as u64) << 32; let (dst, src) = (q(0) as *mut c_void, q(2) as *mut c_void); if let (Some(d), Some(s)) = (ID3D12Resource::from_raw_borrowed(&dst), ID3D12Resource::from_raw_borrowed(&src)) { - list.CopyBufferRegion(d, q(1), s, q(3), q(4)); + let dst_off = q(1).saturating_add(super::real::buffer_delta(dst as usize)); + let src_off = q(3).saturating_add(super::real::buffer_delta(src as usize)); + list.CopyBufferRegion(d, dst_off, s, src_off, q(4)); out.copies += 1; } else { out.skipped += 1; @@ -926,20 +928,29 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let values = [get(8), get(9), get(10), get(11)]; let res = q(2) as *mut c_void; let (gpu, cpu) = (super::console_heap::slot(q(0)), super::console_heap::slot(q(1))); - match (gpu, cpu, ID3D12Resource::from_raw_borrowed(&res)) { - (Some(g), Some(c), Some(r)) if clear_uav_gpu_handle(&g, &c) != 0 => { - let gpu_uav = clear_uav_gpu_handle(&g, &c); - if g.shared_srv != 0 || (c.shared_srv != 0 && gpu_uav == c.pc_gpu_uav) { - ensure_uav_clear_heap(&list, &mut bound_heaps, &mut has_sampler_heap); - } - let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); - if get(1) != 0 { - let f = values.map(f32::from_bits); - list.ClearUnorderedAccessViewFloat(gh, ch, r, &f, &[]); + match (gpu, cpu) { + (Some(g), Some(c)) if clear_uav_gpu_handle(&g, &c) != 0 => { + if super::real::is_unaligned_delta_uav(c.pc_uav as usize) { + out.skipped += 1; } else { - list.ClearUnorderedAccessViewUint(gh, ch, r, &values, &[]); + let pc_res = super::depth_uav::twin_for_pc_uav(c.pc_uav as usize).map_or(res, |t| t as *mut c_void); + if let Some(r) = ID3D12Resource::from_raw_borrowed(&pc_res) { + let gpu_uav = clear_uav_gpu_handle(&g, &c); + if g.shared_srv != 0 || (c.shared_srv != 0 && gpu_uav == c.pc_gpu_uav) { + ensure_uav_clear_heap(&list, &mut bound_heaps, &mut has_sampler_heap); + } + let (gh, ch) = (D3D12_GPU_DESCRIPTOR_HANDLE { ptr: gpu_uav }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: c.pc_uav as usize }); + if get(1) != 0 { + let f = values.map(f32::from_bits); + list.ClearUnorderedAccessViewFloat(gh, ch, r, &f, &[]); + } else { + list.ClearUnorderedAccessViewUint(gh, ch, r, &values, &[]); + } + out.clears += 1; + } else { + out.skipped += 1; + } } - out.clears += 1; } _ => out.skipped += 1, } diff --git a/crates/xcl/src/hle/d3d12x/depth_uav.rs b/crates/xcl/src/hle/d3d12x/depth_uav.rs index 5ff66d5fe5..d5ad37aef2 100644 --- a/crates/xcl/src/hle/d3d12x/depth_uav.rs +++ b/crates/xcl/src/hle/d3d12x/depth_uav.rs @@ -292,6 +292,10 @@ static ENTRIES: Mutex>> = Mutex::new(None); static COUNT: AtomicUsize = AtomicUsize::new(0); /// DSV CPU handle -> `(resource raw pointer, D3D12_DSV_FLAGS)`. static DSV_TO_RES: Mutex>> = Mutex::new(None); +/// PC UAV CPU descriptor handle -> color twin `ID3D12Resource` raw pointer +/// (used to route `ClearUnorderedAccessViewUint/Float` onto the color twin). +static UAV_PC_TO_TWIN: Mutex>> = Mutex::new(None); +static UAV_TWIN_COUNT: AtomicUsize = AtomicUsize::new(0); /// Whether Depth+UAV color twins are enabled (`XCL_DEPTH_UAV_TWIN=0` turns them off). pub fn enabled() -> bool { @@ -334,8 +338,10 @@ pub(super) fn register_if_depth_uav(device: *mut c_void, res: *mut c_void, conso COUNT.fetch_add(1, Ordering::Relaxed); } static LOGGED: AtomicU64 = AtomicU64::new(0); + static LOGGED_TWO_PLANE: AtomicU64 = AtomicU64::new(0); let n = LOGGED.fetch_add(1, Ordering::Relaxed); - if n < 8 || n.is_power_of_two() { + let tp_n = if plan.two_plane { Some(LOGGED_TWO_PLANE.fetch_add(1, Ordering::Relaxed)) } else { None }; + if n < 8 || n.is_power_of_two() || tp_n.is_some_and(|k| k < 8 || k.is_power_of_two()) { crate::xlog_info!( "D3D12.X: tracked depth+UAV texture {res:p} ({width}x{height}x{array_size}, {mip_levels} mips, console fmt {console_fmt}, two_plane {}) for color-twin UAV sync ({} tracked)", plan.two_plane, @@ -361,6 +367,18 @@ pub(super) fn forget(res: usize) { if let Some(m) = DSV_TO_RES.lock().unwrap().as_mut() { m.retain(|_, &mut (v, _)| v != res); } + let d_twin = e.depth_twin.as_ref().map(|t| t.as_raw() as usize); + let s_twin = e.stencil_twin.as_ref().map(|t| t.as_raw() as usize); + if (d_twin.is_some() || s_twin.is_some()) && UAV_TWIN_COUNT.load(Ordering::Relaxed) != 0 { + if let Some(m) = UAV_PC_TO_TWIN.lock().unwrap().as_mut() { + let before = m.len(); + m.retain(|_, &mut t| Some(t) != d_twin && Some(t) != s_twin); + let removed_n = before - m.len(); + if removed_n > 0 { + UAV_TWIN_COUNT.fetch_sub(removed_n, Ordering::Relaxed); + } + } + } // Defer release of internal unadopted pass descriptor heaps until in-flight GPU work completes. unsafe { if let Some(h) = e.pass_dsv_heap.take() { @@ -388,6 +406,96 @@ pub(super) fn note_dsv(dsv_cpu: usize, res: usize, dsv_flags: u32) { } } +/// Propagate tracked DSV mappings across `CopyDescriptorsSimple` / `CopyDescriptors` on DSV heaps, +/// snapshotting source entries first so overlapping ranges copy safely. +pub(super) fn copy_dsv(dst_cpu: usize, src_cpu: usize, count: u32, inc: usize) { + if !any() || count == 0 || inc == 0 || dst_cpu == 0 || src_cpu == 0 || dst_cpu == src_cpu { + return; + } + let mut g = DSV_TO_RES.lock().unwrap(); + let Some(m) = g.as_mut() else { + return; + }; + if m.is_empty() { + return; + } + let n = count as usize; + let mut snap: Vec> = Vec::with_capacity(n); + for i in 0..n { + let Some(src) = i.checked_mul(inc).and_then(|off| src_cpu.checked_add(off)) else { + break; + }; + snap.push(m.get(&src).copied()); + } + for (i, entry) in snap.into_iter().enumerate() { + let Some(dst) = i.checked_mul(inc).and_then(|off| dst_cpu.checked_add(off)) else { + break; + }; + if let Some(v) = entry { + m.insert(dst, v); + } else { + m.remove(&dst); + } + } +} + +/// Record that PC UAV CPU handle `pc_uav` was routed to color twin resource `twin_res`. +pub(super) fn note_uav_twin(pc_uav: usize, twin_res: usize) { + if pc_uav == 0 { + return; + } + if twin_res == 0 { + clear_uav_twin(pc_uav); + return; + } + let mut g = UAV_PC_TO_TWIN.lock().unwrap(); + if g.get_or_insert_with(HashMap::new).insert(pc_uav, twin_res).is_none() { + UAV_TWIN_COUNT.fetch_add(1, Ordering::Relaxed); + } +} + +/// Clear any recorded color-twin mapping for PC UAV CPU handle `pc_uav`. +pub(super) fn clear_uav_twin(pc_uav: usize) { + if pc_uav == 0 || UAV_TWIN_COUNT.load(Ordering::Relaxed) == 0 { + return; + } + if let Some(m) = UAV_PC_TO_TWIN.lock().unwrap().as_mut() { + if m.remove(&pc_uav).is_some() { + UAV_TWIN_COUNT.fetch_sub(1, Ordering::Relaxed); + } + } +} + +/// Look up the color twin resource for a twinned PC UAV CPU handle (e.g. for +/// `ClearUnorderedAccessViewUint/Float`) and mark that twin dirty so subsequent DSV/SRV uses flush. +pub(super) fn twin_for_pc_uav(pc_uav: usize) -> Option { + if pc_uav == 0 || UAV_TWIN_COUNT.load(Ordering::Relaxed) == 0 { + return None; + } + let twin = UAV_PC_TO_TWIN.lock().unwrap().as_ref()?.get(&pc_uav).copied()?; + if any() { + if let Some(map) = ENTRIES.lock().unwrap().as_mut() { + for e in map.values_mut() { + if e.depth_twin.as_ref().is_some_and(|t| t.as_raw() as usize == twin) { + e.depth_twin_dirty = true; + if e.plan.two_plane { + e.depth_plane_dirty = false; + } + break; + } + if e.stencil_twin.as_ref().is_some_and(|t| t.as_raw() as usize == twin) { + e.stencil_twin_dirty = true; + if e.plan.two_plane { + e.stencil_plane_dirty = false; + } + break; + } + } + } + } + Some(twin) +} + unsafe fn create_twin_resource(device: *mut c_void, width: u64, height: u32, array_size: u16, mip_levels: u16, format: i32) -> Option { let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { @@ -442,7 +550,7 @@ pub(super) unsafe fn resolve_uav( let req_fmt = orig_desc.map_or(0, |d| d.Format.0 as u32); // Inspect plan and check whether the twin already exists before allocating outside the lock. - let (need_alloc, is_stencil, twin_fmt, width, height, array_size, mip_levels, device, existing_raw) = { + let (need_alloc, is_stencil, two_plane, twin_fmt, width, height, array_size, mip_levels, device, existing_raw) = { let g = ENTRIES.lock().unwrap(); let e = g.as_ref()?.get(&key)?; let stencil = e.plan.two_plane && is_stencil_uav_format(req_fmt, plane_slice); @@ -452,7 +560,7 @@ pub(super) unsafe fn resolve_uav( } else { e.depth_twin.as_ref().map(|r| r.as_raw()) }; - (existing.is_none(), stencil, twin_fmt, e.width, e.height, e.array_size, e.mip_levels, if dev.is_null() { e.device as *mut c_void } else { dev }, existing) + (existing.is_none(), stencil, e.plan.two_plane, twin_fmt, e.width, e.height, e.array_size, e.mip_levels, if dev.is_null() { e.device as *mut c_void } else { dev }, existing) }; let twin_raw = if let Some(raw) = existing_raw { @@ -500,10 +608,12 @@ pub(super) unsafe fn resolve_uav( } static ROUTED: AtomicU64 = AtomicU64::new(0); + static ROUTED_TWO_PLANE: AtomicU64 = AtomicU64::new(0); let n = ROUTED.fetch_add(1, Ordering::Relaxed); - if n < 8 || n.is_power_of_two() { + let tp_n = if two_plane { Some(ROUTED_TWO_PLANE.fetch_add(1, Ordering::Relaxed)) } else { None }; + if n < 8 || n.is_power_of_two() || tp_n.is_some_and(|k| k < 8 || k.is_power_of_two()) { crate::xlog_info!( - "D3D12.X: routed {} UAV of depth+UAV texture {res:p} (req fmt {req_fmt} -> twin fmt {patched_fmt}) to color twin {twin_raw:p} ({} routed)", + "D3D12.X: routed {} UAV of depth+UAV texture {res:p} (two_plane {two_plane}, req fmt {req_fmt} -> twin fmt {patched_fmt}) to color twin {twin_raw:p} ({} routed)", if is_stencil { "stencil" } else { "depth" }, n + 1 ); @@ -838,11 +948,17 @@ fn decide_enhanced_texture_barrier( if !is_direct { if uav_before || uav_after || common_before { - if !d_subs.is_empty() && e.depth_twin.is_some() && !e.depth_plane_dirty { + if !d_subs.is_empty() && e.depth_twin.is_some() && (e.plan.two_plane || !e.depth_plane_dirty) { e.depth_twin_dirty = true; + if e.plan.two_plane { + e.depth_plane_dirty = false; + } } - if !s_subs.is_empty() && e.stencil_twin.is_some() && !e.stencil_plane_dirty { + if !s_subs.is_empty() && e.stencil_twin.is_some() && (e.plan.two_plane || !e.stencil_plane_dirty) { e.stencil_twin_dirty = true; + if e.plan.two_plane { + e.stencil_plane_dirty = false; + } } } return None; @@ -921,8 +1037,14 @@ fn decide_enhanced_texture_barrier( // Neither before nor after explicitly names UAV. Flush dirty twins (including compute-only // twins transitioning out of COMMON access) unless discarded, and advance tracked PC state. - let flush_d = !discard_before && !d_subs.is_empty() && e.depth_twin.is_some() && (e.depth_twin_dirty || (common_before && !e.depth_plane_dirty)); - let flush_s = !discard_before && !s_subs.is_empty() && e.stencil_twin.is_some() && (e.stencil_twin_dirty || (common_before && !e.stencil_plane_dirty)); + let flush_d = !discard_before + && !d_subs.is_empty() + && e.depth_twin.is_some() + && (e.depth_twin_dirty || (common_before && (e.plan.two_plane || !e.depth_plane_dirty))); + let flush_s = !discard_before + && !s_subs.is_empty() + && e.stencil_twin.is_some() + && (e.stencil_twin_dirty || (common_before && (e.plan.two_plane || !e.stencil_plane_dirty))); let depth = collect_subs(&mut e.pc_states_depth, &d_subs, after_pc); let stencil = collect_subs(&mut e.pc_states_stencil, &s_subs, after_pc); if !d_subs.is_empty() { @@ -931,7 +1053,7 @@ fn decide_enhanced_texture_barrier( } if write_after { e.depth_plane_dirty = true; - } else if discard_before { + } else if discard_before || (flush_d && e.plan.two_plane) { e.depth_plane_dirty = false; } } @@ -941,7 +1063,7 @@ fn decide_enhanced_texture_barrier( } if write_after { e.stencil_plane_dirty = true; - } else if discard_before { + } else if discard_before || (flush_s && e.plan.two_plane) { e.stencil_plane_dirty = false; } } @@ -1047,15 +1169,23 @@ pub(super) unsafe fn filter_enhanced_barriers( had_global_uav } -/// Apply a global UAV barrier to a single entry: mark materialized twins dirty only when their -/// corresponding depth/stencil plane is not currently graphics-dirty (avoiding clobbering -/// graphics-rendered depth targets on unrelated global UAV barriers). +/// Apply a global UAV barrier to a single entry: mark materialized twins dirty. +/// For `two_plane` depth+UAV buffers (e.g. console `D16_UNORM_S8_UINT` material-mask buffers), +/// never let prior `DEPTH_WRITE` / `ClearDepthStencilView` (`depth_plane_dirty`) suppress twin +/// flushing; keep single-plane depth maps (e.g. `fmt 53` shadow maps) guarded by `!depth_plane_dirty` +/// so unrelated global UAV barriers do not clobber graphics-rendered shadow maps. fn mark_global_uav_dirty(e: &mut Entry) { - if e.depth_twin.is_some() && !e.depth_plane_dirty { + if e.depth_twin.is_some() && (e.plan.two_plane || !e.depth_plane_dirty) { e.depth_twin_dirty = true; + if e.plan.two_plane { + e.depth_plane_dirty = false; + } } - if e.stencil_twin.is_some() && !e.stencil_plane_dirty { + if e.stencil_twin.is_some() && (e.plan.two_plane || !e.stencil_plane_dirty) { e.stencil_twin_dirty = true; + if e.plan.two_plane { + e.stencil_plane_dirty = false; + } } } @@ -1089,6 +1219,9 @@ pub(super) fn on_uav_barrier(res: usize) -> [usize; 2] { let d = match &e.depth_twin { Some(t) => { e.depth_twin_dirty = true; + if e.plan.two_plane { + e.depth_plane_dirty = false; + } t.as_raw() as usize } None => 0, @@ -1096,6 +1229,9 @@ pub(super) fn on_uav_barrier(res: usize) -> [usize; 2] { let s = match &e.stencil_twin { Some(t) => { e.stencil_twin_dirty = true; + if e.plan.two_plane { + e.stencil_plane_dirty = false; + } t.as_raw() as usize } None => 0, @@ -1809,6 +1945,21 @@ pub(super) unsafe fn execute_syncs(list: *mut c_void, ops: &[SyncOp]) { continue; }; + if plan.two_plane { + static SYNC_T2D_TWO_PLANE: AtomicU64 = AtomicU64::new(0); + let k = SYNC_T2D_TWO_PLANE.fetch_add(1, Ordering::Relaxed); + if k < 8 || k.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: depth+UAV TwinToDepth sync #{k} on two_plane {res:#x} ({width}x{height}, depth_subs={}, stencil_subs={}, depth_twin={}, stencil_twin={}, kind={:?})", + depth.len(), + stencil.len(), + depth_twin.is_some(), + stencil_twin.is_some(), + plan.depth_sync, + ); + } + } + if !depth.is_empty() { if let Some(twin) = depth_twin { match plan.depth_sync { @@ -1923,6 +2074,21 @@ pub(super) unsafe fn execute_syncs(list: *mut c_void, ops: &[SyncOp]) { continue; }; + if plan.two_plane { + static SYNC_D2T_TWO_PLANE: AtomicU64 = AtomicU64::new(0); + let k = SYNC_D2T_TWO_PLANE.fetch_add(1, Ordering::Relaxed); + if k < 8 || k.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: depth+UAV DepthToTwin sync #{k} on two_plane {res:#x} ({width}x{height}, depth_subs={}, stencil_subs={}, depth_twin={}, stencil_twin={}, kind={:?})", + depth.len(), + stencil.len(), + depth_twin.is_some(), + stencil_twin.is_some(), + plan.depth_sync, + ); + } + } + if !depth.is_empty() { if let Some(twin) = depth_twin { match plan.depth_sync { @@ -2775,4 +2941,217 @@ mod tests { } } } + + #[test] + fn two_plane_global_and_enhanced_barriers_do_not_suppress_twin_dirty() { + #[repr(C)] + struct DummyCom { + vt: *const usize, + } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { + 1 + } + let mut vt = [0usize; 4]; + vt[1] = retain as usize; + vt[2] = retain as usize; + let mut d_obj = DummyCom { vt: vt.as_ptr() }; + let mut s_obj = DummyCom { vt: vt.as_ptr() }; + let mut sp_obj = DummyCom { vt: vt.as_ptr() }; + let all = D3D12_BARRIER_SUBRESOURCE_RANGE { + IndexOrFirstMipLevel: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + NumMipLevels: 0, + FirstArraySlice: 0, + NumArraySlices: 0, + FirstPlane: 0, + NumPlanes: 0, + }; + + unsafe { + // 1. Two-plane D16_UNORM_S8_UINT (fmt 118, RAGE9 material mask): + // starting in DEPTH_WRITE sets depth_plane_dirty = true, stencil_plane_dirty = true. + let plan = plan_for_console_format(118).unwrap(); + let mut e = Entry::new(0x1, plan, 1920, 1080, 1, 1, STATE_DEPTH_WRITE, false); + e.depth_twin = Some(ID3D12Resource::from_raw(&mut d_obj as *mut _ as *mut c_void)); + e.stencil_twin = Some(ID3D12Resource::from_raw(&mut s_obj as *mut _ as *mut c_void)); + assert!(e.depth_plane_dirty && e.stencil_plane_dirty); + assert!(!e.depth_twin_dirty && !e.stencil_twin_dirty); + + // Global UAV barrier must mark both twins dirty and clear plane_dirty even when plane_dirty was true. + mark_global_uav_dirty(&mut e); + assert!(e.depth_twin_dirty && e.stencil_twin_dirty); + assert!(!e.depth_plane_dirty && !e.stencil_plane_dirty); + + // Non-DIRECT enhanced barrier must also mark both twins dirty when plane_dirty was true. + e.depth_twin_dirty = false; + e.stencil_twin_dirty = false; + e.depth_plane_dirty = true; + e.stencil_plane_dirty = true; + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS(0), + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + &all, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + false, + ); + assert!(op.is_none()); + assert!(e.depth_twin_dirty && e.stencil_twin_dirty); + assert!(!e.depth_plane_dirty && !e.stencil_plane_dirty); + + // DIRECT enhanced barrier out of COMMON access must flush TwinToDepth even when plane_dirty was true. + e.depth_twin_dirty = false; + e.stencil_twin_dirty = false; + e.depth_plane_dirty = true; + e.stencil_plane_dirty = true; + let op = decide_enhanced_texture_barrier( + &mut e, + D3D12_BARRIER_ACCESS(0), + D3D12_BARRIER_ACCESS_DEPTH_STENCIL_READ, + D3D12_BARRIER_LAYOUT_COMMON, + D3D12_BARRIER_LAYOUT_DEPTH_STENCIL_READ, + &all, + D3D12_TEXTURE_BARRIER_FLAG_NONE, + true, + ); + assert!(matches!(op, Some(SyncOp::TwinToDepth { .. })), "expected TwinToDepth flush, got {op:?}"); + assert!(!e.depth_plane_dirty && !e.stencil_plane_dirty); + + // 2. Single-plane fmt 53 shadow map: global UAV barrier must stay guarded by !depth_plane_dirty. + let sp_plan = plan_for_console_format(53).unwrap(); + let mut sp = Entry::new(0x1, sp_plan, 1024, 1024, 1, 1, STATE_DEPTH_WRITE, false); + sp.depth_twin = Some(ID3D12Resource::from_raw(&mut sp_obj as *mut _ as *mut c_void)); + assert!(sp.depth_plane_dirty && !sp.depth_twin_dirty); + mark_global_uav_dirty(&mut sp); + assert!(!sp.depth_twin_dirty && sp.depth_plane_dirty, "single-plane shadow map must remain guarded"); + } + } + + #[test] + fn copy_dsv_copies_clears_and_handles_overlaps() { + let mut console_desc = [0u8; 0x38]; + console_desc[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + console_desc[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + console_desc[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + console_desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x20..0x24].copy_from_slice(&118u32.to_le_bytes()); + console_desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + console_desc[0x30..0x34].copy_from_slice(&6u32.to_le_bytes()); + + let res_a = 0x7001_0000usize; + let res_b = 0x7002_0000usize; + register_if_depth_uav(0x1 as *mut c_void, res_a as *mut c_void, &console_desc, STATE_COMMON, STATE_COMMON); + register_if_depth_uav(0x1 as *mut c_void, res_b as *mut c_void, &console_desc, STATE_COMMON, STATE_COMMON); + + let base = 0x9000_0000usize; + let inc = 32usize; + // Slots: [0]=A(1), [1]=empty, [2]=B(2), [3]=A(3) + note_dsv(base, res_a, 1); + note_dsv(base + 2 * inc, res_b, 2); + note_dsv(base + 3 * inc, res_a, 3); + + // Zero count / inc are no-ops + copy_dsv(base + 4 * inc, base, 0, inc); + copy_dsv(base + 4 * inc, base, 2, 0); + + // Disjoint copy including clearing a pre-existing destination where src is empty + note_dsv(base + 5 * inc, res_b, 9); + copy_dsv(base + 4 * inc, base, 4, inc); + { + let g = DSV_TO_RES.lock().unwrap(); + let m = g.as_ref().unwrap(); + assert_eq!(m.get(&(base + 4 * inc)).copied(), Some((res_a, 1))); + assert_eq!(m.get(&(base + 5 * inc)).copied(), None); + assert_eq!(m.get(&(base + 6 * inc)).copied(), Some((res_b, 2))); + assert_eq!(m.get(&(base + 7 * inc)).copied(), Some((res_a, 3))); + } + + // Overlapping forward copy: dst = base + inc, src = base, count = 3 -> [1]=A(1), [2]=empty, [3]=B(2) + copy_dsv(base + inc, base, 3, inc); + { + let g = DSV_TO_RES.lock().unwrap(); + let m = g.as_ref().unwrap(); + assert_eq!(m.get(&base).copied(), Some((res_a, 1))); + assert_eq!(m.get(&(base + inc)).copied(), Some((res_a, 1))); + assert_eq!(m.get(&(base + 2 * inc)).copied(), None); + assert_eq!(m.get(&(base + 3 * inc)).copied(), Some((res_b, 2))); + } + + // Overlapping backward copy: dst = base + 4*inc, src = base + 5*inc, count = 3 -> [4]=empty, [5]=B(2), [6]=A(3) + copy_dsv(base + 4 * inc, base + 5 * inc, 3, inc); + { + let g = DSV_TO_RES.lock().unwrap(); + let m = g.as_ref().unwrap(); + assert_eq!(m.get(&(base + 4 * inc)).copied(), None); + assert_eq!(m.get(&(base + 5 * inc)).copied(), Some((res_b, 2))); + assert_eq!(m.get(&(base + 6 * inc)).copied(), Some((res_a, 3))); + } + + forget(res_a); + forget(res_b); + } + + #[test] + fn uav_twin_tracking_and_forget_cleanup() { + #[repr(C)] + struct DummyCom { + vt: *const usize, + } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { + 1 + } + let mut vt = [0usize; 4]; + vt[1] = retain as usize; + vt[2] = retain as usize; + let mut d_obj = DummyCom { vt: vt.as_ptr() }; + let mut s_obj = DummyCom { vt: vt.as_ptr() }; + let d_raw = &mut d_obj as *mut _ as usize; + let s_raw = &mut s_obj as *mut _ as usize; + + let mut console_desc = [0u8; 0x38]; + console_desc[0..4].copy_from_slice(&3u32.to_le_bytes()); + console_desc[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + console_desc[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + console_desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + console_desc[0x20..0x24].copy_from_slice(&118u32.to_le_bytes()); + console_desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + console_desc[0x30..0x34].copy_from_slice(&6u32.to_le_bytes()); + + let res = 0x7003_0000usize; + register_if_depth_uav(0x1 as *mut c_void, res as *mut c_void, &console_desc, STATE_DEPTH_WRITE, STATE_DEPTH_WRITE); + unsafe { + let mut g = ENTRIES.lock().unwrap(); + let e = g.as_mut().unwrap().get_mut(&res).unwrap(); + e.depth_twin = Some(ID3D12Resource::from_raw(d_raw as *mut c_void)); + e.stencil_twin = Some(ID3D12Resource::from_raw(s_raw as *mut c_void)); + } + + let uav_d = 0xA000_0100usize; + let uav_s = 0xA000_0120usize; + let uav_other = 0xA000_0140usize; + let other_twin = 0x7004_0000usize; + note_uav_twin(uav_d, d_raw); + note_uav_twin(uav_s, s_raw); + note_uav_twin(uav_other, other_twin); + + assert_eq!(twin_for_pc_uav(uav_d), Some(d_raw)); + assert_eq!(twin_for_pc_uav(uav_s), Some(s_raw)); + { + let g = ENTRIES.lock().unwrap(); + let e = g.as_ref().unwrap().get(&res).unwrap(); + assert!(e.depth_twin_dirty && e.stencil_twin_dirty); + assert!(!e.depth_plane_dirty && !e.stencil_plane_dirty); + } + + // `forget(res)` must remove both depth and stencil UAV twin mappings while keeping unrelated ones. + forget(res); + assert_eq!(twin_for_pc_uav(uav_d), None); + assert_eq!(twin_for_pc_uav(uav_s), None); + assert_eq!(twin_for_pc_uav(uav_other), Some(other_twin)); + clear_uav_twin(uav_other); + assert_eq!(twin_for_pc_uav(uav_other), None); + } } diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 6662e7e8ae..3ea02efb1c 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -21,8 +21,14 @@ const SEAL_EVERY: Duration = Duration::from_millis(10); /// how often the thread here looks for batches that can go const TICK: Duration = Duration::from_millis(4); +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum DeferredItem { + Com(usize), + Uma { ptr: usize, sparse: bool }, +} + struct Batch { - dead: Vec, + dead: Vec, /// (fence, value) a queue: all reached = nothing submitted before the batch closed is left marks: Vec<(ID3D12Fence, u64)>, } @@ -31,7 +37,7 @@ struct Batch { struct Held { /// queue → its fence here and the last value signalled on it fences: HashMap, - open: Vec, + open: Vec, sealed: VecDeque, last_seal: Option, } @@ -49,7 +55,7 @@ impl Held { } /// Take out the sealed batches every queue is past without touching `open`. - unsafe fn reap(&mut self) -> Vec { + unsafe fn reap(&mut self) -> Vec { let mut gone = Vec::new(); while self.sealed.front().is_some_and(|b| b.marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { gone.extend(self.sealed.pop_front().unwrap().dead); @@ -58,8 +64,8 @@ impl Held { } /// Close the open batch (at most every `SEAL_EVERY`, or `seal_now`) with a fence value on each of `queues`, - /// and take out the batches every queue is past: the resources to release now. - unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { + /// and take out the batches every queue is past: the items to release now. + unsafe fn drain(&mut self, queues: &[ID3D12CommandQueue], seal_now: bool) -> Vec { if self.needs_seal(seal_now) { let mut marks = Vec::with_capacity(queues.len()); let mut ok = true; @@ -117,16 +123,12 @@ fn ensure_thread() { }); } -/// `res` (an adopted resource) holds one reference that is now this module's. With no work in -/// flight it goes before this returns (the queues pass a fence value at once): a title that -/// frees the memory under a resource right after its last `Release` finds it unpinned, as -/// before. Otherwise the thread here lets it go. -pub unsafe fn hold(res: usize) { +unsafe fn enqueue(item: DeferredItem) { let busy = { let mut g = HELD.lock().unwrap(); let h = g.get_or_insert_with(Held::default); let busy = !h.sealed.is_empty(); - h.open.push(res); + h.open.push(item); busy }; if busy { @@ -148,6 +150,24 @@ pub unsafe fn hold(res: usize) { ensure_thread(); } +/// `res` (an adopted resource) holds one reference that is now this module's. With no work in +/// flight it goes before this returns (the queues pass a fence value at once): a title that +/// frees the memory under a resource right after its last `Release` finds it unpinned, as +/// before. Otherwise the thread here lets it go. +pub unsafe fn hold(res: usize) { + enqueue(DeferredItem::Com(res)); +} + +/// Defer freeing a UMA block (`sparse::free` or `uma::Uma::free`) until every queue XCL knows +/// of has passed the work submitted before this call, so in-flight GPU lists finish before the +/// block is reused or decommitted. +pub(super) fn hold_uma(ptr: usize, sparse: bool) { + if ptr == 0 { + return; + } + unsafe { enqueue(DeferredItem::Uma { ptr, sparse }) }; +} + /// Release what every queue XCL knows of is past: the title's, the tile-mapping one, the /// upload ones. pub unsafe fn drain_known(seal_now: bool) { @@ -181,17 +201,28 @@ pub unsafe fn drain_known(seal_now: bool) { } }; // (outside the lock: a release may end other objects, whose releases come back here) - for res in gone { - if super::vram::recycle_ready(res) { - continue; + for item in gone { + match item { + DeferredItem::Com(res) => { + if super::vram::recycle_ready(res) { + continue; + } + let ptr = res as *mut c_void; + let f: unsafe extern "system" fn(*mut c_void) -> u32 = if super::real::is_adopted(ptr) { + std::mem::transmute(super::real::orig_fn(ptr, 2)) + } else { + std::mem::transmute(*(*(ptr as *const *const usize)).add(2)) + }; + f(ptr); + } + DeferredItem::Uma { ptr, sparse } => { + if sparse { + super::sparse::free(ptr); + } else if let Some(u) = crate::gpu::uma::get() { + u.free(ptr); + } + } } - let ptr = res as *mut c_void; - let f: unsafe extern "system" fn(*mut c_void) -> u32 = if super::real::is_adopted(ptr) { - std::mem::transmute(super::real::orig_fn(ptr, 2)) - } else { - std::mem::transmute(*(*(ptr as *const *const usize)).add(2)) - }; - f(ptr); } } @@ -227,7 +258,7 @@ mod tests { let raw = res.unwrap().into_raw() as usize; let mut held = Held::default(); - held.open.push(raw); + held.open.push(DeferredItem::Com(raw)); let queues = [queue.clone()]; assert!(held.drain(&queues, false).is_empty(), "the queue has not passed the batch's fence value"); std::thread::sleep(Duration::from_millis(100)); @@ -241,7 +272,7 @@ mod tests { std::thread::sleep(Duration::from_millis(5)); gone = held.drain(&queues, false); } - assert_eq!(gone, vec![raw], "released once the queue is past the batch"); + assert_eq!(gone, vec![DeferredItem::Com(raw)], "released once the queue is past the batch"); assert!(held.is_empty()); drop(ID3D12Resource::from_raw(raw as *mut c_void)); } @@ -251,8 +282,8 @@ mod tests { #[test] fn without_queues_a_batch_goes_at_once() { let mut held = Held::default(); - held.open.push(0x1000); - assert_eq!(unsafe { held.drain(&[], false) }, vec![0x1000]); + held.open.push(DeferredItem::Com(0x1000)); + assert_eq!(unsafe { held.drain(&[], false) }, vec![DeferredItem::Com(0x1000)]); assert!(held.is_empty()); } @@ -261,10 +292,37 @@ mod tests { fn reap_keeps_open_items_and_respects_seal_interval() { let mut held = Held::default(); held.last_seal = Some(Instant::now()); - held.open.push(0x2000); + held.open.push(DeferredItem::Com(0x2000)); assert!(!held.needs_seal(false), "within SEAL_EVERY: batching defers sealing"); assert!(held.needs_seal(true), "explicit seal_now seals immediately"); assert!(unsafe { held.reap() }.is_empty()); - assert_eq!(held.open, vec![0x2000]); + assert_eq!(held.open, vec![DeferredItem::Com(0x2000)]); + } + + /// Deferred UMA blocks retire in FIFO order alongside COM releases and wait for active GPU queues. + #[test] + fn hold_uma_preserves_order_and_frees_on_idle_drain() { + let mut held = Held::default(); + held.open.push(DeferredItem::Com(0x1000)); + held.open.push(DeferredItem::Uma { ptr: 0x2000_0000, sparse: false }); + held.open.push(DeferredItem::Uma { ptr: 0x3000_0000, sparse: true }); + assert_eq!( + unsafe { held.drain(&[], false) }, + vec![ + DeferredItem::Com(0x1000), + DeferredItem::Uma { ptr: 0x2000_0000, sparse: false }, + DeferredItem::Uma { ptr: 0x3000_0000, sparse: true }, + ] + ); + assert!(held.is_empty()); + + // Real UMA block deferred through `hold_uma` is returned once no GPU queues are busy. + let Some(u) = crate::gpu::uma::get() else { return }; + let before = u.used(); + let ptr = u.alloc(0x1_0000, 0x1_0000).expect("UMA alloc") as usize; + assert!(u.used() >= before + 0x1_0000); + hold_uma(ptr, false); + // With no active queues in unit tests, `hold_uma` drains synchronously and frees the block. + assert_eq!(u.used(), before, "deferred UMA block should be freed once queues are idle"); } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 0908ec1fa3..53a6ccc12e 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5452,10 +5452,24 @@ unsafe fn clear_uav(this: *mut c_void, slot: usize, gpu: u64, cpu: u64, res: usi return; } }; + if real::is_unaligned_delta_uav(cpu as usize) { + static N: AtomicU64 = AtomicU64::new(0); + if once(&N, 4) { + crate::xlog_warn!("D3D12.X: ClearUnorderedAccessView skipped for unaligned delta buffer UAV (cpu {cpu:#x}, res {res:#x})"); + } + return; + } + let pc_res = super::depth_uav::twin_for_pc_uav(cpu as usize).unwrap_or(res); + if let Some((va, len)) = real::console_buffer(res) { + if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va)) { + note_write(this as usize, va as u64, len as u64); + } + } + super::bind::note_gpu_write(this); if shared { ensure_console_view_heap(this); } - pc::(this, slot)(this, gpu, cpu, res, values, n, rects) + pc::(this, slot)(this, gpu, cpu, pc_res, values, n, rects) } pub(super) unsafe extern "system" fn clear_uav_uint_x(this: *mut c_void, gpu: u64, cpu: u64, res: usize, values: *const u32, n: u32, rects: *const windows::Win32::Foundation::RECT) { diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index b63360d839..c51d80005d 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -619,6 +619,21 @@ pub fn earlier_used_keys() -> std::collections::HashSet { used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt")).unwrap_or_default()) } +/// Flush pending `used-pipelines.txt` keys on the background journal writer. +pub fn flush_used() { + used::flush(); +} + +/// Flush and join the `used-pipelines.txt` journal worker on normal shutdown. +pub fn shutdown_used() { + used::shutdown(); +} + +/// Best-effort bounded flush of pending `used-pipelines.txt` keys on process termination. +pub fn flush_used_bounded(timeout: std::time::Duration) { + used::flush_bounded(timeout); +} + /// The pipelines a title used, by a hash of their shaders, kept between runs /// (`used-pipelines.txt` beside the DXIL cache, a key a line). /// @@ -629,13 +644,313 @@ pub fn earlier_used_keys() -> std::collections::HashSet { /// instead of waiting for its pipeline, ~2 170 dispatches were skipped in those frames without /// this and 94 – 150 with it. mod used { - use std::collections::HashSet; - use std::io::Write; - use std::sync::{Mutex, OnceLock, RwLock}; + use std::sync::{Arc, Condvar, Mutex, OnceLock, RwLock}; + use std::{ + collections::HashSet, + fmt::Write as _, + io::Write, + path::PathBuf, + thread::JoinHandle, + time::{Duration, Instant}, + }; + + /// Coalesce first-use bursts into a single disk write off the bind lock. + const COALESCE_WINDOW: Duration = Duration::from_millis(25); + /// Flush immediately once a burst reaches this many unique keys. + const BATCH_IMMEDIATE: usize = 32; + + enum Sink { + LazyFile(PathBuf, Option), + #[cfg(test)] + Writer(Box), + } + + impl Sink { + fn write_batch(&mut self, bytes: &[u8]) { + match self { + Self::LazyFile(path, file) => { + if file.is_none() { + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + *file = std::fs::OpenOptions::new().create(true).append(true).open(&*path).ok(); + } + if file.as_mut().is_some_and(|f| f.write_all(bytes).is_err() || f.flush().is_err()) { + *file = None; + } + } + #[cfg(test)] + Self::Writer(w) => { + if w.write_all(bytes).is_ok() { + let _ = w.flush(); + } + } + } + } + } + + fn format_keys(batch: &[u64], buf: &mut String) { + buf.clear(); + buf.reserve(batch.len() * 17); + for &key in batch { + let _ = writeln!(buf, "{key:016x}"); + } + } + + fn append_to_path(path: &PathBuf, bytes: &[u8]) { + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) { + let _ = f.write_all(bytes); + let _ = f.flush(); + } + } + + #[derive(Default)] + struct JournalState { + seen: HashSet, + pending: Vec, + fallback_path: Option, + enqueued_seq: u64, + completed_seq: u64, + flush_now: bool, + closed: bool, + writer_stopped: bool, + } + + struct JournalShared { + state: Mutex, + wake_cv: Condvar, + flushed_cv: Condvar, + } + + struct StopGuard<'a>(&'a JournalShared); + impl Drop for StopGuard<'_> { + fn drop(&mut self) { + self.0.state.lock().unwrap_or_else(|e| e.into_inner()).writer_stopped = true; + self.0.flushed_cv.notify_all(); + } + } + + pub(super) struct Journal { + shared: Arc, + writer: Mutex>>, + } + + impl Journal { + fn new_shared(state: JournalState) -> Arc { + Arc::new(JournalShared { state: Mutex::new(state), wake_cv: Condvar::new(), flushed_cv: Condvar::new() }) + } + + fn in_memory(seen: HashSet) -> Self { + Self { + shared: Self::new_shared(JournalState { seen, writer_stopped: true, ..Default::default() }), + writer: Mutex::new(None), + } + } + + fn with_sink(seen: HashSet, sink: Sink, coalesce: Duration) -> Self { + let fallback_path = match &sink { + Sink::LazyFile(p, _) => Some(p.clone()), + #[cfg(test)] + Sink::Writer(_) => None, + }; + let shared = Self::new_shared(JournalState { seen, fallback_path, ..Default::default() }); + let bg = Arc::clone(&shared); + let writer = std::thread::Builder::new() + .name("xcl-pso-used".into()) + .spawn(move || writer_loop(&bg, sink, coalesce)) + .ok(); + if writer.is_none() { + shared.state.lock().unwrap().writer_stopped = true; + shared.flushed_cv.notify_all(); + } + Self { shared, writer: Mutex::new(writer) } + } + + #[cfg(test)] + pub(super) fn with_writer(w: Box, c: Duration) -> Self { + Self::with_sink(HashSet::new(), Sink::Writer(w), c) + } + + #[cfg(test)] + pub(super) fn with_file(p: PathBuf, c: Duration) -> Self { + Self::with_sink(HashSet::new(), Sink::LazyFile(p, None), c) + } + + #[cfg(test)] + pub(super) fn without_writer(p: PathBuf) -> Self { + Self { + shared: Self::new_shared(JournalState { fallback_path: Some(p), writer_stopped: true, ..Default::default() }), + writer: Mutex::new(None), + } + } + + pub(super) fn note(&self, key: u64) { + if key == 0 { + return; + } + let mut g = self.shared.state.lock().unwrap(); + if !g.seen.insert(key) || g.closed || (g.writer_stopped && g.fallback_path.is_none()) { + return; + } + g.pending.push(key); + g.enqueued_seq += 1; + if matches!(g.pending.len(), 1 | BATCH_IMMEDIATE) { + self.shared.wake_cv.notify_one(); + } + } + + #[cfg(test)] + pub(super) fn noted(&self, key: u64) -> bool { + self.shared.state.lock().unwrap().seen.contains(&key) + } + + pub(super) fn flush(&self) { + let (fallback, batch) = { + let mut g = self.shared.state.lock().unwrap(); + let target = g.enqueued_seq; + if g.completed_seq >= target || (g.writer_stopped && g.pending.is_empty()) { + return; + } + if !g.writer_stopped { + g.flush_now = true; + self.shared.wake_cv.notify_one(); + while g.completed_seq < target && !g.writer_stopped { + g = self.shared.flushed_cv.wait(g).unwrap(); + } + } + if g.pending.is_empty() { + return; + } + let batch = std::mem::take(&mut g.pending); + g.completed_seq = g.enqueued_seq; + (g.fallback_path.clone(), batch) + }; + if let Some(path) = fallback { + let mut buf = String::new(); + format_keys(&batch, &mut buf); + append_to_path(&path, buf.as_bytes()); + } + } + + pub(super) fn flush_bounded(&self, timeout: Duration) { + let (fallback, batch) = { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + let target = g.enqueued_seq; + if g.completed_seq >= target || (g.writer_stopped && g.pending.is_empty()) { + return; + } + g.flush_now = true; + self.shared.wake_cv.notify_one(); + let deadline = Instant::now() + timeout; + while g.completed_seq < target && !g.writer_stopped { + let Some(rem) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (guard, res) = self.shared.flushed_cv.wait_timeout(g, rem).unwrap_or_else(|e| e.into_inner()); + g = guard; + if res.timed_out() { + break; + } + } + if g.pending.is_empty() { + return; + } + // Worker timed out (e.g. blocked on the Windows loader lock during ExitProcess) or + // failed to spawn: take the remaining keys and append them directly so none are lost. + let batch = std::mem::take(&mut g.pending); + g.completed_seq = g.enqueued_seq; + (g.fallback_path.clone(), batch) + }; + if let Some(path) = fallback { + let mut buf = String::new(); + format_keys(&batch, &mut buf); + append_to_path(&path, buf.as_bytes()); + } + } + + pub(super) fn shutdown(&self) { + { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + g.closed = true; + g.flush_now = true; + self.shared.wake_cv.notify_one(); + } + if let Some(h) = self.writer.lock().unwrap_or_else(|e| e.into_inner()).take() { + if h.thread().id() != std::thread::current().id() { + let _ = h.join(); + } + } else { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + while !g.writer_stopped { + g = self.shared.flushed_cv.wait(g).unwrap_or_else(|e| e.into_inner()); + } + } + let (fallback, batch) = { + let mut g = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if g.pending.is_empty() { + return; + } + let batch = std::mem::take(&mut g.pending); + g.completed_seq = g.enqueued_seq; + (g.fallback_path.clone(), batch) + }; + if let Some(path) = fallback { + let mut buf = String::new(); + format_keys(&batch, &mut buf); + append_to_path(&path, buf.as_bytes()); + } + } + } + + impl Drop for Journal { + fn drop(&mut self) { + self.shutdown(); + } + } + + fn writer_loop(shared: &JournalShared, mut sink: Sink, coalesce: Duration) { + let _stop = StopGuard(shared); + let mut buf = String::new(); + loop { + let (batch, batch_seq) = { + let mut g = shared.state.lock().unwrap(); + while g.pending.is_empty() && !g.closed { + if std::mem::take(&mut g.flush_now) { + shared.flushed_cv.notify_all(); + } + g = shared.wake_cv.wait(g).unwrap(); + } + if g.pending.is_empty() && g.closed { + break; + } + if !coalesce.is_zero() { + let deadline = Instant::now() + coalesce; + while g.pending.len() < BATCH_IMMEDIATE && !g.flush_now && !g.closed { + let Some(rem) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (guard, res) = shared.wake_cv.wait_timeout(g, rem).unwrap(); + g = guard; + if res.timed_out() { + break; + } + } + } + g.flush_now = false; + (std::mem::take(&mut g.pending), g.enqueued_seq) + }; + format_keys(&batch, &mut buf); + sink.write_batch(buf.as_bytes()); + { + let mut g = shared.state.lock().unwrap(); + g.completed_seq = g.completed_seq.max(batch_seq); + } + shared.flushed_cv.notify_all(); + } + } struct Used { earlier: RwLock>, - now: Mutex<(HashSet, Option)>, + now: Journal, } /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). @@ -643,26 +958,60 @@ mod used { text.lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).filter(|&k| k != 0).collect() } + static U: OnceLock = OnceLock::new(); + + extern "C" { + fn atexit(f: extern "C" fn()) -> std::ffi::c_int; + } + + extern "C" fn on_process_exit() { + shutdown(); + } + + fn init_from_path(path: PathBuf, coalesce: Duration) -> Used { + let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); + if !earlier.is_empty() { + crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); + } + let now = Journal::with_sink(earlier.clone(), Sink::LazyFile(path, None), coalesce); + unsafe { + atexit(on_process_exit); + } + Used { earlier: RwLock::new(earlier), now } + } + fn get() -> &'static Used { - static U: OnceLock = OnceLock::new(); U.get_or_init(|| { // (a test neither reads nor writes the user's file) if cfg!(test) { - return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)) }; - } - let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); - let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); - if !earlier.is_empty() { - crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); - } - if let Some(dir) = path.parent() { - let _ = std::fs::create_dir_all(dir); + #[cfg(test)] + if let Some(p) = std::env::var_os("XCL_TEST_USED_STATIC_PATH") { + return init_from_path(PathBuf::from(p), Duration::from_secs(60)); + } + return Used { earlier: RwLock::new(HashSet::new()), now: Journal::in_memory(HashSet::new()) }; } - let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); - Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier) } + init_from_path(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"), COALESCE_WINDOW) }) } + pub fn flush() { + if let Some(u) = U.get() { + u.now.flush(); + } + } + + pub fn shutdown() { + if let Some(u) = U.get() { + u.now.shutdown(); + } + } + + pub fn flush_bounded(timeout: Duration) { + if let Some(u) = U.get() { + u.now.flush_bounded(timeout); + } + } + /// An earlier run used a pipeline of these shaders. pub fn known(key: u64) -> bool { key != 0 && get().earlier.read().unwrap().contains(&key) @@ -670,21 +1019,13 @@ mod used { /// A pipeline of these shaders is used now: kept for the next run. pub fn note(key: u64) { - if key == 0 { - return; - } - let mut g = get().now.lock().unwrap(); - if g.0.insert(key) { - if let Some(f) = g.1.as_mut() { - let _ = writeln!(f, "{key:016x}"); - } - } + get().now.note(key); } /// (tests) This run used a pipeline of these shaders. #[cfg(test)] pub fn noted(key: u64) -> bool { - get().now.lock().unwrap().0.contains(&key) + get().now.noted(key) } #[cfg(test)] @@ -1010,6 +1351,228 @@ mod used_tests { assert!(keys.contains(&0xff) && keys.contains(&0x1a2b)); } + #[test] + fn used_note_does_not_block_on_slow_writer() { + use std::{io::Write, time::Duration}; + struct Blocking(Option>, mpsc::Receiver<()>, Arc>>); + impl Write for Blocking { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + let _ = self.1.recv(); + } + self.2.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let ((entered_tx, entered_rx), (release_tx, release_rx)) = (mpsc::channel(), mpsc::channel()); + let out = Arc::new(Mutex::new(Vec::new())); + let j = used::Journal::with_writer(Box::new(Blocking(Some(entered_tx), release_rx, out.clone())), Duration::ZERO); + j.note(0x1111); + entered_rx.recv_timeout(Duration::from_secs(5)).expect("writer entered write_all"); + j.note(0x2222); + j.note(0x3333); + assert!(j.noted(0x1111) && j.noted(0x2222) && j.noted(0x3333), "note/noted must not block on writer I/O"); + release_tx.send(()).unwrap(); + j.flush(); + assert_eq!(used::parse(std::str::from_utf8(&out.lock().unwrap()).unwrap()), [0x1111, 0x2222, 0x3333].into()); + } + + #[test] + fn used_burst_coalesces_writes_and_deduplicates_keys() { + use std::{io::Write, time::Duration}; + struct Counting(Arc)>>); + impl Write for Counting { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let mut g = self.0.lock().unwrap(); + g.0 += 1; + g.1.extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let rec = Arc::new(Mutex::new((0usize, Vec::new()))); + let j = used::Journal::with_writer(Box::new(Counting(rec.clone())), Duration::from_millis(500)); + for k in (0u64..=40).chain(0u64..=40) { + j.note(k); + } + j.flush(); + let (writes, bytes) = { + let g = rec.lock().unwrap(); + (g.0, g.1.clone()) + }; + let text = String::from_utf8(bytes).unwrap(); + assert!(writes >= 1 && writes < 40, "expected coalesced writes (< 40), got {writes}"); + assert_eq!(text.lines().count(), 40); + assert_eq!(used::parse(&text), (1u64..=40).collect()); + } + + #[test] + fn used_flush_drop_lazy_file_and_io_error_are_graceful() { + use std::{io::Write, time::Duration}; + let dir = std::env::temp_dir().join(format!("xcl-used-journal-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("nested").join("used-pipelines.txt"); + let j = used::Journal::with_file(path.clone(), Duration::from_secs(5)); + assert!(!dir.exists() && !path.exists(), "dir/file must open lazily on first batch write"); + j.note(0xAA01); + j.note(0xAA02); + j.flush(); + assert_eq!(used::parse(&std::fs::read_to_string(&path).unwrap()), [0xAA01, 0xAA02].into()); + j.note(0xAA03); + drop(j); + assert_eq!(used::parse(&std::fs::read_to_string(&path).unwrap()), [0xAA01, 0xAA02, 0xAA03].into()); + let _ = std::fs::remove_dir_all(&dir); + + struct Failing(Arc); + impl Write for Failing { + fn write(&mut self, _: &[u8]) -> std::io::Result { + self.0.fetch_add(1, Ordering::Relaxed); + Err(std::io::Error::other("disk full")) + } + fn flush(&mut self) -> std::io::Result<()> { + Err(std::io::Error::other("disk full")) + } + } + let attempts = Arc::new(AtomicUsize::new(0)); + let j = used::Journal::with_writer(Box::new(Failing(attempts.clone())), Duration::ZERO); + j.note(0xBAD1); + j.note(0xBAD2); + j.flush(); + j.note(0xBAD3); + j.flush(); + assert!(attempts.load(Ordering::Acquire) >= 1 && j.noted(0xBAD1) && j.noted(0xBAD2) && j.noted(0xBAD3)); + } + + #[test] + fn used_static_once_lock_flushes_on_process_exit() { + use std::time::{Duration, Instant}; + if let Some(path) = std::env::var_os("XCL_TEST_USED_STATIC_PATH") { + let mode = std::env::var("XCL_TEST_USED_EXIT_MODE").unwrap_or_default(); + match mode.as_str() { + "normal" => { + used::note(0xE001); + used::note(0xE002); + return; + } + "flush" => { + used::note(0xE003); + flush_used(); + let text = std::fs::read_to_string(&path).expect("flush_used must flush pending keys"); + assert_eq!(used::parse(&text), [0xE003].into()); + return; + } + "explicit" => { + used::note(0xE004); + shutdown_used(); + let text = std::fs::read_to_string(&path).expect("shutdown_used must flush before exit"); + assert_eq!(used::parse(&text), [0xE004].into()); + shutdown_used(); + flush_used_bounded(Duration::from_millis(50)); + return; + } + "bounded" => { + used::note(0xE005); + flush_used_bounded(Duration::from_secs(5)); + let text = std::fs::read_to_string(&path).expect("flush_used_bounded must flush before termination"); + assert_eq!(used::parse(&text), [0xE005].into()); + return; + } + other => panic!("unexpected mode {other}"), + } + } + let exe = std::env::current_exe().unwrap(); + let dir = std::env::temp_dir().join(format!("xcl-used-exit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for (mode, expected) in [ + ("normal", &[0xE001u64, 0xE002][..]), + ("flush", &[0xE003u64][..]), + ("explicit", &[0xE004u64][..]), + ("bounded", &[0xE005u64][..]), + ] { + let path = dir.join(mode).join("used-pipelines.txt"); + let start = Instant::now(); + let status = std::process::Command::new(&exe) + .args(["--exact", "hle::d3d12x::pso_async::used_tests::used_static_once_lock_flushes_on_process_exit", "--nocapture"]) + .env("XCL_TEST_USED_STATIC_PATH", &path) + .env("XCL_TEST_USED_EXIT_MODE", mode) + .status() + .unwrap(); + assert!(status.success(), "child ({mode}) failed: {status}"); + assert!(start.elapsed() < Duration::from_secs(10), "child ({mode}) waited for coalesce timer"); + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("child ({mode}) lost keys on exit: {e}")); + assert_eq!(used::parse(&text), expected.iter().copied().collect(), "child ({mode}) keys mismatch"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn used_flush_bounded_timeout_and_spawn_failure_fallback_are_sound() { + use std::{io::Write, time::Duration}; + // 1. Slow writer finishing batch 1 after `flush_bounded` already drained batch 2 must not + // regress `completed_seq` below `enqueued_seq` (which would hang a later `flush()`). + struct BlockingOnce(Option>, mpsc::Receiver<()>, Option>, Arc>>); + impl Write for BlockingOnce { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if let Some(tx) = self.0.take() { + let _ = tx.send(()); + let _ = self.1.recv_timeout(Duration::from_secs(5)); + } + self.3.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + if let Some(tx) = self.2.take() { + let _ = tx.send(()); + } + Ok(()) + } + } + let ((entered_tx, entered_rx), (release_tx, release_rx), (wrote_tx, wrote_rx)) = (mpsc::channel(), mpsc::channel(), mpsc::channel()); + let out = Arc::new(Mutex::new(Vec::new())); + let j = Arc::new(used::Journal::with_writer(Box::new(BlockingOnce(Some(entered_tx), release_rx, Some(wrote_tx), out.clone())), Duration::ZERO)); + j.note(0xC001); + entered_rx.recv_timeout(Duration::from_secs(5)).expect("writer entered batch 1"); + j.note(0xC002); + j.flush_bounded(Duration::from_millis(20)); + release_tx.send(()).unwrap(); + wrote_rx.recv_timeout(Duration::from_secs(5)).expect("writer finished batch 1"); + std::thread::sleep(Duration::from_millis(25)); + let (done_tx, done_rx) = mpsc::channel(); + let j2 = Arc::clone(&j); + let flusher = std::thread::spawn(move || { + j2.flush(); + let _ = done_tx.send(()); + }); + done_rx.recv_timeout(Duration::from_secs(5)).expect("flush() must not hang when completed_seq stays monotonic"); + flusher.join().unwrap(); + drop(j); + assert!(used::parse(std::str::from_utf8(&out.lock().unwrap()).unwrap()).contains(&0xC001)); + + // 2. When writer spawn fails (`writer_stopped == true` with `fallback_path`), `note()` + // still queues keys so `flush_bounded()` and `shutdown()` persist them directly. + let dir = std::env::temp_dir().join(format!("xcl-used-nospawn-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let p_bounded = dir.join("bounded").join("used-pipelines.txt"); + let j_b = used::Journal::without_writer(p_bounded.clone()); + j_b.note(0xF001); + j_b.note(0xF002); + j_b.flush_bounded(Duration::from_millis(20)); + assert_eq!(used::parse(&std::fs::read_to_string(&p_bounded).unwrap()), [0xF001, 0xF002].into()); + + let p_shutdown = dir.join("shutdown").join("used-pipelines.txt"); + let j_s = used::Journal::without_writer(p_shutdown.clone()); + j_s.note(0xF003); + j_s.shutdown(); + assert_eq!(used::parse(&std::fs::read_to_string(&p_shutdown).unwrap()), [0xF003].into()); + let _ = std::fs::remove_dir_all(&dir); + } + /// A lazy pipeline of shaders an earlier run used is built without a bind; another one is /// built only at its first use, and that use is kept for the next run. #[test] @@ -1599,9 +2162,6 @@ fn resolve_wait_in( enqueue(p.clone()); } let Some(fcap) = frame_cap else { - if !p.compute { - return p.stand(pso); - } let _held = Held::new(); if let Some(b) = budget { return resolve_within(p, pso, b); @@ -2327,4 +2887,54 @@ mod pso_queue_tests { let _ = released(standin_ok); let _ = released(standin_fail); } + + #[test] + fn frame_cap_none_waits_for_graphics_pso_instead_of_skipping() { + use std::time::{Duration, Instant}; + + let gfx_budget = Mutex::new(FrameWaitBudget::new()); + + // Graphics PSO with `frame_cap == None` and no per-PSO budget waits to completion. + let g_wait = 0x7E57_F101usize; + submit_lazy(g_wait, false, Box::new(|| { + std::thread::sleep(Duration::from_millis(25)); + 0xF201 + }), 0); + let p_wait = entry(g_wait).unwrap(); + assert_eq!(resolve_wait_in(&p_wait, g_wait, None, None, 1, &gfx_budget), 0xF201); + + // Graphics PSO with `frame_cap == None` and a per-PSO budget respects `budget` + // instead of skipping with 0 ms wait. + let g_budget = 0x7E57_F102usize; + let (go_tx, go_rx) = mpsc::channel::<()>(); + submit_lazy(g_budget, false, Box::new(move || { + let _ = go_rx.recv(); + 0xF202 + }), 0); + let p_budget = entry(g_budget).unwrap(); + let t0 = Instant::now(); + assert_eq!( + resolve_wait_in(&p_budget, g_budget, Some(Duration::from_millis(30)), None, 1, &gfx_budget), + g_budget + ); + assert!( + t0.elapsed() >= Duration::from_millis(15), + "must wait for budget instead of skipping immediately ({:?})", + t0.elapsed() + ); + assert!(p_budget.late.load(Ordering::Acquire)); + go_tx.send(()).unwrap(); + let wait_start = Instant::now(); + while is_pending(g_budget) && wait_start.elapsed() < Duration::from_secs(5) { + std::thread::sleep(Duration::from_millis(2)); + } + assert_eq!( + resolve_wait_in(&p_budget, g_budget, Some(Duration::from_millis(30)), None, 1, &gfx_budget), + 0xF202 + ); + + for s in [g_wait, g_budget] { + let _ = released(s); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5fd17acf41..9d7af8caa7 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2063,6 +2063,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } else { f(this) }; + let mut uma_to_free: Option<(usize, bool)> = None; if n == 0 { if let Some(s) = UNMAPPABLE.write().unwrap().as_mut() { s.remove(&(this as usize)); @@ -2092,16 +2093,15 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { forget_outside_resource(this as usize); let gone = UMA_BUFFERS.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); - } + uma_to_free = Some((p, u.is_sparse(p))); } } if held { super::late_release::hold(this as usize); } + if let Some((p, sparse)) = uma_to_free { + super::late_release::hold_uma(p, sparse); + } n } @@ -2574,6 +2574,11 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 } let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, n, dst, src, ty); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 && n > 0 && super::depth_uav::any() { + let get_inc: unsafe extern "system" fn(*mut c_void, u32) -> u32 = std::mem::transmute(orig_fn(this, 15)); + let inc = get_inc(this, ty) as usize; + super::depth_uav::copy_dsv(dst as usize, src as usize, n, inc); + } } /// #23 CopyDescriptors(dst ranges, src ranges, type): range by range over console slots. @@ -2593,7 +2598,39 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst } type F = unsafe extern "system" fn(*mut c_void, u32, *const u64, *const u32, u32, *const u64, *const u32, u32); let f: F = std::mem::transmute(orig_fn(this, 23)); - return f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); + f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty); + if ty == D3D12_DESCRIPTOR_HEAP_TYPE_DSV.0 as u32 && !dsts.is_null() && !srcs.is_null() && nd > 0 && ns > 0 && super::depth_uav::any() { + let get_inc: unsafe extern "system" fn(*mut c_void, u32) -> u32 = std::mem::transmute(orig_fn(this, 15)); + let inc = get_inc(this, ty) as usize; + let (mut di, mut si) = (0usize, 0usize); + let (mut d_rem, mut s_rem) = (0u32, 0u32); + let (mut d_cur, mut s_cur) = (0u64, 0u64); + loop { + while d_rem == 0 { + if di >= nd as usize { + return; + } + d_cur = *dsts.add(di); + d_rem = if dsizes.is_null() { 1 } else { *dsizes.add(di) }; + di += 1; + } + while s_rem == 0 { + if si >= ns as usize { + return; + } + s_cur = *srcs.add(si); + s_rem = if ssizes.is_null() { 1 } else { *ssizes.add(si) }; + si += 1; + } + let run = d_rem.min(s_rem); + super::depth_uav::copy_dsv(d_cur as usize, s_cur as usize, run, inc); + d_cur = d_cur.wrapping_add(run as u64 * inc as u64); + s_cur = s_cur.wrapping_add(run as u64 * inc as u64); + d_rem -= run; + s_rem -= run; + } + } + return; } // Walk (dst, src) ranges in lockstep with zero heap allocations, batching each maximal // contiguous overlap into a single `copy_console_slots` call. @@ -2631,12 +2668,7 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst /// descriptor heap Release (every caller): a console heap's slots go with it unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - super::console_heap::unregister(this as usize); - } - n + release_taking_first(this, || super::console_heap::take(this as usize), |h| h.into_iter().for_each(super::console_heap::free)) } /// Default UAV dimension for a texture resource when `CreateUnorderedAccessView` receives a NULL desc. @@ -3031,6 +3063,11 @@ fn null_uav_desc( .or_else(|| rd.map(resource_dim_to_view)) .unwrap_or(D3D12_UAV_DIMENSION_TEXTURE2D.0); match dim { + 1 => D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + }, 2 => D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_R32_FLOAT, ViewDimension: D3D12_UAV_DIMENSION_TEXTURE1D, @@ -3243,6 +3280,171 @@ fn uav_companion_srv( Some(srv) } +/// PC UAV CPU descriptor handles that were replaced by a null buffer UAV because the placed +/// buffer's `buffer_delta` was not element-aligned (or its counter offset was not 4096-aligned). +/// `ClearUnorderedAccessView*` checks this before calling PC clear with a non-null resource. +static UNALIGNED_DELTA_UAVS: std::sync::RwLock>> = std::sync::RwLock::new(None); +static UNALIGNED_DELTA_UAV_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +pub(super) fn is_unaligned_delta_uav(pc_uav: usize) -> bool { + if UNALIGNED_DELTA_UAV_COUNT.load(Ordering::Relaxed) == 0 || pc_uav == 0 { + return false; + } + UNALIGNED_DELTA_UAVS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pc_uav)) +} + +fn note_unaligned_delta_uav(pc_uav: usize, unaligned: bool) { + if pc_uav == 0 { + return; + } + if unaligned { + let mut g = UNALIGNED_DELTA_UAVS.write().unwrap(); + if g.get_or_insert_with(HashSet::new).insert(pc_uav) { + UNALIGNED_DELTA_UAV_COUNT.fetch_add(1, Ordering::Relaxed); + } + } else if UNALIGNED_DELTA_UAV_COUNT.load(Ordering::Relaxed) != 0 { + if let Some(s) = UNALIGNED_DELTA_UAVS.write().unwrap().as_mut() { + if s.remove(&pc_uav) { + UNALIGNED_DELTA_UAV_COUNT.fetch_sub(1, Ordering::Relaxed); + } + } + } +} + +/// Element byte size for standard DXGI typed buffer formats (`None` for unknown/block-compressed). +fn dxgi_buffer_format_bytes(fmt: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> Option { + use windows::Win32::Graphics::Dxgi::Common::*; + match fmt { + DXGI_FORMAT_R32G32B32A32_TYPELESS + | DXGI_FORMAT_R32G32B32A32_FLOAT + | DXGI_FORMAT_R32G32B32A32_UINT + | DXGI_FORMAT_R32G32B32A32_SINT => Some(16), + DXGI_FORMAT_R32G32B32_TYPELESS + | DXGI_FORMAT_R32G32B32_FLOAT + | DXGI_FORMAT_R32G32B32_UINT + | DXGI_FORMAT_R32G32B32_SINT => Some(12), + DXGI_FORMAT_R16G16B16A16_TYPELESS + | DXGI_FORMAT_R16G16B16A16_FLOAT + | DXGI_FORMAT_R16G16B16A16_UNORM + | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R16G16B16A16_SNORM + | DXGI_FORMAT_R16G16B16A16_SINT + | DXGI_FORMAT_R32G32_TYPELESS + | DXGI_FORMAT_R32G32_FLOAT + | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R32G32_SINT => Some(8), + DXGI_FORMAT_R10G10B10A2_TYPELESS + | DXGI_FORMAT_R10G10B10A2_UNORM + | DXGI_FORMAT_R10G10B10A2_UINT + | DXGI_FORMAT_R11G11B10_FLOAT + | DXGI_FORMAT_R8G8B8A8_TYPELESS + | DXGI_FORMAT_R8G8B8A8_UNORM + | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB + | DXGI_FORMAT_R8G8B8A8_UINT + | DXGI_FORMAT_R8G8B8A8_SNORM + | DXGI_FORMAT_R8G8B8A8_SINT + | DXGI_FORMAT_B8G8R8A8_TYPELESS + | DXGI_FORMAT_B8G8R8A8_UNORM + | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB + | DXGI_FORMAT_B8G8R8X8_TYPELESS + | DXGI_FORMAT_B8G8R8X8_UNORM + | DXGI_FORMAT_B8G8R8X8_UNORM_SRGB + | DXGI_FORMAT_R16G16_TYPELESS + | DXGI_FORMAT_R16G16_FLOAT + | DXGI_FORMAT_R16G16_UNORM + | DXGI_FORMAT_R16G16_UINT + | DXGI_FORMAT_R16G16_SNORM + | DXGI_FORMAT_R16G16_SINT + | DXGI_FORMAT_R32_TYPELESS + | DXGI_FORMAT_R32_FLOAT + | DXGI_FORMAT_R32_UINT + | DXGI_FORMAT_R32_SINT => Some(4), + DXGI_FORMAT_R8G8_TYPELESS + | DXGI_FORMAT_R8G8_UNORM + | DXGI_FORMAT_R8G8_UINT + | DXGI_FORMAT_R8G8_SNORM + | DXGI_FORMAT_R8G8_SINT + | DXGI_FORMAT_R16_TYPELESS + | DXGI_FORMAT_R16_FLOAT + | DXGI_FORMAT_R16_UNORM + | DXGI_FORMAT_R16_UINT + | DXGI_FORMAT_R16_SNORM + | DXGI_FORMAT_R16_SINT + | DXGI_FORMAT_B5G6R5_UNORM + | DXGI_FORMAT_B5G5R5A1_UNORM + | DXGI_FORMAT_B4G4R4A4_UNORM => Some(2), + DXGI_FORMAT_R8_TYPELESS + | DXGI_FORMAT_R8_UNORM + | DXGI_FORMAT_R8_UINT + | DXGI_FORMAT_R8_SNORM + | DXGI_FORMAT_R8_SINT + | DXGI_FORMAT_A8_UNORM => Some(1), + _ => crate::gpu::desc::gfx10_format(fmt) + .filter(|&g| (1..=77).contains(&g)) + .map(|g| crate::gpu::desc::format_bytes(g) as u64), + } +} + +/// Element byte size for a buffer UAV (`None` when the typed format is unknown). +fn buffer_uav_element_bytes(desc: &D3D12_UNORDERED_ACCESS_VIEW_DESC) -> Option { + // SAFETY: caller ensures `desc.ViewDimension == D3D12_UAV_DIMENSION_BUFFER`. + let b = unsafe { desc.Anonymous.Buffer }; + if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 { + Some(4) + } else if b.StructureByteStride > 0 { + Some(b.StructureByteStride as u64) + } else { + dxgi_buffer_format_bytes(desc.Format) + } +} + +/// Adjust a PC buffer UAV description by `res_delta` (and `ctr_delta` when `has_counter`). +/// - `Ok(None)`: no delta adjustment needed. +/// - `Ok(Some(patched))`: aligned delta applied (`FirstElement += res_delta / elem`, +/// `CounterOffsetInBytes += ctr_delta`). +/// - `Err(())`: delta buffer UAV cannot be safely shifted on PC (null desc, unknown element size, +/// unaligned `res_delta % elem != 0`, or unaligned counter offset mod 4096) — bind a null PC UAV +/// so PC `ClearUnorderedAccessView*` / pipelines never overwrite `[va & !0xFFFF, va)`. +fn patch_buffer_uav_delta( + desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>, + is_buffer_res: bool, + res_delta: u64, + has_counter: bool, + ctr_delta: u64, +) -> Result, ()> { + if res_delta == 0 && (!has_counter || ctr_delta == 0) { + return Ok(None); + } + let is_buf_view = desc.is_some_and(|d| d.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) || is_buffer_res; + if !is_buf_view { + return Ok(None); + } + let Some(d) = desc else { + return Err(()); + }; + if d.ViewDimension != D3D12_UAV_DIMENSION_BUFFER { + return Err(()); + } + let elem = buffer_uav_element_bytes(d).filter(|&e| e > 0).ok_or(())?; + if res_delta % elem != 0 { + return Err(()); + } + let mut patched = *d; + // SAFETY: `ViewDimension == D3D12_UAV_DIMENSION_BUFFER` verified above. + unsafe { + let b = &mut patched.Anonymous.Buffer; + if has_counter && ctr_delta != 0 { + let new_ctr = b.CounterOffsetInBytes.checked_add(ctr_delta).ok_or(())?; + if new_ctr % 4096 != 0 { + return Err(()); + } + b.CounterOffsetInBytes = new_ctr; + } + b.FirstElement = b.FirstElement.checked_add(res_delta / elem).ok_or(())?; + } + Ok(Some(patched)) +} + unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) { let orig_desc = desc.as_ref().copied(); // Route depth+UAV textures (`ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS`) to their @@ -3286,16 +3488,58 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, // another non-UAV resource): a null view – a UAV of it is an invalid call (0x887A0001) let uav_rd_opt = if uav_res == res { rd_opt } else { ID3D12Resource::from_raw_borrowed(&uav_res).map(|r| r.GetDesc()) }; let no_uav = uav_rd_opt.is_some_and(|d| d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0); + // Placed buffers with `buffer_delta != 0` start below the title's VA (`va & !0xFFFF`). Shift + // the PC UAV's `FirstElement` (and `CounterOffsetInBytes`) by the delta so PC UAV clears and + // pipelines hit the title's true buffer instead of `[va & !0xFFFF, va)` in live CPU RAM; if + // the delta is unaligned, bind a null PC UAV and skip PC clears on it. + let res_delta = buffer_delta(uav_res as usize); + let ctr_delta = if counter.is_null() { 0 } else { buffer_delta(counter as usize) }; + let is_buf_res = uav_rd_opt.is_some_and(|d| d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER); + let (pc_uav_desc_patched, unaligned_delta) = if depth_twin.is_none() && !no_uav { + match patch_buffer_uav_delta(uav_desc.as_ref(), is_buf_res, res_delta, !counter.is_null(), ctr_delta) { + Ok(patched) => (patched, false), + Err(()) => (None, true), + } + } else { + (None, false) + }; + let pc_uav_desc = pc_uav_desc_patched.as_ref().map_or(uav_desc, |d| d as *const _); let null_desc = null_uav_desc(uav_desc.as_ref(), uav_rd_opt.as_ref()); + let null_buf_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32_UINT, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + ..Default::default() + }; let pc_uav = |at: u64| { + note_unaligned_delta_uav(at as usize, unaligned_delta); + if let Some((twin_res, _)) = &depth_twin { + super::depth_uav::note_uav_twin(at as usize, *twin_res as usize); + } else { + super::depth_uav::clear_uav_twin(at as usize); + } if no_uav { static N: AtomicU64 = AtomicU64::new(0); - if N.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_warn!("D3D12.X: a UAV of a resource that cannot have one on the PC (a depth buffer) – a null view"); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + if let Some(d) = uav_rd_opt { + crate::xlog_warn!( + "D3D12.X: a UAV of a resource that cannot have one on the PC (res {res:p}, fmt {}, {}x{}, samples {}, flags {:#x}) – a null view", + d.Format.0, d.Width, d.Height, d.SampleDesc.Count, d.Flags.0 + ); + } else { + crate::xlog_warn!("D3D12.X: a UAV of a resource that cannot have one on the PC (res {res:p}) – a null view"); + } } f(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_desc, at) + } else if unaligned_delta { + static N: AtomicU64 = AtomicU64::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 8 { + crate::xlog_warn!( + "D3D12.X: buffer UAV on placed resource {res:p} has unaligned delta (res_delta={res_delta:#x}, ctr_delta={ctr_delta:#x}) – binding null PC UAV" + ); + } + f(this, std::ptr::null_mut(), std::ptr::null_mut(), &null_buf_desc, at) } else { - f(this, uav_res, counter, uav_desc, at) + f(this, uav_res, counter, pc_uav_desc, at) } }; let Some(slot) = super::console_heap::slot(cpu) else { return pc_uav(cpu) }; @@ -4243,21 +4487,18 @@ fn heap_block(heap: usize) -> Option<(usize, bool)> { Some((p, cpu_readback)) } -/// ID3D12Heap::Release: its block of unified memory goes with it. +/// ID3D12Heap::Release: its block of unified memory goes with it (deferred until active GPU +/// queues finish so in-flight lists never lose their backing block). unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - let gone = HEAP_UMA.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block); - if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); + release_taking_first( + this, + || HEAP_UMA.write().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block), + |gone| { + if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { + super::late_release::hold_uma(p, u.is_sparse(p)); } - } - } - n + }, + ) } creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]); @@ -5535,8 +5776,7 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL } let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { - keep_compute_blob(key, *ppv, dxil.len()); - if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { + if let (Some(p), Some(b)) = (disk.as_deref(), keep_compute_blob(key, *ppv, dxil.len())) { driver_cache::keep(p, &b, in_driver); } } else if reused && from_disk { @@ -5884,6 +6124,30 @@ mod compute_blob_tests { } assert_eq!(*total, 0); } + + /// A blob the in-memory store has no room for still goes back to its caller (which writes + /// it to the disk cache); one that fits is kept in memory as well. + #[test] + fn a_blob_over_the_memory_budget_still_reaches_its_caller() { + let mut store = (super::HashMap::new(), 0usize); + let fits = super::remember_compute_blob(&mut store, (1, 2, 0), vec![7u8; 64]).expect("a blob that fits"); + assert_eq!(fits.len(), 64); + assert_eq!(store.1, 64); + assert!(store.0.contains_key(&(1, 2, 0))); + let duplicate = super::remember_compute_blob(&mut store, (1, 2, 0), vec![3; 64]).unwrap(); + assert!(std::sync::Arc::ptr_eq(&fits, &duplicate)); + assert_eq!(store.1, 64, "a concurrent insertion of the same blob is charged once"); + + // the store is full: nothing more is kept in memory … + store.1 = super::COMPUTE_BLOBS_MAX; + let over = super::remember_compute_blob(&mut store, (3, 4, 0), vec![9u8; 128]); + assert!(!store.0.contains_key(&(3, 4, 0))); + assert_eq!(store.1, super::COMPUTE_BLOBS_MAX, "a blob that is not kept is not charged"); + // … but the caller gets it for the disk + assert_eq!(over.expect("the blob for the disk cache").as_slice(), &[9u8; 128][..]); + + assert!(super::remember_compute_blob(&mut store, (5, 6, 0), Vec::new()).is_none(), "an empty blob is nothing to keep"); + } } /// Read `GetCachedBlob` from either an adopted or raw PC `ID3D12PipelineState`. @@ -5933,13 +6197,36 @@ fn insert_cached_blob( } /// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute -/// passes owned by `TwoPassPso`). -unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || compute_blob(key).is_some() { - return; +/// passes owned by `TwoPassPso`), for the disk cache; kept in memory too while `COMPUTE_BLOBS_MAX` +/// has room. +unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) -> Option>> { + if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() { + return None; } - let Some(bytes) = read_pso_cached_blob(pso) else { return }; - insert_cached_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, key, bytes); + if let Some(b) = compute_blob(key) { + return Some(b); + } + let bytes = read_pso_cached_blob(pso)?; + let mut g = COMPUTE_BLOBS.lock().unwrap(); + remember_compute_blob(g.get_or_insert_with(|| (HashMap::new(), 0)), key, bytes) +} + +/// `bytes`, the driver's blob of the pipeline `key`, for its caller – and in `store` (the blobs +/// kept in memory and their bytes in all) while `COMPUTE_BLOBS_MAX` has room. The blob is +/// returned either way so once the RAM store fills, slower pipelines still persist to disk. +fn remember_compute_blob(store: &mut (HashMap<(u64, usize, i32), std::sync::Arc>>, usize), key: (u64, usize, i32), bytes: Vec) -> Option>> { + if let Some(current) = store.0.get(&key) { + return Some(current.clone()); + } + if bytes.is_empty() { + return None; + } + let bytes = std::sync::Arc::new(bytes); + if bytes.len() <= COMPUTE_BLOBS_MAX.saturating_sub(store.1) { + store.1 += bytes.len(); + store.0.insert(key, bytes.clone()); + } + Some(bytes) } /// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), @@ -7370,8 +7657,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: } let creused = hc >= 0 && chas_isa_blob && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; if hc >= 0 && !creused && !compute.is_null() { - keep_compute_blob(ckey, compute, tp.cs.len()); - if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { + if let (Some(p), Some(b)) = (cdisk.as_deref(), keep_compute_blob(ckey, compute, tp.cs.len())) { driver_cache::keep(p, &b, cin_driver); } } else if creused && cfrom_disk { @@ -8523,25 +8809,42 @@ unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { n } -unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { +/// Release `this` through its driver vtable. When this call drops the last reference, `take` +/// runs first, while the call still holds one: once the driver has freed the object, another +/// thread can get a new one at the same address and record its own entries there, which `take` +/// would then remove. What `take` returns goes to `after` once the object is gone (memory the +/// object was made on is freed after it). Two last-but-one releases at once both miss +/// `AddRef == 2`; the one whose `Release` ends at 0 then runs `take` after the object is gone, +/// as before. +unsafe fn release_taking_first(this: *mut c_void, take: impl FnOnce() -> T, after: impl FnOnce(T)) -> u32 { + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let mut take = Some(take); + let taken = if add_ref(this) == 2 { take.take().map(|t| t()) } else { None }; + f(this); let n = f(this); - if n == 0 { - super::list_x::on_queue_release(this as usize); + let taken = taken.or_else(|| if n == 0 { take.take().map(|t| t()) } else { None }); + if let Some(t) = taken { + after(t); } n } +unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { + release_taking_first(this, || super::list_x::on_queue_release(this as usize), drop) +} + unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - dispatch_chain::allocator_reset(this as usize); - super::console_list::allocator_reset(this); - super::alloc_pool::forget(this as usize); - super::list_x::on_allocator_release(this as usize); - } - n + release_taking_first( + this, + || { + dispatch_chain::allocator_reset(this as usize); + super::console_list::allocator_reset(this); + super::alloc_pool::forget(this as usize); + super::list_x::on_allocator_release(this as usize); + }, + drop, + ) } /// Reset the (adopted) PC allocator `raw` itself. @@ -9630,7 +9933,7 @@ mod queue_tests { impl Drop for ClassCleanup { fn drop(&mut self) { let mut exts = Vec::new(); - CLASSES.lock().unwrap().retain(|c| { + CLASSES.write().unwrap().retain(|c| { if c.orig == self.0 { exts.push(c.ext); false @@ -9638,7 +9941,7 @@ mod queue_tests { true } }); - if let Some(set) = EXTS.lock().unwrap().as_mut() { + if let Some(set) = EXTS.write().unwrap().as_mut() { for e in exts { set.remove(&e); } @@ -11641,3 +11944,205 @@ mod outside_buffer_tests { } } } + +#[cfg(test)] +mod release_order_tests { + use super::*; + use std::sync::atomic::AtomicU32; + + /// A driver object whose last Release runs `freed` with its address, as another thread's + /// new object made at that address the moment the driver frees it would. + #[repr(C)] + struct Reused { + vt: *const usize, + refs: u32, + freed: fn(usize), + ext_vt: [usize; 4], + orig_vt: [usize; 3], + } + unsafe extern "system" fn reused_add_ref(this: *mut c_void) -> u32 { + (*(this as *mut Reused)).refs += 1; + (*(this as *mut Reused)).refs + } + unsafe extern "system" fn reused_release(this: *mut c_void) -> u32 { + let o = &mut *(this as *mut Reused); + o.refs -= 1; + if o.refs == 0 { + (o.freed)(this as usize); + } + o.refs + } + fn reused(refs: u32, freed: fn(usize)) -> *mut Reused { + let o = Box::into_raw(Box::new(Reused { vt: std::ptr::null(), refs, freed, ext_vt: [0; 4], orig_vt: [0; 3] })); + unsafe { + (*o).orig_vt[1] = reused_add_ref as usize; + (*o).orig_vt[2] = reused_release as usize; + (*o).ext_vt[0] = (*o).orig_vt.as_ptr() as usize; + (*o).ext_vt[1] = (*o).orig_vt[0]; + (*o).ext_vt[2] = (*o).orig_vt[1]; + (*o).ext_vt[3] = (*o).orig_vt[2]; + (*o).vt = (*o).ext_vt.as_ptr().add(1); + } + o + } + + std::thread_local! { + static EVENTS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + fn event(e: &'static str) { + EVENTS.with(|v| v.borrow_mut().push(e)); + } + + #[test] + fn take_runs_before_the_last_release_and_after_once_it_is_gone() { + EVENTS.with(|v| v.borrow_mut().clear()); + let o = reused(2, |_| event("freed")); + unsafe { + let raw = o as *mut c_void; + assert_eq!(release_taking_first(raw, || event("take"), |()| event("after")), 1); + assert!(EVENTS.with(|v| v.borrow().is_empty()), "nothing runs while references are left"); + assert_eq!(release_taking_first(raw, || { event("take"); 7 }, |t| { assert_eq!(t, 7); event("after") }), 0); + drop(Box::from_raw(o)); + } + assert_eq!(EVENTS.with(|v| v.borrow().clone()), ["take", "freed", "after"]); + } + + #[repr(C)] + struct Racy { + vt: *const usize, + refs: AtomicU32, + ext_vt: [usize; 4], + orig_vt: [usize; 3], + } + static RACY_BARRIER: std::sync::LazyLock = std::sync::LazyLock::new(|| std::sync::Barrier::new(2)); + unsafe extern "system" fn racy_add_ref(this: *mut c_void) -> u32 { + let n = (*(this as *mut Racy)).refs.fetch_add(1, Ordering::AcqRel) + 1; + RACY_BARRIER.wait(); + n + } + unsafe extern "system" fn racy_release(this: *mut c_void) -> u32 { + (*(this as *mut Racy)).refs.fetch_sub(1, Ordering::AcqRel) - 1 + } + + #[test] + fn two_last_releases_at_once_take_the_entries_once() { + static TAKES: AtomicU32 = AtomicU32::new(0); + static AFTERS: AtomicU32 = AtomicU32::new(0); + let o = Box::into_raw(Box::new(Racy { vt: std::ptr::null(), refs: AtomicU32::new(2), ext_vt: [0; 4], orig_vt: [0; 3] })); + unsafe { + (*o).orig_vt[1] = racy_add_ref as usize; + (*o).orig_vt[2] = racy_release as usize; + (*o).ext_vt[0] = (*o).orig_vt.as_ptr() as usize; + (*o).ext_vt[1] = (*o).orig_vt[0]; + (*o).ext_vt[2] = (*o).orig_vt[1]; + (*o).ext_vt[3] = (*o).orig_vt[2]; + (*o).vt = (*o).ext_vt.as_ptr().add(1); + } + let addr = o as usize; + let release = move || unsafe { + release_taking_first(addr as *mut c_void, || TAKES.fetch_add(1, Ordering::AcqRel), |_| { + AFTERS.fetch_add(1, Ordering::AcqRel); + }) + }; + let a = std::thread::spawn(release); + let b = std::thread::spawn(release); + let mut left = [a.join().unwrap(), b.join().unwrap()]; + left.sort_unstable(); + unsafe { drop(Box::from_raw(o)) }; + assert_eq!(left[0], 0, "one of the two releases is the last"); + assert_eq!((TAKES.load(Ordering::Acquire), AFTERS.load(Ordering::Acquire)), (1, 1), "the entries are taken once, by the last release"); + } + + #[test] + fn mem_heap_release_keeps_a_new_heap_at_the_freed_address() { + let o = reused(1, |addr| { + let h = HeapUma { size: 0x1_0000, align: 0x1_0000, prefer_coherent: false, cpu_readback: false, block: None }; + HEAP_UMA.write().unwrap().get_or_insert_with(HashMap::new).insert(addr, h); + }); + let addr = o as usize; + unsafe { + assert_eq!(mem_heap_release(o as *mut c_void), 0); + drop(Box::from_raw(o)); + } + let kept = HEAP_UMA.write().unwrap().as_mut().and_then(|m| m.remove(&addr)).is_some(); + assert!(kept, "mem_heap_release dropped the heap made at the freed address after the driver freed the old one"); + } +} + +#[cfg(test)] +mod uav_buffer_delta_tests { + use super::*; + use windows::Win32::Graphics::Dxgi::Common::*; + + fn buf_uav(fmt: DXGI_FORMAT, first: u64, num: u32, stride: u32, ctr_off: u64, raw: bool) -> D3D12_UNORDERED_ACCESS_VIEW_DESC { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: fmt, + ViewDimension: D3D12_UAV_DIMENSION_BUFFER, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Buffer: D3D12_BUFFER_UAV { + FirstElement: first, + NumElements: num, + StructureByteStride: stride, + CounterOffsetInBytes: ctr_off, + Flags: if raw { D3D12_BUFFER_UAV_FLAG_RAW } else { D3D12_BUFFER_UAV_FLAG_NONE }, + }, + }, + } + } + + #[test] + fn patch_buffer_uav_delta_shifts_raw_structured_and_typed_views() { + // Zero delta is a no-op. + let raw = buf_uav(DXGI_FORMAT_R32_TYPELESS, 10, 64, 0, 0, true); + assert!(patch_buffer_uav_delta(Some(&raw), true, 0, false, 0).unwrap().is_none()); + + // Raw buffer (4-byte elements): delta 0x200 -> +128 elements. + let p = patch_buffer_uav_delta(Some(&raw), true, 0x200, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 10 + 128); + + // Structured buffer (24-byte stride): 0x300 % 24 == 0 -> +32 elements; 0x100 % 24 != 0 -> Err. + let structured = buf_uav(DXGI_FORMAT_UNKNOWN, 5, 100, 24, 0, false); + let p = patch_buffer_uav_delta(Some(&structured), true, 0x300, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 5 + 32); + assert!(patch_buffer_uav_delta(Some(&structured), true, 0x100, false, 0).is_err()); + + // Typed buffers (R8=1, R16=2, R32=4, RG32=8, RGBA32=16, R11G11B10=4, R10G10B10A2=4). + for (fmt, elem) in [ + (DXGI_FORMAT_R8_UINT, 1u64), + (DXGI_FORMAT_R16_UNORM, 2), + (DXGI_FORMAT_R32_UINT, 4), + (DXGI_FORMAT_R11G11B10_FLOAT, 4), + (DXGI_FORMAT_R10G10B10A2_UNORM, 4), + (DXGI_FORMAT_R32G32_FLOAT, 8), + (DXGI_FORMAT_R32G32B32A32_FLOAT, 16), + ] { + let typed = buf_uav(fmt, 3, 16, 0, 0, false); + let p = patch_buffer_uav_delta(Some(&typed), true, elem * 7, false, 0).unwrap().unwrap(); + assert_eq!(unsafe { p.Anonymous.Buffer.FirstElement }, 10); + if elem > 1 { + assert!(patch_buffer_uav_delta(Some(&typed), true, elem - 1, false, 0).is_err()); + } + } + + // Counter buffer offset alignment (4096 bytes). + let with_ctr = buf_uav(DXGI_FORMAT_UNKNOWN, 0, 16, 16, 4096, false); + let p = patch_buffer_uav_delta(Some(&with_ctr), true, 64, true, 8192).unwrap().unwrap(); + assert_eq!(unsafe { (p.Anonymous.Buffer.FirstElement, p.Anonymous.Buffer.CounterOffsetInBytes) }, (4, 12288)); + assert!(patch_buffer_uav_delta(Some(&with_ctr), true, 64, true, 128).is_err()); + + // NULL desc or unknown typed format with non-zero delta must fail safely to null PC UAV. + assert!(patch_buffer_uav_delta(None, true, 0x100, false, 0).is_err()); + let unknown = buf_uav(DXGI_FORMAT_UNKNOWN, 0, 16, 0, 0, false); + assert!(patch_buffer_uav_delta(Some(&unknown), true, 0x100, false, 0).is_err()); + } + + #[test] + fn unaligned_delta_uav_tracking_sets_and_clears() { + let handle = 0xDEAD_BEEF_1234usize; + assert!(!is_unaligned_delta_uav(handle)); + note_unaligned_delta_uav(handle, true); + assert!(is_unaligned_delta_uav(handle)); + note_unaligned_delta_uav(handle, false); + assert!(!is_unaligned_delta_uav(handle)); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 839f956a27..79162a0b0b 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -9,6 +9,9 @@ static PIECES: AtomicU64 = AtomicU64::new(0); static DISPATCHES: AtomicU64 = AtomicU64::new(0); /// slabs dispatched (`pso::dispatch_slabs`) static SLABS: AtomicU64 = AtomicU64::new(0); +/// `.plib` hits and misses for split compute pipelines (pieces and whole forms) +static PLIB_HITS: AtomicU64 = AtomicU64::new(0); +static PLIB_MISSES: AtomicU64 = AtomicU64::new(0); /// scratch alive now, the most there was, and the most a dispatch would have needed at once (bytes) static LIVE: AtomicU64 = AtomicU64::new(0); static PEAK: AtomicU64 = AtomicU64::new(0); @@ -28,8 +31,8 @@ static SLICER_LABELED: std::sync::atomic::AtomicUsize = std::sync::atomic::Atomi pub(crate) fn log_counts() { let mib = |a: &AtomicU64| a.load(Ordering::Relaxed) >> 20; let n = |a: &AtomicU64| a.load(Ordering::Relaxed); - crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab); ExecuteIndirect: {} chained ({} of them whole, {} slabs lost), {} whole", - n(&PROGRAMS), n(&PIECES), n(&DISPATCHES), n(&SLABS), mib(&LIVE), mib(&PEAK), mib(&WANTED), + crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; plib {} hits / {} misses; scratch {} MiB (most {}, largest dispatch {} in one slab); ExecuteIndirect: {} chained ({} of them whole, {} slabs lost), {} whole", + n(&PROGRAMS), n(&PIECES), n(&DISPATCHES), n(&SLABS), n(&PLIB_HITS), n(&PLIB_MISSES), mib(&LIVE), mib(&PEAK), mib(&WANTED), n(&INDIRECT), n(&INDIRECT_WHOLE), n(&INDIRECT_LOST), n(&WHOLE_INDIRECT)); } @@ -64,7 +67,7 @@ struct PipelineBuilder { } impl PipelineBuilder { - unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Option { + unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Result { let lib_key = split_plib_key(dxil, &self.samplers, self.flags.0); let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; let lib_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { @@ -76,15 +79,23 @@ impl PipelineBuilder { }; let mut raw = std::ptr::null_mut(); if pso_lib::try_load_compute(self.device.as_raw(), &lib_key, &lib_desc, iid, &mut raw) && !raw.is_null() { - return Some(ID3D12PipelineState::from_raw(raw)); + let hits = PLIB_HITS.fetch_add(1, Ordering::Relaxed) + 1; + if hits <= 4 { + crate::xlog_info!("compute split: .plib hit #{hits} for cs {:016x} ({lib_key})", self.record); + } + return Ok(ID3D12PipelineState::from_raw(raw)); + } + let misses = PLIB_MISSES.fetch_add(1, Ordering::Relaxed) + 1; + if misses <= 4 { + crate::xlog_info!("compute split: .plib miss #{misses} for cs {:016x} ({lib_key})", self.record); } let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), dxil, self.record, iid, &mut raw, true); if hr >= 0 && !raw.is_null() { pso_lib::store_pipeline(self.device.as_raw(), &lib_key, raw); - Some(ID3D12PipelineState::from_raw(raw)) + Ok(ID3D12PipelineState::from_raw(raw)) } else { - None + Err(hr) } } } @@ -94,10 +105,10 @@ struct Chain { tail: Vec, words: u32, whole_code: Vec, - whole: OnceLock, + whole: OnceLock>, whole_started: AtomicBool, - whole_failed: AtomicBool, - build_whole: Mutex<()>, + /// after a whole build that ran out of memory: when it may be tried, once more + retry_at: Mutex>, /// its command signature for ExecuteIndirect (`pso::chain_command_signature`) signature: OnceLock, /// the most slabs one of its ExecuteIndirects had @@ -106,6 +117,9 @@ struct Chain { warned: AtomicBool, } +/// How long a split program's whole form waits after a build that ran out of memory, before its last try. +const WHOLE_RETRY: std::time::Duration = std::time::Duration::from_secs(10); + pub(in crate::hle::d3d12x) enum WholeStatus { /// Not a split compute pipeline. NotSplit, @@ -120,17 +134,39 @@ pub(in crate::hle::d3d12x) enum WholeStatus { impl Chain { unsafe fn whole(&self) -> Result { - if let Some(p) = self.whole.get() { return Ok(p.clone()); } - let _guard = self.build_whole.lock().unwrap(); - if let Some(p) = self.whole.get() { return Ok(p.clone()); } - let p = self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?; - super::super::dred::label_text(p.as_raw() as usize, || format!("cs {:016x} whole", self.builder.record)); - let _ = self.whole.set(p.clone()); - Ok(p) + if let Some(p) = self.whole.get() { + return p.clone().ok_or_else(|| "whole compute pipeline".into()); + } + let mut retry_at = self.retry_at.lock().unwrap(); + if let Some(p) = self.whole.get() { + return p.clone().ok_or_else(|| "whole compute pipeline".into()); + } + if retry_at.is_some_and(|t| std::time::Instant::now() < t) { + return Err("whole compute pipeline: out of memory".into()); + } + match self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)) { + Ok(p) => { + super::super::dred::label_text(p.as_raw() as usize, || format!("cs {:016x} whole", self.builder.record)); + let _ = self.whole.set(Some(p.clone())); + Ok(p) + } + Err(hr) if hr == crate::util::E_OUTOFMEMORY && retry_at.is_none() => { + *retry_at = Some(std::time::Instant::now() + WHOLE_RETRY); + Err("whole compute pipeline: out of memory".into()) + } + Err(_) => { + let _ = self.whole.set(None); + Err("whole compute pipeline".into()) + } + } + } + + fn whole_in_cooldown(&self) -> bool { + self.retry_at.lock().unwrap().is_some_and(|t| std::time::Instant::now() < t) } fn start_whole_async(self: &Arc) { - if self.whole.get().is_some() || self.whole_failed.load(Ordering::Acquire) { + if self.whole.get().is_some() || self.whole_in_cooldown() { return; } if self.whole_started.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { @@ -164,7 +200,10 @@ fn enqueue_whole_async(chain: Arc) -> bool { }; let record = chain.builder.record; if let Err(e) = unsafe { chain.whole() } { - chain.whole_failed.store(true, Ordering::Release); + if chain.whole.get().is_none() { + // Transient E_OUTOFMEMORY: allow one retry after WHOLE_RETRY. + chain.whole_started.store(false, Ordering::Release); + } crate::xlog_warn!("D3D12.X: background whole compute PSO for cs {record:016x} failed: {e}"); } } @@ -183,12 +222,75 @@ fn enqueue_whole_async(chain: Arc) -> bool { static CHAINS: LazyLock>>> = LazyLock::new(Default::default); +/// Canonical COM object identity (`IUnknown*`) for a D3D12 device pointer so tear-off interfaces +/// share cache slots while synthetic/unreadable test pointers preserve their raw address safely. +unsafe fn canonical_device_key(this: *mut c_void) -> usize { + if this.is_null() || !crate::gpu::shader::readable(this as usize, std::mem::size_of::()) { + return this as usize; + } + let v = *(this as *const usize); + if !crate::gpu::shader::readable(v, std::mem::size_of::()) || *(v as *const usize) == 0 { + return this as usize; + } + if is_ext(v) && orig_fn(this, 0) == 0 { + return this as usize; + } + ID3D12Device::from_raw_borrowed(&this) + .and_then(|d| d.cast::().ok()) + .map_or(this as usize, |u| u.as_raw() as usize) +} + +/// Dispatch-chain root signatures shared per `(canonical_device_key, static_samplers)`. +/// Intentionally retained for the process lifetime (bounded to one `ID3D12RootSignature` per +/// distinct `(device, static_sampler_set)`) so split programs sharing pieces hit `COMPUTE_BLOBS` +/// instead of allocating a fresh root signature object per program. +static SIGNATURES: LazyLock), ID3D12RootSignature>>> = LazyLock::new(Default::default); + +fn sampler_key(samplers: &[pso::StaticSampler]) -> Vec { + samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect() +} + +unsafe fn root_signature_device(rs: &ID3D12RootSignature) -> Option { + let mut owner: Option = None; + rs.GetDevice(&mut owner).ok()?; + owner +} + +unsafe fn rs_belongs_to_device(rs: &ID3D12RootSignature, dev_key: usize) -> bool { + root_signature_device(rs).is_some_and(|owner| canonical_device_key(owner.as_raw()) == dev_key) +} + +/// Shared dispatch-chain root signature for `dev` and `samplers`, isolating distinct D3D12 devices +/// so `COMPUTE_BLOBS` never reuses a root signature across devices or sampler layouts. +unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler]) -> Option { + let dev_key = canonical_device_key(dev.as_raw()); + let key = (dev_key, sampler_key(samplers)); + if let Some(rs) = SIGNATURES.lock().unwrap().get(&key).cloned() { + if rs_belongs_to_device(&rs, dev_key) { + return Some(rs); + } + } + let created = match pso::dispatch_chain_root_signature(dev, samplers) { + Ok(rs) => rs, + Err(e) => { + note_translation_error(format!("dispatch-chain root signature: {e}")); + return None; + } + }; + let mut g = SIGNATURES.lock().unwrap(); + if g.get(&key).is_some_and(|rs| !rs_belongs_to_device(rs, dev_key)) { + g.insert(key, created.clone()); + return Some(created); + } + Some(g.entry(key).or_insert(created).clone()) +} + pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, iid: *const GUID, result: *mut *mut c_void, record: u64, whole: &[u8], samplers: &[pso::StaticSampler], plan: Arc) -> Option { if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; } let dev = ID3D12Device::from_raw_borrowed(&this)?; - let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; + let signature = signature_for(dev, samplers)?; let rs = signature.as_raw() as usize; let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, samplers: samplers.to_vec(), flags: desc.Flags, node: desc.NodeMask, record }); @@ -196,7 +298,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let plan = plan.clone(); let builder = builder.clone(); let iid = if i == 0 { *iid } else { pc_iid(Kind::PipelineState) }; - Box::new(move || builder.pipeline(&plan.pieces[i], &iid).map_or(0, |p| p.into_raw() as usize)) as super::super::pso_async::Job + Box::new(move || builder.pipeline(&plan.pieces[i], &iid).ok().map_or(0, |p| p.into_raw() as usize)) as super::super::pso_async::Job }).collect(); // Take ownership of every success, including when a different piece failed. let built: Vec<_> = super::super::pso_async::build_pieces(jobs).into_iter() @@ -214,8 +316,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT whole_code: whole.to_vec(), whole: OnceLock::new(), whole_started: AtomicBool::new(false), - whole_failed: AtomicBool::new(false), - build_whole: Mutex::new(()), + retry_at: Mutex::new(None), signature: OnceLock::new(), slabs: Default::default(), warned: AtomicBool::new(false), @@ -248,12 +349,13 @@ pub(in crate::hle::d3d12x) unsafe fn whole_nonblocking(pso: usize) -> WholeStatu let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return WholeStatus::NotSplit; }; - if let Some(p) = chain.whole.get() { - WHOLE_INDIRECT.fetch_add(1, Ordering::Relaxed); - return WholeStatus::Ready(p.clone()); - } - if chain.whole_failed.load(Ordering::Acquire) { - return WholeStatus::Failed; + match chain.whole.get() { + Some(Some(p)) => { + WHOLE_INDIRECT.fetch_add(1, Ordering::Relaxed); + return WholeStatus::Ready(p.clone()); + } + Some(None) => return WholeStatus::Failed, + None => {} } if !super::super::pso_async::enabled() { return match chain.whole() { @@ -261,12 +363,12 @@ pub(in crate::hle::d3d12x) unsafe fn whole_nonblocking(pso: usize) -> WholeStatu WHOLE_INDIRECT.fetch_add(1, Ordering::Relaxed); WholeStatus::Ready(p) } - Err(_) => { - chain.whole_failed.store(true, Ordering::Release); - WholeStatus::Failed - } + Err(_) => WholeStatus::Failed, }; } + if chain.whole_in_cooldown() { + return WholeStatus::Failed; + } chain.start_whole_async(); WholeStatus::Pending } @@ -534,16 +636,23 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, let most = scratch.as_ref().map_or(1, |(s, _)| (s.bytes / group).max(1)); let slabs = pso::dispatch_slabs(grid, most); let Some((scratch, used)) = scratch else { - if let Some(whole) = chain.whole.get() { - list.SetPipelineState(whole); - list.Dispatch(x, y, z); - return Ok(()); + match chain.whole.get() { + Some(Some(whole)) => { + list.SetPipelineState(whole); + list.Dispatch(x, y, z); + return Ok(()); + } + Some(None) => return Err("whole compute pipeline".into()), + None => {} } if !super::super::pso_async::enabled() { list.SetPipelineState(&chain.whole()?); list.Dispatch(x, y, z); return Ok(()); } + if chain.whole_in_cooldown() { + return Err("whole compute pipeline: out of memory".into()); + } chain.start_whole_async(); return Err("whole compute pipeline still building in background".into()); }; @@ -634,7 +743,7 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( } bind()?; // under the title's own predication XCL's cannot be set: the slabs past the rounds are lost - let full = if predicated { None } else { chain.whole.get().cloned() }; + let full = if predicated { None } else { chain.whole.get().and_then(|o| o.clone()) }; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); pso::record_dispatch_chain_indirect(list, &sig, &buffer, rounds, full.is_some(), &scratch.buffer, std::iter::once(&first).chain(&chain.tail)); let at = pso::chain_predicate_offset(rounds, pieces); @@ -664,23 +773,37 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( #[cfg(test)] mod tests { use super::{scratch_bytes, LEAST}; + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Direct3D12::{ + ID3D12Device, ID3D12PipelineState, D3D12_COMPUTE_PIPELINE_STATE_DESC, D3D12_PIPELINE_STATE_FLAG_NONE, + }; const MB: u64 = 1 << 20; - #[test] - fn a_list_recorded_after_another_goes_on_in_its_scratch() { - use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; - use windows::Win32::Graphics::Direct3D12::{D3D12CreateDevice, ID3D12Device}; + fn test_device() -> Option { + use windows::Win32::Graphics::Direct3D12::D3D12CreateDevice; use windows::Win32::Graphics::Dxgi::*; let mut dev: Option = None; if unsafe { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev) }.is_err() { let warp = unsafe { CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) }; - if warp.and_then(|w| unsafe { D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev) }).is_err() { - crate::gpu::recomp::runner::skip_test("no GPU"); - return; - } + let _ = warp.and_then(|w| unsafe { D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev) }); } - let dev = dev.unwrap(); + dev + } + + fn warp_device() -> Option { + use windows::Win32::Graphics::Dxgi::*; + let warp = unsafe { CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()) }.ok()?; + crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_11_0).ok() + } + + #[test] + fn a_list_recorded_after_another_goes_on_in_its_scratch() { + let Some(dev) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; let (a, b, c, alloc) = (0x7E57_5C01usize, 0x7E57_5C02usize, 0x7E57_5C03usize, 0x7E57_5CA0usize); let (first, used) = unsafe { super::scratch_for(&dev, a, alloc, MB, 4096) }.unwrap(); assert!(!used); @@ -806,4 +929,324 @@ mod tests { assert_ne!(split_key, super::split_plib_key(dxil, &[], 0)); assert_ne!(split_key, super::split_plib_key(dxil, &samplers, 1)); } + + #[test] + fn signature_for_reuses_root_signature_per_device_and_separates_devices_and_samplers() { + let Some(dev1) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Some(dev2) = warp_device().filter(|d| d.as_raw() != dev1.as_raw()) else { + crate::gpu::recomp::runner::skip_test("second distinct D3D12 device unavailable"); + return; + }; + let sampler: super::pso::StaticSampler = ([0x1111_0001, 0x2222_0002, 0x3333_0003, 0x4444_0004], false); + unsafe { + let rs1_a = super::signature_for(&dev1, &[]).expect("dispatch chain RS 1"); + let rs1_b = super::signature_for(&dev1, &[]).expect("dispatch chain RS 1 cached"); + assert_eq!(rs1_a.as_raw(), rs1_b.as_raw(), "repeated builds on the same device must share one RS"); + + let rs1_samp_a = super::signature_for(&dev1, &[sampler]).expect("dispatch chain RS with sampler"); + let rs1_samp_b = super::signature_for(&dev1, &[sampler]).expect("dispatch chain RS with sampler cached"); + assert_eq!(rs1_samp_a.as_raw(), rs1_samp_b.as_raw()); + assert_ne!(rs1_samp_a.as_raw(), rs1_a.as_raw(), "static samplers must partition the RS cache"); + + let rs2 = super::signature_for(&dev2, &[]).expect("dispatch chain RS for second device"); + assert_ne!(rs2.as_raw(), rs1_a.as_raw(), "distinct D3D12 devices must never share COM root signatures"); + + let cs = super::super::dummy().cs.clone(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::ManuallyDrop::new(Some(rs2.clone())), + CS: super::super::bytecode(&cs), + ..Default::default() + }; + let _pso: ID3D12PipelineState = dev2.CreateComputePipelineState(&desc).expect("dev2 accepts its own dispatch-chain RS"); + } + } + + #[test] + fn signature_retention_and_device_child_lifetime() { + let Some(dev_hw) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + let Some(dev_warp) = warp_device() else { + crate::gpu::recomp::runner::skip_test("WARP device unavailable"); + return; + }; + unsafe { + let warp_key = super::canonical_device_key(dev_warp.as_raw()); + let refs_of = |d: &ID3D12Device| -> u32 { + type F = unsafe extern "system" fn(*mut std::ffi::c_void) -> u32; + let vt = *(d.as_raw() as *const *const usize); + let add: F = std::mem::transmute(*vt.add(1)); + let rel: F = std::mem::transmute(*vt.add(2)); + add(d.as_raw()); + rel(d.as_raw()) + }; + let before_refs = refs_of(&dev_warp); + let rs_warp = super::signature_for(&dev_warp, &[]).expect("WARP dispatch chain RS"); + let after_refs = refs_of(&dev_warp); + assert!(super::rs_belongs_to_device(&rs_warp, warp_key)); + let owner = super::root_signature_device(&rs_warp).expect("GetDevice while device live"); + assert_eq!(super::canonical_device_key(owner.as_raw()), warp_key); + drop(owner); + drop(rs_warp); + drop(dev_warp); + + // While `SIGNATURES` retains the child root signature, inspect `GetDevice` and cache entry count. + let retained = super::SIGNATURES.lock().unwrap().get(&(warp_key, Vec::new())).cloned().expect("retained child RS"); + let resurrected_owner = super::root_signature_device(&retained).expect("retained ID3D12RootSignature keeps parent device queryable"); + assert_eq!(super::canonical_device_key(resurrected_owner.as_raw()), warp_key); + + let sig_count_before = super::SIGNATURES.lock().unwrap().len(); + let _ = super::signature_for(&dev_hw, &[]).expect("HW dispatch chain RS"); + let _ = super::signature_for(&dev_hw, &[]).expect("HW dispatch chain RS cached"); + let sig_count_after = super::SIGNATURES.lock().unwrap().len(); + assert!(sig_count_after <= sig_count_before + 1, "repeated calls must not grow SIGNATURES"); + println!("SIGNATURES_LIFETIME before_refs={before_refs} after_refs={after_refs} cached_entries={sig_count_after}"); + } + } + + #[test] + fn split_programs_sharing_large_piece_hit_compute_blobs_and_reuse_root_signature() { + use std::ffi::c_void; + use std::sync::{atomic::Ordering, Arc, Mutex}; + + if crate::gpu::recomp::dxc::location().is_err() { + crate::gpu::recomp::runner::skip_test("no DXC"); + return; + } + let Some(dev) = test_device() else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + + // Compile unique >= 16 KB DXIL pieces (`>= COMPUTE_BLOB_MIN_DXIL`) with a per-run salt so + // earlier runs' disk caches cannot satisfy Program A cold builds. + let nonce = (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u32) ^ std::process::id(); + let compile_piece = |rounds: u32, extra_xor: u32| { + let hlsl = format!( + "RWByteAddressBuffer dst : register(u0, space0);\n\ + [numthreads(1, 1, 1)] void main(uint3 id : SV_DispatchThreadID) {{\n\ + uint x = id.x ^ 0x{nonce:08x}u ^ 0x{extra_xor:08x}u;\n\ + [unroll] for (uint i = 0; i < {rounds}; ++i) {{\n\ + x = (x * 1664525u + (i ^ 0x9e3779b9u)) ^ (x >> 13);\n\ + }}\n\ + dst.Store(0, x);\n\ + }}\n" + ); + crate::gpu::recomp::dxc::compile(&hlsl, "main", "cs_6_0", &[]).expect("compile cs_6_0 piece") + }; + let mut rounds = 600u32; + let mut shared = compile_piece(rounds, 0); + while shared.len() < super::super::COMPUTE_BLOB_MIN_DXIL { + rounds *= 2; + shared = compile_piece(rounds, 0); + } + let tail_a = compile_piece(12, 1); + let tail_b = compile_piece(12, 2); + let whole = compile_piece(16, 3); + + static SPY_LOCK: Mutex<()> = Mutex::new(()); + static SPY_CALLS: Mutex> = Mutex::new(Vec::new()); + let _serial = SPY_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SPY_CALLS.lock().unwrap().clear(); + + struct FixtureCleanup { + psos: Vec, + blob_keys: Vec<(u64, usize, i32)>, + disk_dxils: Vec>, + } + impl Drop for FixtureCleanup { + fn drop(&mut self) { + for pso in self.psos.drain(..) { + super::forget(pso.as_raw() as usize); + } + for key in self.blob_keys.drain(..) { + super::super::forget_compute_blob(key); + } + for bytes in self.disk_dxils.drain(..) { + if let Some(p) = super::super::driver_cache::path_for(&bytes, 0, true) { + let _ = std::fs::remove_file(p); + } + } + SPY_CALLS.lock().unwrap().clear(); + } + } + let mut cleanup = FixtureCleanup { + psos: Vec::new(), + blob_keys: Vec::new(), + disk_dxils: vec![shared.clone(), tail_a.clone(), tail_b.clone()], + }; + + unsafe extern "system" fn spy_create(this: *mut c_void, desc: *const c_void, _iid: *const super::GUID, out: *mut *mut c_void) -> super::HRESULT { + let d = &*(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + SPY_CALLS.lock().unwrap().push((d.CS.BytecodeLength, !d.CachedPSO.pCachedBlob.is_null())); + let dev = ID3D12Device::from_raw_borrowed(&this).unwrap(); + match dev.CreateComputePipelineState::(d) { + Ok(pso) => { + *out = pso.into_raw(); + 0 + } + Err(e) => e.code().0, + } + } + + let base_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + let iid = &ID3D12PipelineState::IID as *const windows::core::GUID as *const super::GUID; + let plan_a = Arc::new(super::DispatchChain { pieces: vec![shared.clone(), tail_a.clone()], dwords_per_group: 4 }); + let plan_b = Arc::new(super::DispatchChain { pieces: vec![shared.clone(), tail_b.clone()], dwords_per_group: 4 }); + + unsafe { + let mut raw_a: *mut c_void = std::ptr::null_mut(); + let rs_a = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_a, 1, &whole, &[], plan_a.clone()).expect("build Program A"); + cleanup.psos.push(ID3D12PipelineState::from_raw(raw_a)); + cleanup.blob_keys.push(super::super::compute_blob_key(&shared, rs_a, 0)); + cleanup.blob_keys.push(super::super::compute_blob_key(&tail_a, rs_a, 0)); + let a_calls = std::mem::take(&mut *SPY_CALLS.lock().unwrap()); + assert_eq!(a_calls.len(), 2, "Program A should compile 2 pieces, got {a_calls:?}"); + assert!(a_calls.iter().any(|&(len, cached)| len == shared.len() && !cached), "Program A shared piece should start cold: {a_calls:?}"); + + let sigs_after_a = super::SIGNATURES.lock().unwrap().len(); + let key_shared = super::super::compute_blob_key(&shared, rs_a, 0); + let count_shared_keys = || { + super::super::COMPUTE_BLOBS.lock().unwrap().as_ref().map_or(0, |(m, _)| m.keys().filter(|k| k.0 == key_shared.0).count()) + }; + let stored_blob = count_shared_keys(); + assert!(stored_blob <= 1, "shared piece driver blob stored at most once in COMPUTE_BLOBS (0 on AMD stub-blob drivers)"); + + let plib_hits_before_b = super::PLIB_HITS.load(Ordering::Relaxed); + let mut raw_b: *mut c_void = std::ptr::null_mut(); + let rs_b = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_b, 2, &whole, &[], plan_b).expect("build Program B"); + cleanup.psos.push(ID3D12PipelineState::from_raw(raw_b)); + cleanup.blob_keys.push(super::super::compute_blob_key(&tail_b, rs_b, 0)); + let b_calls = std::mem::take(&mut *SPY_CALLS.lock().unwrap()); + assert_eq!(rs_b, rs_a, "Program B must reuse Program A's cached dispatch-chain root signature"); + assert_eq!(super::SIGNATURES.lock().unwrap().len(), sigs_after_a, "Program B must not allocate a new SIGNATURES entry"); + if stored_blob == 1 { + assert!( + super::PLIB_HITS.load(Ordering::Relaxed) > plib_hits_before_b + || b_calls.iter().any(|&(len, cached)| len == shared.len() && cached), + "Program B must reuse shared piece from .plib or COMPUTE_BLOBS via CachedPSO: {b_calls:?}" + ); + } + assert_eq!(count_shared_keys(), stored_blob, "Program B must not insert a duplicate COMPUTE_BLOBS entry under another root signature"); + + // Dropping and rebuilding Program A must also hit .plib or COMPUTE_BLOBS with no extra root signature. + let pso_a = cleanup.psos.remove(0); + super::forget(pso_a.as_raw() as usize); + drop(pso_a); + let plib_hits_before_a2 = super::PLIB_HITS.load(Ordering::Relaxed); + let mut raw_a2: *mut c_void = std::ptr::null_mut(); + let rs_a2 = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_a2, 3, &whole, &[], plan_a).expect("rebuild Program A"); + cleanup.psos.push(ID3D12PipelineState::from_raw(raw_a2)); + let a2_calls = std::mem::take(&mut *SPY_CALLS.lock().unwrap()); + assert_eq!(rs_a2, rs_a); + assert_eq!(super::SIGNATURES.lock().unwrap().len(), sigs_after_a); + if stored_blob == 1 { + assert!( + super::PLIB_HITS.load(Ordering::Relaxed) > plib_hits_before_a2 + || a2_calls.iter().any(|&(len, cached)| len == shared.len() && cached), + "rebuild must hit .plib or COMPUTE_BLOBS: {a2_calls:?}" + ); + } + assert_eq!(count_shared_keys(), stored_blob); + println!("DISPATCH_CHAIN_RS_CACHE shared_dxil={} sigs={}", shared.len(), sigs_after_a); + } + } + + #[test] + fn a_failed_whole_form_is_not_built_again() { + use std::ffi::c_void; + use std::sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + Arc, Mutex, OnceLock, + }; + static CALLS: AtomicU64 = AtomicU64::new(0); + unsafe extern "system" fn refused(_: *mut c_void, _: *const c_void, _: *const super::GUID, _: *mut *mut c_void) -> super::HRESULT { + CALLS.fetch_add(1, Ordering::Relaxed); + crate::util::E_FAIL + } + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let signature = super::pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + let builder = Arc::new(super::PipelineBuilder { + device: dev, + create: refused, + signature, + samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, + node: 0, + record: 0, + }); + let chain = super::Chain { + builder, + tail: Vec::new(), + words: 4, + whole_code: vec![0; 16], + whole: OnceLock::new(), + whole_started: AtomicBool::new(false), + retry_at: Mutex::new(None), + signature: OnceLock::new(), + slabs: Default::default(), + warned: AtomicBool::new(false), + }; + assert!(chain.whole().is_err()); + assert!(chain.whole().is_err()); + assert_eq!(CALLS.load(Ordering::Relaxed), 1); + } + } + + #[test] + fn a_whole_form_that_ran_out_of_memory_is_tried_once_more_after_a_pause() { + use std::ffi::c_void; + use std::sync::{ + atomic::{AtomicBool, AtomicU64, Ordering}, + Arc, Mutex, OnceLock, + }; + static CALLS: AtomicU64 = AtomicU64::new(0); + unsafe extern "system" fn out_of_memory(_: *mut c_void, _: *const c_void, _: *const super::GUID, _: *mut *mut c_void) -> super::HRESULT { + CALLS.fetch_add(1, Ordering::Relaxed); + crate::util::E_OUTOFMEMORY + } + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + let signature = super::pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + let builder = Arc::new(super::PipelineBuilder { + device: dev, + create: out_of_memory, + signature, + samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, + node: 0, + record: 0, + }); + let chain = super::Chain { + builder, + tail: Vec::new(), + words: 4, + whole_code: vec![0; 16], + whole: OnceLock::new(), + whole_started: AtomicBool::new(false), + retry_at: Mutex::new(None), + signature: OnceLock::new(), + slabs: Default::default(), + warned: AtomicBool::new(false), + }; + assert!(chain.whole().is_err()); + assert!(chain.whole().is_err()); + assert_eq!(CALLS.load(Ordering::Relaxed), 1); + *chain.retry_at.lock().unwrap() = Some(std::time::Instant::now()); + assert!(chain.whole().is_err()); + assert_eq!(CALLS.load(Ordering::Relaxed), 2); + *chain.retry_at.lock().unwrap() = Some(std::time::Instant::now()); + assert!(chain.whole().is_err()); + assert_eq!(CALLS.load(Ordering::Relaxed), 2); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 374c6ab5a7..6875bed66f 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -253,8 +253,8 @@ struct State { /// unpinned unused pool tiles queued from `forget_in` (cannot signal queues under D3D12 release locks) /// until `flush_pending_quarantine` places them behind GPU fences pending_quarantine: Vec<(u32, u32)>, - /// per-title-queue fences used to mark in-flight GPU work (`note_queue`) - queue_fences: FxHashMap, + /// per-title-queue fences used to mark in-flight GPU work (non-owning raw queue key → fence + value) + queue_fences: FxHashMap, /// placed buffers → the pool tiles they use buffers: FxHashMap>, /// reused tiles / decommitted partial pages to clear: (address, bytes) @@ -1362,7 +1362,6 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; s.drain_lazy_commits(); - s.note_queue(queue); let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); if filtered.is_empty() { return; @@ -1454,18 +1453,78 @@ fn return_readback_job(job: ReadbackJob) { } } +/// Apply GPU readback bytes for `[dst, dst + len)` into host memory, comparing each 64-byte +/// chunk's current host bytes against its Phase-1 `snap_hashes` entry so any chunk modified by +/// the CPU during the GPU wait is NOT clobbered (and its `sent` hash remains stale so the next +/// `before_execute` uploads the CPU's write). Updates `snap_hashes` for copied chunks so a +/// multi-batch readback splitting a 64-byte chunk across `job.cap` preserves continuity. +unsafe fn apply_readback_preserving_cpu_writes( + dst: usize, + src: *const u8, + len: usize, + snap_base: usize, + snap_hashes: &mut [u64], + mapped: &mut FxHashMap, +) { + let mut at = dst; + let mut src_off = 0usize; + let end = dst + len; + while at < end { + let pg = at & !(PAGE - 1); + let t = pg & !(TILE - 1); + let page_idx = (pg - t) / PAGE; + let page_end = (pg + PAGE).min(end); + if let Some(entry) = mapped.get_mut(&t).filter(|e| e.holes & (1u16 << page_idx) == 0) { + while at < page_end { + let chunk_va = at & !(CHUNK - 1); + let chunk_end = (chunk_va + CHUNK).min(page_end); + let step = chunk_end - at; + let snap_i = (chunk_va - snap_base) / CHUNK; + if let Some(expected) = snap_hashes.get_mut(snap_i) { + let cur_slice = std::slice::from_raw_parts(chunk_va as *const u8, CHUNK); + if chunk_hash(cur_slice) == *expected { + std::ptr::copy_nonoverlapping(src.add(src_off), at as *mut u8, step); + let new_h = chunk_hash(std::slice::from_raw_parts(chunk_va as *const u8, CHUNK)); + *expected = new_h; + let k = (chunk_va - pg) / CHUNK; + if let Some(sent) = entry.sent[page_idx].as_deref_mut() { + sent[k] = new_h; + } else if new_h != ZERO_HASH { + let sent = entry.sent[page_idx].insert(Box::new(ZERO_HASHES)); + sent[k] = new_h; + } + } + } + at += step; + src_off += step; + } + } else { + let step = page_end - at; + at += step; + src_off += step; + } + } +} + /// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with /// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending -/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then -/// copies the range back from VRAM into CPU memory using a per-call pooled `ReadbackJob` whose -/// GPU fence wait runs OUTSIDE the global `STATE` lock. +/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, orders +/// `s.queue` behind active title queues via `rb_fence` before copying, and copies the range +/// back from VRAM into CPU memory using a per-call pooled `ReadbackJob` whose GPU fence wait +/// runs OUTSIDE the global `STATE` lock without clobbering concurrent CPU writes. pub unsafe fn readback_now(va: usize, len: usize) { if len == 0 { return; } - // 1. Flush pending clears & dirty CPU chunks under `STATE`, collect mapped spans, then release - // `STATE` before recording/waiting so other `Map` threads and `before_execute` never stall. - let (dev, spans): (ID3D12Device, Vec<(usize, ID3D12Resource, u64, usize)>) = { + let end = va.saturating_add(len); + let snap_base = va & !(CHUNK - 1); + let snap_end = end.saturating_add(CHUNK - 1) & !(CHUNK - 1); + let snap_count = (snap_end - snap_base) / CHUNK; + + // 1. Flush pending clears & dirty CPU chunks under `STATE`, snapshot Phase-1 64-byte chunk + // hashes, collect mapped spans, then release `STATE` before recording/waiting so other + // `Map` threads and `before_execute` never stall. + let (dev, spans, mut snap_hashes): (ID3D12Device, Vec<(usize, ID3D12Resource, u64, usize)>, Vec) = { let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; if s.window_index(va).is_none() { @@ -1479,10 +1538,11 @@ pub unsafe fn readback_now(va: usize, len: usize) { } s.upload_zeros(&zeroed); } - // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` + // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` and snapshot + // each 64-byte chunk's Phase-1 hash so Phase 3 never clobbers concurrent CPU writes. let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); + let mut snap_hashes = vec![ZERO_HASH; snap_count]; let mut pg = va & !(PAGE - 1); - let end = va + len; while pg < end { let t = pg & !(TILE - 1); let tile_end = (t + TILE).min(end); @@ -1493,6 +1553,16 @@ pub unsafe fn readback_now(va: usize, len: usize) { if entry.holes & (1u16 << idx) == 0 { let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); + if let Some(sent) = entry.sent[idx].as_deref() { + let lo = va.saturating_sub(p) / CHUNK; + let hi = (end.min(p + PAGE) - p).div_ceil(CHUNK).min(CHUNKS); + for k in lo..hi { + let snap_i = (p + k * CHUNK - snap_base) / CHUNK; + if let Some(dst_h) = snap_hashes.get_mut(snap_i) { + *dst_h = sent[k]; + } + } + } } p += PAGE; } @@ -1522,13 +1592,14 @@ pub unsafe fn readback_now(va: usize, len: usize) { if spans.is_empty() { return; } - (s.dev.clone(), spans) + (s.dev.clone(), spans, snap_hashes) }; let total_need: usize = spans.iter().map(|s| s.3).sum(); let Some(job) = take_readback_job(&dev, total_need) else { let mut g = lock_state(); if let Some(s) = g.as_mut() { + s.wait_title_queues_for_readback(); s.readback_ranges(&[(va, len)]); } return; @@ -1538,6 +1609,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { let mut sub_off = 0usize; let mut pending: Vec<(usize, usize, usize)> = Vec::new(); let mut job_idle = true; + let mut waited_title_queues = false; while idx < spans.len() { let mut used = 0usize; pending.clear(); @@ -1561,11 +1633,16 @@ pub unsafe fn readback_now(va: usize, len: usize) { break; } let Ok(cmd_list) = job.list.cast::() else { break }; - // 2. Submit & signal atomically under `STATE` (strictly ordered after our uploads on `s.queue`), - // then release `STATE` BEFORE waiting on the GPU fence. + // 2. Order `s.queue` behind active title queues via `rb_fence`, then submit & signal + // atomically under `STATE` (ordered after our uploads on `s.queue`) and release + // `STATE` BEFORE waiting on the GPU fence. let wait_target = { let mut g = lock_state(); let Some(s) = g.as_mut() else { break }; + if !waited_title_queues { + s.wait_title_queues_for_readback(); + waited_title_queues = true; + } super::title_textures::own_work(|| { s.queue.ExecuteCommandLists(&[Some(cmd_list)]); }); @@ -1585,26 +1662,13 @@ pub unsafe fn readback_now(va: usize, len: usize) { break; } } - // 3. Copy only still-committed non-hole bytes into host memory and sync `sent` hashes. + // 3. Copy only still-committed non-hole 64-byte chunks that were NOT modified by the CPU + // during the GPU wait, and sync `sent` hashes only for copied chunks. let mut g = lock_state(); let Some(s) = g.as_mut() else { break }; let p = job.mapped as *const u8; for &(dst, off, chunk) in &pending { - let mut at = dst; - let mut src_off = off; - let end = dst + chunk; - while at < end { - let pg = at & !(PAGE - 1); - let t = pg & !(TILE - 1); - let page_idx = (pg - t) / PAGE; - let step = (pg + PAGE).min(end) - at; - if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << page_idx) == 0) { - std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); - } - at += step; - src_off += step; - } - s.sync_sent_range(dst, chunk); + apply_readback_preserving_cpu_writes(dst, p.add(off), chunk, snap_base, &mut snap_hashes, &mut s.mapped); } s.reclaim_ring(); } @@ -1734,6 +1798,19 @@ impl State { /// Move any `pending_quarantine` tiles (unpinned when a placed buffer was released) into the /// GPU fence quarantine behind `self.fence` and every known title queue. unsafe fn flush_pending_quarantine(&mut self) -> bool { + self.flush_pending_quarantine_with(None) + } + + unsafe fn flush_pending_quarantine_with(&mut self, extra: Option<&ID3D12CommandQueue>) -> bool { + if self.pending_quarantine.is_empty() { + return false; + } + let raw_ptrs = collect_known_queue_ptrs(extra); + let borrowed: Vec<&ID3D12CommandQueue> = raw_ptrs.iter().filter_map(|p| ID3D12CommandQueue::from_raw_borrowed(p)).collect(); + self.flush_pending_quarantine_for(&borrowed) + } + + unsafe fn flush_pending_quarantine_for(&mut self, queues: &[&ID3D12CommandQueue]) -> bool { if self.pending_quarantine.is_empty() { return false; } @@ -1751,52 +1828,70 @@ impl State { if tiles.is_empty() { return false; } - self.quarantine_tiles(tiles); + self.quarantine_tiles_for(tiles, queues); true } - unsafe fn note_queue(&mut self, q: &ID3D12CommandQueue) -> bool { - let key = q.as_raw() as usize; - if self.queue_fences.contains_key(&key) { - return true; - } - // Ignore queues belonging to a different device (e.g. isolated unit tests). - let mut qdev: Option = None; - if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { - return true; - } - match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { - Ok(fence) => { - self.queue_fences.insert(key, (q.clone(), fence, 0)); - true - } - Err(_) => false, - } - } - - unsafe fn sync_known_queues(&mut self) -> bool { - let mut ok = true; + /// Order `self.queue` behind every active same-device title queue via `self.rb_fence` + /// so a subsequent sparse readback sees all submitted GPU writes. + unsafe fn wait_title_queues_for_readback(&mut self) { + let self_q = self.queue.as_raw() as usize; + let self_dev = self.dev.as_raw(); + let mut seen: Vec = Vec::new(); for raw in super::present::known_queues() { - if !self.queue_fences.contains_key(&raw) { - let ptr = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&ptr) { - ok &= self.note_queue(q); - } + if raw == 0 || raw == self_q || seen.contains(&raw) { + continue; + } + let ptr = raw as *mut c_void; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&ptr) else { + continue; + }; + let mut qdev: Option = None; + if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self_dev) { + continue; + } + seen.push(raw); + self.rb_value += 1; + let v = self.rb_value; + if q.Signal(&self.rb_fence, v).is_ok() { + let _ = self.queue.Wait(&self.rb_fence, v); + super::list_x::note_internal_wait(self_q, "sparse readback behind a title queue", &self.rb_fence, v); } } - ok } - unsafe fn signal_title_queues(&mut self) -> Option> { - if !self.sync_known_queues() { - return None; - } - let mut marks = Vec::with_capacity(self.queue_fences.len()); - for (q, fence, val) in self.queue_fences.values_mut() { - let next = *val + 1; - if q.Signal(&*fence, next).is_ok() { - *val = next; - marks.push((fence.clone(), next)); + unsafe fn signal_title_queues_for(&mut self, queues: &[&ID3D12CommandQueue]) -> Option> { + // Pass 1 (before signaling): deduplicate live same-device title queues and prune stale + // queue fences unconditionally so an early error cannot prune another live queue. + let self_q = self.queue.as_raw() as usize; + let mut active: Vec<(usize, &ID3D12CommandQueue)> = Vec::with_capacity(queues.len()); + let mut live_keys: Vec = Vec::with_capacity(queues.len()); + for &q in queues { + let key = q.as_raw() as usize; + if key == 0 || key == self_q || live_keys.contains(&key) { + continue; + } + let mut qdev: Option = None; + if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { + continue; + } + live_keys.push(key); + active.push((key, q)); + } + self.queue_fences.retain(|k, _| live_keys.contains(k)); + let mut marks = Vec::with_capacity(active.len()); + for (key, q) in active { + let entry = match self.queue_fences.entry(key) { + std::collections::hash_map::Entry::Occupied(e) => e.into_mut(), + std::collections::hash_map::Entry::Vacant(e) => match self.dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) { + Ok(fence) => e.insert((fence, 0)), + Err(_) => return None, + }, + }; + let next = entry.1 + 1; + if q.Signal(&entry.0, next).is_ok() { + entry.1 = next; + marks.push((entry.0.clone(), next)); } else { return None; } @@ -1804,11 +1899,11 @@ impl State { Some(marks) } - unsafe fn quarantine_tiles(&mut self, tiles: Vec<(u32, u32)>) { + unsafe fn quarantine_tiles_for(&mut self, tiles: Vec<(u32, u32)>, queues: &[&ID3D12CommandQueue]) { if tiles.is_empty() { return; } - let marks = self.signal_title_queues().map(|mut title_marks| { + let marks = self.signal_title_queues_for(queues).map(|mut title_marks| { title_marks.push((self.fence.clone(), self.value)); title_marks }); @@ -1899,12 +1994,26 @@ impl State { /// inserting a cross-queue GPU `Wait` on `self.queue`). When no title queues are busy, unmaps /// immediately on `self.queue` and quarantines unpinned pool tiles behind `self.fence`. unsafe fn flush_parked(&mut self) -> bool { + self.flush_parked_with(None) + } + + unsafe fn flush_parked_with(&mut self, extra: Option<&ID3D12CommandQueue>) -> bool { + self.drain_pending_unmaps(); + if self.parked.is_empty() { + return false; + } + let raw_ptrs = collect_known_queue_ptrs(extra); + let borrowed: Vec<&ID3D12CommandQueue> = raw_ptrs.iter().filter_map(|p| ID3D12CommandQueue::from_raw_borrowed(p)).collect(); + self.flush_parked_for(&borrowed) + } + + unsafe fn flush_parked_for(&mut self, queues: &[&ID3D12CommandQueue]) -> bool { self.drain_pending_unmaps(); if self.parked.is_empty() { return false; } let entries: Vec<(usize, (u32, u32))> = std::mem::take(&mut self.parked).into_iter().collect(); - let title_marks = self.signal_title_queues(); + let title_marks = self.signal_title_queues_for(queues); if title_marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { self.unmap_entries_and_quarantine(entries); } else { @@ -1919,6 +2028,18 @@ impl State { } } +fn collect_known_queue_ptrs(extra: Option<&ID3D12CommandQueue>) -> Vec<*mut c_void> { + let mut raw_ptrs: Vec<*mut c_void> = + super::present::known_queues().into_iter().filter(|&raw| raw != 0).map(|raw| raw as *mut c_void).collect(); + if let Some(q) = extra { + let p = q.as_raw(); + if !p.is_null() && !raw_ptrs.contains(&p) { + raw_ptrs.push(p); + } + } + raw_ptrs +} + /// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write /// has to reach the GPU. pub fn mapped_ranges() -> Vec<(usize, usize)> { @@ -1960,10 +2081,9 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; s.drain_lazy_commits(); - s.note_queue(queue); // the title's work sees what was decommitted unmapped, as it was - let flushed = s.flush_parked(); - let quarantined = s.flush_pending_quarantine(); + let flushed = s.flush_parked_with(Some(queue)); + let quarantined = s.flush_pending_quarantine_with(Some(queue)); let drained = s.drain_quarantined(); if flushed || quarantined || drained { s.retire_free_pools(); @@ -2674,7 +2794,9 @@ mod tests { let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); let mut dev: Option = None; - if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + if std::env::var("XCL_WARP").ok().as_deref() == Some("1") + || D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() + { let warp: IDXGIAdapter = factory.EnumWarpAdapter().expect("WARP"); D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); } @@ -2780,7 +2902,6 @@ mod tests { unsafe { let (base, mut s) = test_state_with_reserved(2); let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); - assert!(s.note_queue(&title_q)); s.commit_range(base, TILE); let tile = s.mapped[&base].pool; @@ -2792,7 +2913,7 @@ mod tests { s.decommit_range(base, TILE); s.free.clear(); - assert!(s.flush_parked()); + assert!(s.flush_parked_for(&[&title_q])); // Even after `s.queue` finishes `unmap_tiles`, `title_q` is still gated behind `title_gate`. s.wait_for(s.value); @@ -2815,6 +2936,108 @@ mod tests { } } + unsafe fn com_refcount(q: &ID3D12CommandQueue) -> u32 { + let raw = q.as_raw() as *mut *const *const c_void; + let vt = *raw; + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vt.add(1)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*vt.add(2)); + let _ = add_ref(raw as *mut c_void); + release(raw as *mut c_void) + } + + #[test] + fn flush_parked_does_not_retain_title_queue_com_refs() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + unsafe { + let (base, mut s) = test_state_with_reserved(1); + let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let before = com_refcount(&title_q); + s.commit_range(base, TILE); + s.wait_for(s.value); + s.decommit_range(base, TILE); + assert!(s.flush_parked_for(&[&title_q])); + assert_eq!(com_refcount(&title_q), before, "flush_parked must not retain a strong COM ref on title queues"); + assert_eq!(s.queue_fences.len(), 1); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn flush_parked_prunes_stale_queue_fences_while_inflight_batches_stay_gated() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + unsafe { + let (base, mut s) = test_state_with_reserved(2); + let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); + let title_gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence"); + let _unblock = SignalOnDrop(title_gate.clone(), 1); + title_q.Wait(&title_gate, 1).expect("gate title queue"); + + s.commit_range(base, TILE); + let tile_a = s.mapped[&base].pool; + s.commit_range(base + TILE, TILE); + let tile_b = s.mapped[&(base + TILE)].pool; + s.wait_for(s.value); + + s.decommit_range(base, TILE); + s.free.clear(); + assert!(s.flush_parked_for(&[&title_q])); + assert_eq!(s.queue_fences.len(), 1); + + // Simulate title_q release before the next flush: stale fence entry is pruned, + // while batch A keeps its own fence clone in `marks` and stays gated. + s.decommit_range(base + TILE, TILE); + assert!(s.flush_parked_for(&[])); + assert!(s.queue_fences.is_empty(), "stale queue fence must be pruned"); + s.wait_for(s.value); + s.drain_quarantined(); + assert!(!s.free.contains(&tile_a) && !s.pending_unmaps.is_empty(), "in-flight batch A must stay gated"); + + title_gate.Signal(1).expect("release title queue"); + let start = std::time::Instant::now(); + while (!s.free.contains(&tile_a) || !s.free.contains(&tile_b)) && start.elapsed() < std::time::Duration::from_secs(5) { + s.drain_quarantined(); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + assert!(s.free.contains(&tile_a) && s.free.contains(&tile_b), "both batches must drain after title_q completes"); + drop(_unblock); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn repeated_queue_quarantine_and_release_does_not_leak_queues_or_fences() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + unsafe { + let (base, mut s) = test_state_with_reserved(2); + for i in 0..80usize { + let q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap_or_else(|e| panic!("queue {i}: {e}")); + let before = com_refcount(&q); + s.commit_range(base, TILE); + s.decommit_range(base, TILE); + assert!(s.flush_parked_for(&[&q])); + assert_eq!(com_refcount(&q), before, "queue {i} refcount leaked"); + drop(q); + s.commit_range(base + TILE, TILE); + s.decommit_range(base + TILE, TILE); + assert!(s.flush_parked_for(&[])); + assert!(s.queue_fences.is_empty(), "stale fence leaked at iteration {i}"); + s.wait_for(s.value); + let start = std::time::Instant::now(); + while (!s.quarantined.is_empty() || !s.pending_unmaps.is_empty()) && start.elapsed() < std::time::Duration::from_secs(5) { + s.drain_quarantined(); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert!(s.quarantined.is_empty() && s.pending_unmaps.is_empty(), "quarantine failed to drain at iteration {i}"); + } + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// Sub-tile decommits (two 32 KiB halves, sixteen 4 KiB pages, or decommitting the last /// remaining committed page) must unmap the tile and return unpinned pool tiles to `free` /// once `holes` reaches `0xFFFF`, pruning stale `to_zero` entries for unmapped tiles. @@ -3006,7 +3229,6 @@ mod tests { let title_queue: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); let gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence"); let _release_gate = SignalOnDrop(gate.clone(), 1); - assert!(s.note_queue(&title_queue)); s.commit_range(base, TILE); let tile = s.mapped[&base].pool; @@ -3017,7 +3239,7 @@ mod tests { // Decommit and flush while still pinned by BUF: tile is unmapped from window once // idle title_queue passes its fence, NOT freed. s.decommit_range(base, TILE); - assert!(s.flush_parked()); + assert!(s.flush_parked_for(&[&title_queue])); let start = std::time::Instant::now(); while !s.pending_unmaps.is_empty() && start.elapsed() < std::time::Duration::from_secs(5) { s.drain_pending_unmaps(); @@ -3037,7 +3259,7 @@ mod tests { assert_eq!(s.pending_quarantine, vec![tile]); // Flushing pending_quarantine attaches title_queue fence; tile stays quarantined until gate signals. - assert!(s.flush_pending_quarantine()); + assert!(s.flush_pending_quarantine_for(&[&title_queue])); assert!(s.pending_quarantine.is_empty()); assert!(!s.drain_quarantined(), "tile must remain quarantined while title queue is blocked"); assert!(!s.free.contains(&tile)); @@ -3064,7 +3286,6 @@ mod tests { unsafe { let (base, mut s) = test_state_with_reserved(2); let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); - assert!(s.note_queue(&title_q)); s.commit_range(base, TILE); let tile = s.mapped[&base].pool; @@ -3077,7 +3298,7 @@ mod tests { // Decommit + flush while title_q is busy: NULL unmap must be deferred, NOT queued on s.queue yet. s.decommit_range(base, TILE); - assert!(s.flush_parked()); + assert!(s.flush_parked_for(&[&title_q])); assert_eq!(s.value, v_before, "UpdateTileMappings(NULL) must not be issued while title queue is in flight"); assert_eq!(s.pending_unmaps.len(), 1); assert!(s.pending_unmap_va.contains_key(&base)); @@ -3096,7 +3317,7 @@ mod tests { let _unblock2 = SignalOnDrop(gate2.clone(), 1); title_q.Wait(&gate2, 1).expect("gate title_q 2"); s.decommit_range(base, TILE); - assert!(s.flush_parked()); + assert!(s.flush_parked_for(&[&title_q])); assert_eq!(s.pending_unmaps.len(), 2); gate1.Signal(1).expect("signal gate1"); @@ -3169,4 +3390,61 @@ mod tests { assert_ne!(VirtualFree(p as *mut c_void, 0, MEM_RELEASE), 0); } } + + #[test] + fn readback_now_preserves_concurrent_cpu_writes_and_unaligned_batches() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE}; + unsafe { + // Allocate a real 64 KiB aligned tile with page 0 committed and page 1 left as a hole. + let tile = VirtualAlloc(std::ptr::null(), TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert!(tile != 0 && tile % TILE == 0); + assert!(!VirtualAlloc(tile as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + + let host = std::slice::from_raw_parts_mut(tile as *mut u8, PAGE); + host[0..64].fill(0x11); // chunk 0: untouched during GPU wait -> should take GPU readback + host[64..128].fill(0x22); // chunk 1: modified by CPU during GPU wait -> must NOT be clobbered + host[128..192].fill(0x33); // chunk 2: split across two unaligned batches -> both halves should apply + + let mut mapped: FxHashMap = FxHashMap::default(); + mapped.insert(tile, TileEntry::with_holes((0, 0), 0xFFFF & !1u16)); + let mut dirty = Vec::new(); + scan_page(host, tile, &mut mapped.get_mut(&tile).unwrap().sent[0], &mut dirty); + assert_eq!(dirty, vec![(tile, 192)]); + + // Phase-1 snapshot hashes for chunks 0..3. + let mut snap_hashes = vec![ + chunk_hash(&host[0..64]), + chunk_hash(&host[64..128]), + chunk_hash(&host[128..192]), + ]; + + // Simulate concurrent CPU write to chunk 1 during the GPU wait. + host[64 + 7] = 0xEE; + + // GPU readback buffer containing new GPU values for chunks 0..3. + let mut gpu_rb = vec![0u8; 192]; + gpu_rb[0..64].fill(0xA1); + gpu_rb[64..128].fill(0xB2); + gpu_rb[128..160].fill(0xC3); + gpu_rb[160..192].fill(0xD4); + + // Batch 1 covers [0..160) (splitting chunk 2 in half); Batch 2 covers [160..192). + apply_readback_preserving_cpu_writes(tile, gpu_rb.as_ptr(), 160, tile, &mut snap_hashes, &mut mapped); + apply_readback_preserving_cpu_writes(tile + 160, gpu_rb.as_ptr().add(160), 32, tile, &mut snap_hashes, &mut mapped); + + // Chunk 0 received GPU readback; chunk 1 preserved CPU write; chunk 2 received both batch halves. + assert!(host[0..64].iter().all(|&b| b == 0xA1)); + assert_eq!(host[64 + 7], 0xEE, "concurrent CPU write in chunk 1 must not be clobbered"); + assert_eq!(host[64], 0x22, "rest of modified chunk 1 must stay intact"); + assert!(host[128..160].iter().all(|&b| b == 0xC3)); + assert!(host[160..192].iter().all(|&b| b == 0xD4)); + + // Next `scan_page` must detect ONLY chunk 1 as dirty (chunks 0 and 2 had their `sent` hashes synced). + dirty.clear(); + scan_page(host, tile, &mut mapped.get_mut(&tile).unwrap().sent[0], &mut dirty); + assert_eq!(dirty, vec![(tile + 64, 64)]); + + assert_ne!(VirtualFree(tile as *mut c_void, 0, MEM_RELEASE), 0); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index f0488df7af..24d8e2cc27 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2769,13 +2769,57 @@ fn console_has_packed_3d_mips(desc: &D3D12_RESOURCE_DESC) -> bool { .unwrap_or(false) } +fn volume_texel_bytes(f: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> u64 { + use windows::Win32::Graphics::Dxgi::Common::*; + match f { + DXGI_FORMAT_R32G32B32A32_FLOAT + | DXGI_FORMAT_R32G32B32A32_UINT + | DXGI_FORMAT_R32G32B32A32_SINT + | DXGI_FORMAT_R32G32B32A32_TYPELESS => 16, + DXGI_FORMAT_R16G16B16A16_FLOAT + | DXGI_FORMAT_R16G16B16A16_UNORM + | DXGI_FORMAT_R16G16B16A16_UINT + | DXGI_FORMAT_R16G16B16A16_SNORM + | DXGI_FORMAT_R16G16B16A16_SINT + | DXGI_FORMAT_R16G16B16A16_TYPELESS + | DXGI_FORMAT_R32G32_FLOAT + | DXGI_FORMAT_R32G32_UINT + | DXGI_FORMAT_R32G32_SINT + | DXGI_FORMAT_R32G32_TYPELESS + | DXGI_FORMAT_D32_FLOAT_S8X24_UINT + | DXGI_FORMAT_R32G8X24_TYPELESS => 8, + DXGI_FORMAT_R8G8_UNORM + | DXGI_FORMAT_R8G8_UINT + | DXGI_FORMAT_R8G8_SNORM + | DXGI_FORMAT_R8G8_SINT + | DXGI_FORMAT_R8G8_TYPELESS + | DXGI_FORMAT_R16_FLOAT + | DXGI_FORMAT_R16_UNORM + | DXGI_FORMAT_R16_UINT + | DXGI_FORMAT_R16_SNORM + | DXGI_FORMAT_R16_SINT + | DXGI_FORMAT_R16_TYPELESS + | DXGI_FORMAT_D16_UNORM + | DXGI_FORMAT_B5G6R5_UNORM + | DXGI_FORMAT_B5G5R5A1_UNORM + | DXGI_FORMAT_B4G4R4A4_UNORM => 2, + DXGI_FORMAT_R8_UNORM + | DXGI_FORMAT_R8_UINT + | DXGI_FORMAT_R8_SNORM + | DXGI_FORMAT_R8_SINT + | DXGI_FORMAT_A8_UNORM + | DXGI_FORMAT_R8_TYPELESS => 1, + _ => 4, + } +} + /// The least a 3D texture of `desc` takes on the console – the texels of its first level, one /// after the other – for a 3D texture whose size there is not known: the pages it has to itself /// at its address. None: not a 3D texture. The PC's tiles past those pages are its own /// (`owned_pages`), not the pages of what the title placed behind it. fn least_volume_bytes(desc: &D3D12_RESOURCE_DESC) -> Option { (desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D) - .then(|| desc.Width * desc.Height as u64 * desc.DepthOrArraySize as u64 * super::targets::texel_bytes(desc.Format) as u64) + .then(|| desc.Width * desc.Height as u64 * desc.DepthOrArraySize as u64 * volume_texel_bytes(desc.Format)) .filter(|&b| b != 0) } diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 38e4e700a8..8353160490 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1246,7 +1246,16 @@ fn page_home(page: usize) -> Option { /// Whether every page of `pages` (at least one) is a physical page allocated now. pub fn physical_pages_live(pages: &[usize]) -> bool { - !pages.is_empty() && pages.iter().all(|&p| if alias::enabled() { alias::page_live(p) } else { page_home(p).is_some() }) + if pages.is_empty() { + return false; + } + if alias::enabled() { + return pages.iter().all(|&p| alias::page_live(p)); + } + // Lock `AWAY` before `PHYS_BLOCKS` (`page_home`) to match `read_physical_pages` / + // `write_physical_pages` and avoid ABBA lock inversions. + let away = AWAY.lock().unwrap(); + pages.iter().all(|&p| !away.as_ref().is_some_and(|a| a.freed.contains(&p)) && page_home(p).is_some()) } /// Whether a home is only reserved until it is used (a sparse window's, or plain memory's – @@ -1268,6 +1277,9 @@ unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: u } let mut addrs = Vec::with_capacity(need); for &p in &pages[..need] { + if away.is_some_and(|a| a.freed.contains(&p)) { + return None; + } let home = page_home(p)?; let addr = match away.and_then(|a| a.page.get(&p).copied()) { Some(at) => at, @@ -4180,4 +4192,30 @@ mod tests { assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()), 1); } } + + #[test] + fn physical_pages_live_and_rw_reject_partially_freed_pages() { + unsafe { + let _ = crate::gpu::uma::get().expect("UMA must initialize"); + let (mut n, mut pages) = (2usize, [0usize; 2]); + assert_eq!(AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let [p0, p1] = pages; + assert!(physical_pages_live(&[p0, p1])); + + // Free only p0 while p1 keeps the backing PHYS_BLOCKS entry alive. + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, [p0].as_mut_ptr()), 1); + assert!(!physical_pages_live(&[p0]), "individually freed page must not be reported live"); + assert!(!physical_pages_live(&[p0, p1]), "slice containing a freed page must not be reported live"); + assert!(physical_pages_live(&[p1]), "sibling page in the same block must remain live"); + + let mut buf = [0u8; 16]; + assert!(!read_physical_pages(&[p0], 0, &mut buf), "read_physical_pages must reject a freed page"); + assert!(!write_physical_pages(&[p0], 0, &[0xAB; 16]), "write_physical_pages must reject a freed page"); + assert!(write_physical_pages(&[p1], 0, &[0xCD; 16]), "sibling page stays writable"); + assert!(read_physical_pages(&[p1], 0, &mut buf) && buf == [0xCD; 16], "sibling page stays readable"); + + assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 1, [p1].as_mut_ptr()), 1); + assert!(!physical_pages_live(&[p1]), "fully freed block must not be live"); + } + } } From cdeaf152a8a62a016fcb4eb36c7ab75004d8de85 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:05:53 +0100 Subject: [PATCH 190/258] D3D12.X: fix 30GB PSO commit/preload storm, add AMD gpu_awake heartbeat, hybrid P-core pinning, ambient directional AO/air cap, and u4 guard --- crates/xcl/src/hle/d3d12x/ambient.rs | 394 ++++++++++++++++++++--- crates/xcl/src/hle/d3d12x/bind.rs | 58 +++- crates/xcl/src/hle/d3d12x/gpu_awake.rs | 412 +++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 2 + crates/xcl/src/hle/d3d12x/pcores.rs | 270 ++++++++++++++++ crates/xcl/src/hle/d3d12x/pso_async.rs | 193 +++++++++--- crates/xcl/src/hle/d3d12x/real.rs | 7 +- 7 files changed, 1243 insertions(+), 93 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/gpu_awake.rs create mode 100644 crates/xcl/src/hle/d3d12x/pcores.rs diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 4c4949aa44..8e3f4718a8 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -11,13 +11,14 @@ //! * `0` / `off` / `none`: disabled. //! //! Tunables: `XCL_AMBIENT_GAIN`, `XCL_AMBIENT_POWER`, `XCL_AMBIENT_LEAST`, `XCL_AMBIENT_AO`, -//! `XCL_AMBIENT_REFLECT`. +//! `XCL_AMBIENT_REFLECT`, `XCL_AMBIENT_SETTLE_MS`, `XCL_AMBIENT_AIR`. use std::collections::{HashMap, HashSet}; use std::ffi::c_void; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock, RwLock}; +use std::time::Instant; use windows::core::{Interface, PCSTR}; use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; @@ -42,6 +43,8 @@ struct Config { least: f32, ao: f32, reflect: f32, + settle_ms: f32, + air: f32, } impl Default for Config { @@ -53,6 +56,8 @@ impl Default for Config { least: 0.025, ao: 0.55, reflect: 0.50, + settle_ms: 250.0, + air: 1.5, } } } @@ -85,10 +90,29 @@ fn config() -> &'static Config { least: env_f32("XCL_AMBIENT_LEAST", def.least, 0.0, 2.0), ao: env_f32("XCL_AMBIENT_AO", def.ao, 0.0, 1.0), reflect: env_f32("XCL_AMBIENT_REFLECT", def.reflect, 0.05, 4.0), + settle_ms: env_f32("XCL_AMBIENT_SETTLE_MS", def.settle_ms, 0.0, 10_000.0), + air: env_f32("XCL_AMBIENT_AIR", def.air, 0.0, 16.0), } }) } +/// Time-based EMA smoothing factor `1 - exp(-dt / tau)` for sky-dome ambient settling. +/// Snaps immediately (`1.0`) on the first captured sample or when `settle_ms <= 0`. +fn settle_alpha(dt_s: f32, settle_ms: f32, first_sample: bool) -> f32 { + if first_sample || settle_ms <= 0.0 { + return 1.0; + } + let dt = dt_s.clamp(0.0, 2.0); + let tau = (settle_ms * 1e-3).max(1e-4); + (1.0 - (-dt / tau).exp()).clamp(0.0, 1.0) +} + +fn monotonic_us() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + let base = EPOCH.get_or_init(Instant::now); + (base.elapsed().as_micros() as u64).saturating_add(1) +} + /// Whether sky-following stand-in ambient tracking is enabled (`XCL_AMBIENT != 0/off`). pub fn enabled() -> bool { config().mode != Mode::Off @@ -109,6 +133,7 @@ pub(super) enum PassRole { SkyDome, TemporalResolve, ReflectionHistory, + InscatteringVolume, } fn contains_ascii_ci(haystack: &[u8], needle: &[u8]) -> bool { @@ -131,6 +156,8 @@ fn classify_cs(blob: &[u8]) -> Option { Some(PassRole::TemporalResolve) } else if contains_ascii_ci(blob, b"CS_UpdateHistory") { Some(PassRole::ReflectionHistory) + } else if contains_ascii_ci(blob, b"CS_AccumulateLocalLightInscatteringVolume") { + Some(PassRole::InscatteringVolume) } else { None } @@ -155,7 +182,8 @@ pub(super) fn note_graphics_pso(pso: usize, ps: Option<&[u8]>) { } /// Whether a compute shader blob belongs to a pass handled by stand-in ambient lighting -/// (`CS_ScreenProbes_TemporalResolve` / `CS_UpdateHistory`). +/// (`CS_ScreenProbes_TemporalResolve` / `CS_UpdateHistory` / +/// `CS_AccumulateLocalLightInscatteringVolume`). pub(super) fn is_ambient_compute(blob: &[u8]) -> bool { classify_cs(blob).is_some() } @@ -369,6 +397,55 @@ fn score_dispatch_target(rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; Some(d88.min(d84).min(d42)) } +fn is_air_volume_uav_format(fmt: i32) -> bool { + // R16G16B16A16_FLOAT (10), R11G11B10_FLOAT (26) + matches!(fmt, 10 | 26) +} + +/// Match a 3D volumetric inscattering froxel UAV against dispatch grid dimensions, returning +/// a lower-is-better score when compatible (`None` if incompatible). +fn score_volume_target(rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; 3]) -> Option { + if rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE3D + || rd.SampleDesc.Count != 1 + || rd.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 + || !is_air_volume_uav_format(view_fmt) + { + return None; + } + let w = rd.Width as u32; + let h = rd.Height; + let d = rd.DepthOrArraySize as u32; + if w < 16 || h < 16 || d < 4 { + return None; + } + if groups[0] == 0 || groups[1] <= 1 { + return Some(u64::MAX - (w as u64).saturating_mul(h as u64).saturating_mul(d as u64)); + } + let max_w = groups[0].saturating_mul(32); + let max_h = groups[1].saturating_mul(32); + let min_w = (groups[0] / 2).max(16); + let min_h = (groups[1] / 2).max(16); + if w < min_w || w > max_w || h < min_h || h > max_h { + return None; + } + let dw = (w as i64 - groups[0].saturating_mul(8) as i64) + .unsigned_abs() + .min((w as i64 - groups[0].saturating_mul(4) as i64).unsigned_abs()); + let dh = (h as i64 - groups[1].saturating_mul(8) as i64) + .unsigned_abs() + .min((h as i64 - groups[1].saturating_mul(4) as i64).unsigned_abs()); + let dd = if groups[2] <= 1 { + 0 + } else { + (d as i64 - groups[2] as i64) + .unsigned_abs() + .min((d as i64 - groups[2].saturating_mul(2) as i64).unsigned_abs()) + .min((d as i64 - groups[2].saturating_mul(4) as i64).unsigned_abs()) + .min((d as i64 - groups[2].saturating_mul(8) as i64).unsigned_abs()) + }; + Some(dw + dh + dd) +} + #[cfg(test)] fn matches_dispatch_target(rd: &D3D12_RESOURCE_DESC, groups: [u32; 3]) -> bool { score_dispatch_target(rd, rd.Format.0, groups).is_some() @@ -397,7 +474,9 @@ struct AmbientDevice { rs: ID3D12RootSignature, reduce_pso: ID3D12PipelineState, fill_pso: ID3D12PipelineState, + fill_write_pso: ID3D12PipelineState, reflect_pso: ID3D12PipelineState, + air_pso: ID3D12PipelineState, sky_copy: ID3D12Resource, sky_level: ID3D12Resource, dummy_depth: ID3D12Resource, @@ -407,6 +486,7 @@ struct AmbientDevice { inc: u32, next_group: AtomicU32, sky_ready: AtomicBool, + last_sky_us: AtomicU64, } unsafe impl Send for AmbientDevice {} @@ -444,7 +524,7 @@ cbuffer C : register(b0) { float gain; float power; float least; - float _p3; + float settle_alpha; uint _u4; uint _u5; uint _u6; @@ -477,13 +557,20 @@ void main(uint3 gtid : SV_GroupThreadID, uint gidx : SV_GroupIndex) { } if (gidx == 0) { float3 mean_rgb = max(gs_sum[0] * (1.0 / 64.0), 0.0); - float3 level = gain * pow(mean_rgb, power) + least; + float3 target = gain * pow(mean_rgb, power) + least; + float4 prev = sky_level[0]; + float a = saturate(settle_alpha); + float3 level = (a >= 0.999 || !all(isfinite(prev.rgb)) || prev.w <= 0.0) + ? target + : lerp(prev.rgb, target, a); float lum = dot(level, float3(0.2126, 0.7152, 0.0722)); sky_level[0] = float4(level, lum); } } "#; +/// Screen-space radiance floor + 8-tap IGN-rotated golden-angle horizon crease AO + outlier +/// probe tile suppression (requires typed UAV load on `out_uav`). const AMBIENT_FILL_HLSL: &str = r#" Texture2D depth_tex : register(t0); RWTexture2D out_uav : register(u0); @@ -498,6 +585,33 @@ cbuffer C : register(b0) { uint sky_ready; float fallback_level; }; +float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { + float d0 = depth_tex.Load(int3(dc, 0)); + if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { + return 1.0; + } + float ign = frac(52.9829189 * frac(dot(float2(tid), float2(0.06711056, 0.00583715)))); + float base_ang = ign * 6.2831853; + float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); + float inv_d0 = 1.0 / max(d0, 1e-5); + float occ = 0.0; + [unroll] + for (uint i = 0; i < 4; ++i) { + float ang = base_ang + float(i) * 0.78539816; + float t = frac(ign * 0.61803399 + (float(i) + 0.5) * 0.25); + float rad = clamp(max_rad * sqrt(t), 1.5, 16.0); + int2 ofs = int2(int(round(cos(ang) * rad)), int(round(sin(ang) * rad))); + float dp = depth_tex.Load(int3(clamp(dc + ofs, int2(0, 0), maxc), 0)); + float dn = depth_tex.Load(int3(clamp(dc - ofs, int2(0, 0), maxc), 0)); + float rp = (dp - d0) * inv_d0; + float rn = (dn - d0) * inv_d0; + float wp = (isfinite(dp) && dp > 1e-6 && dp < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rp))) : 0.0; + float wn = (isfinite(dn) && dn > 1e-6 && dn < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rn))) : 0.0; + float conc = max(0.0, rp * wp + rn * wn); + occ += saturate((conc - 0.003) * 4.5); + } + return saturate(1.0 - ao_strength * saturate(occ * 0.25)); +} [numthreads(8, 8, 1)] void main(uint3 tid : SV_DispatchThreadID) { if (tid.x >= width || tid.y >= height) return; @@ -505,20 +619,82 @@ void main(uint3 tid : SV_DispatchThreadID) { float ao = 1.0; if (has_depth != 0 && depth_w > 0 && depth_h > 0) { int2 dc = int2( - min((tid.x * depth_w) / max(width, 1u), depth_w - 1), - min((tid.y * depth_h) / max(height, 1u), depth_h - 1) + int(min((tid.x * depth_w) / max(width, 1u), depth_w - 1)), + int(min((tid.y * depth_h) / max(height, 1u), depth_h - 1)) ); - float d0 = depth_tex.Load(int3(dc, 0)); - if (isfinite(d0) && d0 > 1e-6 && d0 < 0.99999) { - int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); - float d1 = depth_tex.Load(int3(clamp(dc + int2(2, 0), int2(0, 0), maxc), 0)); - float d2 = depth_tex.Load(int3(clamp(dc - int2(2, 0), int2(0, 0), maxc), 0)); - float d3 = depth_tex.Load(int3(clamp(dc + int2(0, 2), int2(0, 0), maxc), 0)); - float d4 = depth_tex.Load(int3(clamp(dc - int2(0, 2), int2(0, 0), maxc), 0)); - float avg = 0.25 * (d1 + d2 + d3 + d4); - float crease = saturate(abs(avg - d0) / max(d0, 1e-4) * 3.0); - ao = 1.0 - ao_strength * crease; - } + int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); + ao = horizon_crease_ao(tid.xy, dc, maxc); + } + float3 amb_ao = amb * ao; + float amb_lum = max(dot(amb, float3(0.2126, 0.7152, 0.0722)), 0.02); + float cap_lum = 4.0 * amb_lum; + float4 cur = out_uav[tid.xy]; + float3 existing = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + float cur_lum = dot(existing, float3(0.2126, 0.7152, 0.0722)); + if (cur_lum > cap_lum) { + existing *= (cap_lum / max(cur_lum, 1e-6)); + } + float ch_cap = cap_lum * 1.5; + existing = min(existing, float3(ch_cap, ch_cap, ch_cap)); + float3 out_rgb = max(existing, amb_ao); + out_uav[tid.xy] = float4(out_rgb, isfinite(cur.a) ? cur.a : 1.0); +} +"#; + +/// Write-only fallback for `TemporalResolve` when typed UAV load is unsupported on `out_uav`. +const AMBIENT_FILL_WRITE_HLSL: &str = r#" +Texture2D depth_tex : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint depth_w; + uint depth_h; + uint has_depth; + float ao_strength; + uint sky_ready; + float fallback_level; +}; +float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { + float d0 = depth_tex.Load(int3(dc, 0)); + if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { + return 1.0; + } + float ign = frac(52.9829189 * frac(dot(float2(tid), float2(0.06711056, 0.00583715)))); + float base_ang = ign * 6.2831853; + float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); + float inv_d0 = 1.0 / max(d0, 1e-5); + float occ = 0.0; + [unroll] + for (uint i = 0; i < 4; ++i) { + float ang = base_ang + float(i) * 0.78539816; + float t = frac(ign * 0.61803399 + (float(i) + 0.5) * 0.25); + float rad = clamp(max_rad * sqrt(t), 1.5, 16.0); + int2 ofs = int2(int(round(cos(ang) * rad)), int(round(sin(ang) * rad))); + float dp = depth_tex.Load(int3(clamp(dc + ofs, int2(0, 0), maxc), 0)); + float dn = depth_tex.Load(int3(clamp(dc - ofs, int2(0, 0), maxc), 0)); + float rp = (dp - d0) * inv_d0; + float rn = (dn - d0) * inv_d0; + float wp = (isfinite(dp) && dp > 1e-6 && dp < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rp))) : 0.0; + float wn = (isfinite(dn) && dn > 1e-6 && dn < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rn))) : 0.0; + float conc = max(0.0, rp * wp + rn * wn); + occ += saturate((conc - 0.003) * 4.5); + } + return saturate(1.0 - ao_strength * saturate(occ * 0.25)); +} +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height) return; + float3 amb = (sky_ready != 0) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + float ao = 1.0; + if (has_depth != 0 && depth_w > 0 && depth_h > 0) { + int2 dc = int2( + int(min((tid.x * depth_w) / max(width, 1u), depth_w - 1)), + int(min((tid.y * depth_h) / max(height, 1u), depth_h - 1)) + ); + int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); + ao = horizon_crease_ao(tid.xy, dc, maxc); } out_uav[tid.xy] = float4(amb * ao, 1.0); } @@ -548,10 +724,48 @@ void main(uint3 tid : SV_DispatchThreadID) { } "#; +/// Lightweight 3D froxel luminance cap for `CS_AccumulateLocalLightInscatteringVolume`: smoothly +/// compresses over-bright indoor volumetric haze against the settled sky luminance * `air_scale` +/// while preserving sky scatter chromaticity through windows. +const AIR_CAP_HLSL: &str = r#" +Texture2D _unused : register(t0); +RWTexture3D vol_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint depth; + uint _u3; + uint _u4; + float air_scale; + float _p6; + float _p7; +}; +[numthreads(8, 8, 2)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height || tid.z >= depth) return; + float4 cur = vol_uav[tid]; + float3 rgb = all(isfinite(cur.rgb)) ? max(cur.rgb, 0.0) : float3(0.0, 0.0, 0.0); + float sky_lum = max(sky_level[0].w, 0.01); + float cap = max(sky_lum * air_scale, 0.01); + float lum = dot(rgb, float3(0.2126, 0.7152, 0.0722)); + if (lum > cap) { + float excess = lum - cap; + float rolled = cap + excess / (1.0 + excess / max(cap, 1e-4)); + rgb *= (rolled / max(lum, 1e-6)); + } + float ch_cap = cap * 2.0; + rgb = min(rgb, float3(ch_cap, ch_cap, ch_cap)); + vol_uav[tid] = float4(rgb, isfinite(cur.a) ? cur.a : 0.0); +} +"#; + unsafe fn build_device(dev: &ID3D12Device) -> Option { let reduce_bc = compile_cs_sm5(SKY_REDUCE_HLSL)?; let fill_bc = compile_cs_sm5(AMBIENT_FILL_HLSL)?; + let fill_write_bc = compile_cs_sm5(AMBIENT_FILL_WRITE_HLSL)?; let reflect_bc = compile_cs_sm5(REFLECT_CLAMP_HLSL)?; + let air_bc = compile_cs_sm5(AIR_CAP_HLSL)?; // Shared compute RS: [0] 8 root constants (b0), [1] 1 SRV (t0), [2] 2 UAVs (u0..u1) let srv_range = D3D12_DESCRIPTOR_RANGE { @@ -641,7 +855,9 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { }; let reduce_pso = make_cs(&reduce_bc)?; let fill_pso = make_cs(&fill_bc)?; + let fill_write_pso = make_cs(&fill_write_bc)?; let reflect_pso = make_cs(&reflect_bc)?; + let air_pso = make_cs(&air_bc)?; let default_hp = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; let make_res = |rd: &D3D12_RESOURCE_DESC, init: D3D12_RESOURCE_STATES| -> Option { @@ -710,7 +926,9 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { rs, reduce_pso, fill_pso, + fill_write_pso, reflect_pso, + air_pso, sky_copy, sky_level, dummy_depth, @@ -720,6 +938,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { inc, next_group: AtomicU32::new(0), sky_ready: AtomicBool::new(false), + last_sky_us: AtomicU64::new(0), }) } @@ -830,7 +1049,15 @@ pub(super) unsafe fn after_draw(list: *mut c_void, pso_resolved: usize) { let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 14)); let cfg = config(); - let consts = [cfg.gain.to_bits(), cfg.power.to_bits(), cfg.least.to_bits(), 0, 0, 0, 0, 0]; + let now_us = monotonic_us(); + let prev_us = ad.last_sky_us.swap(now_us, Ordering::AcqRel); + let first_sample = prev_us == 0 || !ad.sky_ready.load(Ordering::Acquire); + let dt_s = if first_sample { 0.0 } else { now_us.saturating_sub(prev_us) as f32 * 1e-6 }; + let alpha = settle_alpha(dt_s, cfg.settle_ms, first_sample); + if !first_sample { + uav_barrier(list, ad.sky_level.as_raw() as usize); + } + let consts = [cfg.gain.to_bits(), cfg.power.to_bits(), cfg.least.to_bits(), alpha.to_bits(), 0, 0, 0, 0]; set_heaps(list, 1, &heap_raw); set_cs_rs(list, ad.rs.as_raw()); set_pso(list, ad.reduce_pso.as_raw()); @@ -924,14 +1151,15 @@ unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMu } /// Inspect a compute dispatch's bound descriptor tables, SM 6.6 directly-indexed view heap -/// (`view_heap_base`), and root/table CBVs to locate its output screen-space float UAV -/// (and optional depth SRV for crease AO). +/// (`view_heap_base`), and root/table CBVs to locate its output float UAV (2D screen-space or +/// 3D froxel volume when `want_3d` is true) and optional depth SRV for crease AO. unsafe fn find_dispatch_views( layout: &Layout, args: &[u8], groups: [u32; 3], view_heap_base: u32, -) -> (Option<(usize, i32, u32, u32)>, Option<(usize, i32, u32, u32)>, usize, usize, usize) { + want_3d: bool, +) -> (Option<(usize, i32, u32, u32, u32)>, Option<(usize, i32, u32, u32)>, usize, usize, usize) { let Some(u) = crate::gpu::uma::get() else { return (None, None, 0, 0, 0) }; let word = |at: usize| args.get(at..at + 4).map(|b| u32::from_le_bytes(b.try_into().unwrap())); let mut param_tables: Vec = Vec::new(); @@ -1002,7 +1230,7 @@ unsafe fn find_dispatch_views( } } - let mut uav_hit: Option<(u64, usize, i32, u32, u32)> = None; + let mut uav_hit: Option<(u64, usize, i32, u32, u32, u32)> = None; let mut depth_hit: Option<(usize, i32, u32, u32)> = None; let slots = VIEW_SLOTS.read().unwrap(); let Some(vs) = slots.as_ref() else { return (None, None, tables.len(), indices.len(), table_cbvs) }; @@ -1028,12 +1256,18 @@ unsafe fn find_dispatch_views( let Some(res) = ID3D12Resource::from_raw_borrowed(&ptr) else { return }; let rd = res.GetDesc(); if ve.is_uav { - if let Some(score) = score_dispatch_target(&rd, ve.fmt, groups) { - if uav_hit.is_none_or(|(best, _, _, _, _)| score < best) { - uav_hit = Some((score, ve.res, ve.fmt, rd.Width as u32, rd.Height)); + let scored = if want_3d { + score_volume_target(&rd, ve.fmt, groups).map(|s| (s, rd.DepthOrArraySize as u32)) + } else { + score_dispatch_target(&rd, ve.fmt, groups).map(|s| (s, 1u32)) + }; + if let Some((score, depth)) = scored { + if uav_hit.is_none_or(|(best, _, _, _, _, _)| score < best) { + uav_hit = Some((score, ve.res, ve.fmt, rd.Width as u32, rd.Height, depth)); } } - } else if depth_hit.is_none() + } else if !want_3d + && depth_hit.is_none() && rd.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && rd.DepthOrArraySize == 1 && rd.SampleDesc.Count == 1 @@ -1054,12 +1288,14 @@ unsafe fn find_dispatch_views( check_slot(addr); } } - (uav_hit.map(|(_, r, f, w, h)| (r, f, w, h)), depth_hit, tables.len(), indices.len(), table_cbvs) + (uav_hit.map(|(_, r, f, w, h, d)| (r, f, w, h, d)), depth_hit, tables.len(), indices.len(), table_cbvs) } /// Called right after a translated compute dispatch completes: when RT is gated off and a sky -/// dome sample has been captured, replace `CS_ScreenProbes_TemporalResolve` with sky-following -/// ambient + depth-crease AO and clamp `CS_UpdateHistory` reflections to `reflect * ambient`. +/// dome sample has been captured, apply the sky-following screen-space radiance floor + 8-tap +/// horizon crease AO on `CS_ScreenProbes_TemporalResolve`, clamp `CS_UpdateHistory` reflections +/// to `reflect * ambient`, and cap `CS_AccumulateLocalLightInscatteringVolume` 3D froxel haze +/// against settled sky luminance * `air`. pub(super) unsafe fn after_compute_dispatch( list: *mut c_void, pso_resolved: usize, @@ -1072,7 +1308,11 @@ pub(super) unsafe fn after_compute_dispatch( return; } let Some(role) = role_of(pso_resolved) else { return }; - if !matches!(role, PassRole::TemporalResolve | PassRole::ReflectionHistory) { + if !matches!(role, PassRole::TemporalResolve | PassRole::ReflectionHistory | PassRole::InscatteringVolume) { + return; + } + let cfg = config(); + if role == PassRole::InscatteringVolume && cfg.air <= 0.0 { return; } let ty = list_x::tracked_list_type(list); @@ -1111,8 +1351,9 @@ pub(super) unsafe fn after_compute_dispatch( } } - let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(layout, args, groups, view_heap_base); - let Some((uav_res, uav_fmt, w, h)) = uav_opt else { + let want_3d = role == PassRole::InscatteringVolume; + let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(layout, args, groups, view_heap_base, want_3d); + let Some((uav_res, uav_fmt, w, h, d)) = uav_opt else { static MISS: AtomicU64 = AtomicU64::new(0); if MISS.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_info!( @@ -1121,7 +1362,8 @@ pub(super) unsafe fn after_compute_dispatch( } return; }; - if role == PassRole::ReflectionHistory && !typed_uav_load_supported(&dev, DXGI_FORMAT(uav_fmt)) { + let can_typed_load = typed_uav_load_supported(&dev, DXGI_FORMAT(uav_fmt)); + if matches!(role, PassRole::ReflectionHistory | PassRole::InscatteringVolume) && !can_typed_load { static NO_LOAD: AtomicU64 = AtomicU64::new(0); if NO_LOAD.fetch_add(1, Ordering::Relaxed) < 2 { crate::xlog_info!("D3D12.X: ambient: {role:?} skipped (typed UAV load unsupported for fmt {uav_fmt})"); @@ -1149,12 +1391,22 @@ pub(super) unsafe fn after_compute_dispatch( Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }, }, }; - let out_uav_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC { - Format: DXGI_FORMAT(uav_fmt), - ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, - Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { - Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }, - }, + let out_uav_desc = if want_3d { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(uav_fmt), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE3D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture3D: D3D12_TEX3D_UAV { MipSlice: 0, FirstWSlice: 0, WSize: d }, + }, + } + } else { + D3D12_UNORDERED_ACCESS_VIEW_DESC { + Format: DXGI_FORMAT(uav_fmt), + ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_UAV { MipSlice: 0, PlaneSlice: 0 }, + }, + } }; let level_uav = D3D12_UNORDERED_ACCESS_VIEW_DESC { Format: DXGI_FORMAT_UNKNOWN, @@ -1177,15 +1429,21 @@ pub(super) unsafe fn after_compute_dispatch( let set_cs_consts: unsafe extern "system" fn(*mut c_void, u32, u32, *const u32, u32) = std::mem::transmute(real::orig_fn(list, 35)); let dispatch: unsafe extern "system" fn(*mut c_void, u32, u32, u32) = std::mem::transmute(real::orig_fn(list, 14)); - let cfg = config(); - let (pso, consts) = match role { + let (pso, consts, disp) = match role { PassRole::TemporalResolve => ( - ad.fill_pso.as_raw(), + if can_typed_load { ad.fill_pso.as_raw() } else { ad.fill_write_pso.as_raw() }, [w, h, depth_w, depth_h, has_depth, cfg.ao.to_bits(), sky_ready as u32, cfg.least.to_bits()], + (w.div_ceil(8), h.div_ceil(8), 1), ), PassRole::ReflectionHistory => ( ad.reflect_pso.as_raw(), [w, h, 0, 0, 0, cfg.reflect.to_bits(), 0, 0], + (w.div_ceil(8), h.div_ceil(8), 1), + ), + PassRole::InscatteringVolume => ( + ad.air_pso.as_raw(), + [w, h, d, 0, 0, cfg.air.to_bits(), 0, 0], + (w.div_ceil(8), h.div_ceil(8), d.div_ceil(2)), ), PassRole::SkyDome => return, }; @@ -1195,13 +1453,13 @@ pub(super) unsafe fn after_compute_dispatch( set_cs_consts(list, 0, 8, consts.as_ptr(), 0); set_cs_table(list, 1, gpu0); set_cs_table(list, 2, gpu0 + inc); - dispatch(list, w.div_ceil(8), h.div_ceil(8), 1); + dispatch(list, disp.0, disp.1, disp.2); uav_barrier(list, uav_res); list_x::restore_after_internal_pass(list, false, true); static LOGGED: AtomicU64 = AtomicU64::new(0); - if LOGGED.fetch_add(1, Ordering::Relaxed) < 4 { - crate::xlog_info!("D3D12.X: ambient: applied {role:?} stand-in on {w}x{h} fmt {uav_fmt} (depth AO: {has_depth})"); + if LOGGED.fetch_add(1, Ordering::Relaxed) < 6 { + crate::xlog_info!("D3D12.X: ambient: applied {role:?} stand-in on {w}x{h}x{d} fmt {uav_fmt} (depth AO: {has_depth})"); } } @@ -1284,7 +1542,53 @@ mod tests { fn sm5_ambient_hlsl_shaders_compile_cleanly() { assert!(compile_cs_sm5(SKY_REDUCE_HLSL).is_some(), "SKY_REDUCE_HLSL failed D3DCompile"); assert!(compile_cs_sm5(AMBIENT_FILL_HLSL).is_some(), "AMBIENT_FILL_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(AMBIENT_FILL_WRITE_HLSL).is_some(), "AMBIENT_FILL_WRITE_HLSL failed D3DCompile"); assert!(compile_cs_sm5(REFLECT_CLAMP_HLSL).is_some(), "REFLECT_CLAMP_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(AIR_CAP_HLSL).is_some(), "AIR_CAP_HLSL failed D3DCompile"); + } + + #[test] + fn inscattering_volume_classification_volume_scoring_and_time_based_settling() { + assert_eq!( + classify_cs(b"ILDN\0CS_AccumulateLocalLightInscatteringVolume\0"), + Some(PassRole::InscatteringVolume) + ); + assert!(is_ambient_compute(b"ILDN\0CS_AccumulateLocalLightInscatteringVolume_V2\0")); + + let def = Config::default(); + assert!((def.settle_ms - 250.0).abs() < 1e-6); + assert!((def.air - 1.5).abs() < 1e-6); + + // First capture or settle_ms == 0 snaps immediately; subsequent samples follow 1 - exp(-dt/tau). + assert_eq!(settle_alpha(0.016, 250.0, true), 1.0); + assert_eq!(settle_alpha(0.016, 0.0, false), 1.0); + assert_eq!(settle_alpha(0.0, 250.0, false), 0.0); + let a_frame = settle_alpha(1.0 / 60.0, 250.0, false); + let a_tau = settle_alpha(0.25, 250.0, false); + let a_long = settle_alpha(1.0, 250.0, false); + assert!(a_frame > 0.05 && a_frame < 0.08, "16.7 ms EMA step: {a_frame}"); + assert!((a_tau - (1.0 - (-1.0f32).exp())).abs() < 1e-5, "dt == tau: {a_tau}"); + assert!(a_long > a_tau && a_long < 1.0, "1 s EMA step: {a_long}"); + + // 3D froxel volume matching: accepts 3D RGBA16F and R11G11B10F UAVs, rejects 2D and wrong formats. + let vol = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE3D, + Width: 160, + Height: 90, + DepthOrArraySize: 64, + MipLevels: 1, + Format: DXGI_FORMAT_R16G16B16A16_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + assert!(score_volume_target(&vol, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [20, 12, 32]).is_some()); + assert!(score_volume_target(&vol, DXGI_FORMAT_R11G11B10_FLOAT.0, [0, 0, 0]).is_some()); + assert!(score_volume_target(&vol, DXGI_FORMAT_R32G32B32A32_FLOAT.0, [20, 12, 32]).is_none()); + let tex2d = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, ..vol }; + assert!(score_volume_target(&tex2d, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [20, 12, 1]).is_none()); + let tiny = D3D12_RESOURCE_DESC { DepthOrArraySize: 2, ..vol }; + assert!(score_volume_target(&tiny, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [20, 12, 1]).is_none()); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 684302b84b..4cffb0a3b7 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -2408,7 +2408,7 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { s.uma_windows = Some(w); } let w = s.uma_windows.as_deref().unwrap(); - let first = w[0]; + let first = w.iter().copied().find(|&v| v != 0).ok_or("unified memory is not open on the GPU")?; Ok([ first, w.get(1).copied().filter(|&v| v != 0).unwrap_or(first), @@ -2644,6 +2644,18 @@ fn align_root_uav(va: u64) -> Result<(u64, u32), String> { Ok((va & !255, (va & 255) as u32)) } +/// Resolve an optional auxiliary root UAV address (`u4`: count buffer in `SCALE_ARGS_HLSL`, +/// group-limit buffer in `GUARD_ARGS_HLSL`), guaranteeing a valid non-null GPU VA by falling +/// back to `fallback_va` whenever `primary_va` is `None` or `Some(0)` so drivers never +/// speculatively fetch from GPU VA `0x0`. +fn resolve_aux_uav_va(primary_va: Option, fallback_va: u64) -> Result { + match primary_va.filter(|&va| va != 0) { + Some(va) => Ok(va), + None if fallback_va != 0 => Ok(fallback_va), + None => Err("missing valid non-null fallback GPU VA for auxiliary root UAV (u4)".into()), + } +} + /// Validate `SCALE_ARGS_HLSL`'s command-buffer layout and return the source byte span (`max * stride`). fn validate_scale_args_layout(max: u32, stride: u32, mesh_offset: u32) -> Result { if max == 0 { @@ -2808,12 +2820,16 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis } with(this, |s| s.inline_guard = None); let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, 256)?; - let lim_off = (crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32; let dst_va = dst.GetGPUVirtualAddress() + dst_off; + if dst_va == 0 { + return Err("indirect guard scratch buffer has null GPU VA".into()); + } + let lim_off = if dispatch_io_va != 0 { (crate::gpu::recomp::IO_GROUP_LIMIT * 4) as u32 } else { 0 }; if super::console_heap::window_views_ready() { if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, 12) { let (rs, pso) = guard_indirect_heap_pipeline(&dev)?; let consts = [src_slot, src_off, most_groups(), lim_off]; + let lim_va = resolve_aux_uav_va((dispatch_io_va != 0).then_some(dispatch_io_va), dst_va)?; ensure_heaps_cached(this); // the title's writes of the arguments before this (`fresh_indirect_arguments`) emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); @@ -2821,7 +2837,7 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis list.SetPipelineState(&pso); list.SetComputeRoot32BitConstants(0, consts.len() as u32, consts.as_ptr() as *const c_void, 0); list.SetComputeRootUnorderedAccessView(1, dst_va); - list.SetComputeRootUnorderedAccessView(2, dispatch_io_va); + list.SetComputeRootUnorderedAccessView(2, lim_va); list.Dispatch(1, 1, 1); emit_transition_and_uav(list, &dst, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, GUARDED_ARGS_STATE); with(this, |s| { @@ -2839,6 +2855,7 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; + let lim_va = resolve_aux_uav_va((dispatch_io_va != 0).then_some(dispatch_io_va), consts_va)?; // the title's writes of the arguments before this (`fresh_indirect_arguments`) emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); @@ -2846,7 +2863,7 @@ unsafe fn guard_dispatch_args(this: *mut c_void, list: &ID3D12GraphicsCommandLis list.SetComputeRootUnorderedAccessView(0, consts_va); list.SetComputeRootUnorderedAccessView(1, src_base); list.SetComputeRootUnorderedAccessView(2, dst_va); - list.SetComputeRootUnorderedAccessView(3, dispatch_io_va); + list.SetComputeRootUnorderedAccessView(3, lim_va); list.Dispatch(1, 1, 1); // Transition scratch to INDIRECT_ARGUMENT | NON_PIXEL_SHADER_RESOURCE and flush the // `IO_GROUP_LIMIT` store in `dispatch_io_va`. @@ -2908,6 +2925,9 @@ unsafe fn guard_draw_args( with(this, |s| s.inline_guard = None); let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, commands)?; let dst_va = dst.GetGPUVirtualAddress() + dst_off; + if dst_va == 0 { + return Err("indirect draw guard scratch buffer has null GPU VA".into()); + } if super::console_heap::window_views_ready() { if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, commands as usize) { let (rs, pso) = guard_draw_heap_pipeline(&dev)?; @@ -3228,6 +3248,9 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman with(this, |s| s.inline_guard = None); let (dst, dst_off, slot, prev_state) = scratch_args_pingpong(this, &dev, commands.saturating_mul(2))?; let dst_va = dst.GetGPUVirtualAddress() + dst_off; + if dst_va == 0 { + return Err("scaled indirect scratch buffer has null GPU VA".into()); + } if super::console_heap::window_views_ready() { if let Some((src_slot, src_off)) = uma_heap_slot_off(u, src, commands as usize) { let cnt_loc = match count { @@ -3272,9 +3295,10 @@ unsafe fn make_scaled_args_buffer(this: *mut c_void, list: &ID3D12GraphicsComman let p = with(this, |s| s.arena.take(u, std::mem::size_of_val(&consts), 256, &mut s.uma)).ok_or("unified memory is full")?; std::ptr::copy_nonoverlapping(consts.as_ptr().cast::(), p, std::mem::size_of_val(&consts)); let consts_va = super::real::uma_va_of(p as usize).ok_or("unified memory is not open on the GPU")?; - // Bind u4 unconditionally (to `consts_va` when no count buffer is supplied) because - // `SCALE_ARGS_HLSL` statically references `cnt : register(u4)`. - let cnt_base = count_bound.map_or(consts_va, |(base, _)| base); + // Bind u4 unconditionally to a valid non-null GPU VA (falling back to `consts_va` when no + // count buffer is supplied) because `SCALE_ARGS_HLSL` statically declares `cnt : register(u4)` + // and AMD/NVIDIA hardware may speculatively fetch unbound/null root UAVs. + let cnt_base = resolve_aux_uav_va(count_bound.map(|(base, _)| base), consts_va)?; // the title's writes of the arguments before this (`fresh_indirect_arguments`) emit_uav_and_transition(list, &dst, prev_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); list.SetComputeRootSignature(&rs); @@ -6774,6 +6798,26 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) assert_eq!(draw_sig_of(sig), None); } + #[test] + fn aux_uav_u4_fallback_and_non_poisoning_zero_max_guards() { + // Primary non-null GPU VA is preserved; None or Some(0) falls back to valid non-null VA. + assert_eq!(resolve_aux_uav_va(Some(0x1_0000_0100), 0x2_0000_0200).unwrap(), 0x1_0000_0100); + assert_eq!(resolve_aux_uav_va(None, 0x2_0000_0200).unwrap(), 0x2_0000_0200); + assert_eq!(resolve_aux_uav_va(Some(0), 0x2_0000_0200).unwrap(), 0x2_0000_0200); + // Never allows GPU VA 0x0 to be bound on u4 even if fallback is also 0. + assert!(resolve_aux_uav_va(None, 0).is_err()); + assert!(resolve_aux_uav_va(Some(0), 0).is_err()); + + // max == 0 is rejected immediately before emitting any scale/draw guard pass. + assert!(validate_scale_args_layout(0, 16, 4).is_err()); + + // Per-record indirect draw guard is strictly non-poisoning: a garbage record zeroes only + // itself and never rejects subsequent valid records. + let records = [(u32::MAX, u32::MAX), (3000, 4), (DRAW_VERTS_PER_INST_LIMIT, 1), (1024, 16)]; + let rejected: Vec = records.iter().map(|&(v, i)| draw_record_rejected(v, i)).collect(); + assert_eq!(rejected, vec![true, false, true, false]); + } + #[test] fn recycle_into_pool_drops_overflow_outside_pool_lock() { struct ReentrantDrop { diff --git a/crates/xcl/src/hle/d3d12x/gpu_awake.rs b/crates/xcl/src/hle/d3d12x/gpu_awake.rs new file mode 100644 index 0000000000..141385f0d8 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gpu_awake.rs @@ -0,0 +1,412 @@ +//! AMD GPU keep-awake compute heartbeat (`XCL_GPU_AWAKE`). +//! +//! On AMD RDNA2/RDNA3 GPUs, the SMU can drop shader clocks during 1.2–2.4 ms CPU gaps between +//! title command-list submissions, inflating GPU frame time by 20–30%. While the title is actively +//! submitting GPU work (within the last 250 ms), a single lightweight background thread keeps at +//! most two tiny async-compute dispatches in flight on a dedicated `D3D12_COMMAND_LIST_TYPE_COMPUTE` +//! queue so the GPU never falls into deep idle between submits, and sleeps immediately whenever +//! title submission pauses (menus, shader compile stalls, idle). +//! +//! Controlled by `XCL_GPU_AWAKE`: +//! - `0` / `off` / `false`: disabled +//! - `1` / `on` / `true`: forced on +//! - unset / `auto` / other: enabled automatically on AMD adapters (`vendor_id == 0x1002`) + +use std::ffi::c_void; +use std::mem::ManuallyDrop; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use windows::core::{Interface, PCSTR}; +use windows::Win32::Foundation::HANDLE; +use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; + +/// PCI vendor ID for AMD GPUs. +const AMD_VENDOR_ID: u32 = 0x1002; +/// How long after the most recent title GPU submit we keep submitting heartbeats. +const ACTIVE_WINDOW_MS: u64 = 250; +/// Sleep interval while the title is idle (no submit within `ACTIVE_WINDOW_MS`). +const IDLE_SLEEP_MS: u64 = 4; +/// Fence wait slice so `stop()` or device removal is noticed promptly. +const WAIT_SLICE_MS: u32 = 100; +/// Bounded drain timeout on clean shutdown before dropping D3D12 objects. +const SHUTDOWN_DRAIN_MS: u32 = 500; + +/// Minimal SM 5.0 compute shader: 64 threads running a 400,000-step LCG and writing 1 uint each +/// (256 bytes total) to a root UAV at `u0` (no descriptor heap required). +const HEARTBEAT_HLSL: &str = r#" +RWByteAddressBuffer dst : register(u0); + +[numthreads(64, 1, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + uint x = tid.x ^ 0x9e3779b9u; + [loop] + for (uint i = 0u; i < 400000u; ++i) { + x = x * 1664525u + 1013904223u; + } + dst.Store(tid.x * 4u, x); +} +"#; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + Off, + On, + Auto, +} + +fn parse_mode(val: Option<&str>) -> Mode { + let Some(raw) = val.map(str::trim).filter(|s| !s.is_empty()) else { + return Mode::Auto; + }; + if raw.eq_ignore_ascii_case("0") || raw.eq_ignore_ascii_case("off") || raw.eq_ignore_ascii_case("false") { + Mode::Off + } else if raw.eq_ignore_ascii_case("1") || raw.eq_ignore_ascii_case("on") || raw.eq_ignore_ascii_case("true") { + Mode::On + } else { + Mode::Auto + } +} + +fn should_enable(mode: Mode, vendor_id: u32) -> bool { + match mode { + Mode::Off => false, + Mode::On => true, + Mode::Auto => vendor_id == AMD_VENDOR_ID, + } +} + +fn configured_mode() -> Mode { + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| parse_mode(std::env::var("XCL_GPU_AWAKE").ok().as_deref())) +} + +static STARTED: OnceLock<()> = OnceLock::new(); +static STOP: AtomicBool = AtomicBool::new(false); +static LAST_SUBMIT_MS: AtomicU64 = AtomicU64::new(0); + +fn epoch_ms() -> u64 { + static EPOCH: OnceLock = OnceLock::new(); + // +1 so 0 unambiguously means "no title submit observed yet". + EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64 + 1 +} + +/// Record that the title just submitted GPU work so the heartbeat thread stays active for the next +/// `ACTIVE_WINDOW_MS` (250 ms). Lock-free single atomic store on the hot submit path. +pub(super) fn note_activity() { + LAST_SUBMIT_MS.store(epoch_ms(), Ordering::Relaxed); +} + +/// Signal the background heartbeat thread to stop cleanly. +pub(super) fn stop() { + STOP.store(true, Ordering::Release); +} + +/// Start the GPU keep-awake heartbeat thread if enabled by `XCL_GPU_AWAKE` (auto-enabled on AMD +/// `vendor_id == 0x1002`). Idempotent via `OnceLock`. +/// +/// # Safety +/// `device` must be a valid live `ID3D12Device`. +pub(super) unsafe fn start(device: &ID3D12Device, vendor_id: u32) { + let mode = configured_mode(); + if !should_enable(mode, vendor_id) { + return; + } + let dev_clone = device.clone(); + STARTED.get_or_init(|| { + STOP.store(false, Ordering::Release); + struct SendDevice(ID3D12Device); + // COM ID3D12Device methods used here are free-threaded per D3D12 spec. + unsafe impl Send for SendDevice {} + let send_dev = SendDevice(dev_clone); + let spawned = std::thread::Builder::new().name("xcl-gpu-awake".into()).spawn(move || { + let dev = send_dev; + run_worker(dev.0, vendor_id); + }); + if let Err(e) = spawned { + crate::xlog_warn!("D3D12.X: failed to spawn xcl-gpu-awake thread: {e}"); + } + }); +} + +fn compile_heartbeat_cs() -> Option> { + unsafe { + let mut blob = None; + let r = D3DCompile( + HEARTBEAT_HLSL.as_ptr() as *const c_void, + HEARTBEAT_HLSL.len(), + PCSTR::null(), + None, + None, + PCSTR(b"main\0".as_ptr()), + PCSTR(b"cs_5_0\0".as_ptr()), + 0, + 0, + &mut blob, + None, + ); + match (r, blob) { + (Ok(()), Some(b)) => Some(std::slice::from_raw_parts(b.GetBufferPointer() as *const u8, b.GetBufferSize()).to_vec()), + _ => None, + } + } +} + +struct EventGuard(windows_sys::Win32::Foundation::HANDLE); + +impl EventGuard { + fn new() -> Result { + let h = unsafe { windows_sys::Win32::System::Threading::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) }; + if h.is_null() { + Err("CreateEventW failed".into()) + } else { + Ok(Self(h)) + } + } + + fn as_win_handle(&self) -> HANDLE { + HANDLE(self.0) + } + + fn wait(&self, timeout_ms: u32) { + unsafe { + windows_sys::Win32::System::Threading::WaitForSingleObject(self.0, timeout_ms); + } + } +} + +impl Drop for EventGuard { + fn drop(&mut self) { + if !self.0.is_null() { + unsafe { + windows_sys::Win32::Foundation::CloseHandle(self.0); + } + } + } +} + +struct RecordedSlot { + _alloc: ID3D12CommandAllocator, + _list: ID3D12GraphicsCommandList, + cmd_list: ID3D12CommandList, +} + +struct HeartbeatState { + queue: ID3D12CommandQueue, + _uav_buf: ID3D12Resource, + _root_sig: ID3D12RootSignature, + _pso: ID3D12PipelineState, + slots: [RecordedSlot; 2], + fence: ID3D12Fence, + event: EventGuard, +} + +unsafe fn init_state(device: &ID3D12Device) -> Result { + let bytecode = compile_heartbeat_cs().ok_or_else(|| "D3DCompile failed for heartbeat compute shader".to_string())?; + + let queue: ID3D12CommandQueue = device + .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, + Priority: D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0, + Flags: D3D12_COMMAND_QUEUE_FLAG_NONE, + NodeMask: 0, + }) + .map_err(|e| format!("CreateCommandQueue(COMPUTE) failed: {e}"))?; + + let mut uav_opt: Option = None; + device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + }, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + None, + &mut uav_opt, + ) + .map_err(|e| format!("CreateCommittedResource(UAV) failed: {e}"))?; + let uav_buf = uav_opt.ok_or_else(|| "CreateCommittedResource(UAV) returned null".to_string())?; + let uav_va = uav_buf.GetGPUVirtualAddress(); + + let param = D3D12_ROOT_PARAMETER { + ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, + Anonymous: D3D12_ROOT_PARAMETER_0 { + Descriptor: D3D12_ROOT_DESCRIPTOR { ShaderRegister: 0, RegisterSpace: 0 }, + }, + ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, + }; + let rs_desc = D3D12_ROOT_SIGNATURE_DESC { + NumParameters: 1, + pParameters: ¶m, + NumStaticSamplers: 0, + pStaticSamplers: std::ptr::null(), + Flags: D3D12_ROOT_SIGNATURE_FLAG_NONE, + }; + let mut rs_blob = None; + D3D12SerializeRootSignature(&rs_desc, D3D_ROOT_SIGNATURE_VERSION_1, &mut rs_blob, None) + .map_err(|e| format!("D3D12SerializeRootSignature failed: {e}"))?; + let rs_blob = rs_blob.ok_or_else(|| "D3D12SerializeRootSignature returned null blob".to_string())?; + let rs_bytes = std::slice::from_raw_parts(rs_blob.GetBufferPointer() as *const u8, rs_blob.GetBufferSize()); + let root_sig: ID3D12RootSignature = device + .CreateRootSignature(0, rs_bytes) + .map_err(|e| format!("CreateRootSignature failed: {e}"))?; + + let mut pso_desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: ManuallyDrop::new(Some(root_sig.clone())), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytecode.as_ptr() as *const c_void, + BytecodeLength: bytecode.len(), + }, + ..Default::default() + }; + let pso_res: windows::core::Result = device.CreateComputePipelineState(&pso_desc); + ManuallyDrop::drop(&mut pso_desc.pRootSignature); + let pso = pso_res.map_err(|e| format!("CreateComputePipelineState failed: {e}"))?; + + let make_slot = || -> Result { + let alloc: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE) + .map_err(|e| format!("CreateCommandAllocator(COMPUTE) failed: {e}"))?; + let list: ID3D12GraphicsCommandList = device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &alloc, Some(&pso)) + .map_err(|e| format!("CreateCommandList(COMPUTE) failed: {e}"))?; + list.SetComputeRootSignature(&root_sig); + list.SetPipelineState(&pso); + list.SetComputeRootUnorderedAccessView(0, uav_va); + list.Dispatch(1, 1, 1); + list.Close().map_err(|e| format!("CommandList::Close failed: {e}"))?; + let cmd_list: ID3D12CommandList = list.cast().map_err(|e| format!("cast to ID3D12CommandList failed: {e}"))?; + Ok(RecordedSlot { _alloc: alloc, _list: list, cmd_list }) + }; + let slots = [make_slot()?, make_slot()?]; + + let fence: ID3D12Fence = device + .CreateFence(0, D3D12_FENCE_FLAG_NONE) + .map_err(|e| format!("CreateFence failed: {e}"))?; + let event = EventGuard::new()?; + + Ok(HeartbeatState { + queue, + _uav_buf: uav_buf, + _root_sig: root_sig, + _pso: pso, + slots, + fence, + event, + }) +} + +fn run_worker(device: ID3D12Device, vendor_id: u32) { + let state = match super::title_textures::own_work(|| unsafe { init_state(&device) }) { + Ok(s) => s, + Err(e) => { + crate::xlog_warn!("D3D12.X: GPU keep-awake heartbeat disabled ({e})"); + return; + } + }; + crate::xlog_info!("D3D12.X: GPU keep-awake async-compute heartbeat active (vendor {vendor_id:#06x}, XCL_GPU_AWAKE=0 to disable)"); + + let mut fence_val: u64 = 0; + while !STOP.load(Ordering::Acquire) { + if unsafe { device.GetDeviceRemovedReason() }.is_err() { + break; + } + let last = LAST_SUBMIT_MS.load(Ordering::Relaxed); + let now = epoch_ms(); + if last == 0 || now.saturating_sub(last) > ACTIVE_WINDOW_MS { + std::thread::sleep(Duration::from_millis(IDLE_SLEEP_MS)); + continue; + } + + // Keep at most 2 dispatches in flight: wait until the slot we are about to reuse has + // finished executing on the GPU (`fence >= fence_val - 1`). + let wait_target = fence_val.saturating_sub(1); + if wait_target > 0 { + loop { + let completed = unsafe { state.fence.GetCompletedValue() }; + if completed == u64::MAX || unsafe { device.GetDeviceRemovedReason() }.is_err() { + return; + } + if completed >= wait_target || STOP.load(Ordering::Acquire) { + break; + } + if unsafe { state.fence.SetEventOnCompletion(wait_target, state.event.as_win_handle()) }.is_err() { + return; + } + state.event.wait(WAIT_SLICE_MS); + } + if STOP.load(Ordering::Acquire) { + break; + } + } + + let slot_idx = (fence_val as usize) & 1; + let next_val = fence_val + 1; + let submitted = super::title_textures::own_work(|| unsafe { + state.queue.ExecuteCommandLists(&[Some(state.slots[slot_idx].cmd_list.clone())]); + state.queue.Signal(&state.fence, next_val).is_ok() + }); + if !submitted { + break; + } + fence_val = next_val; + } + + // Drain in-flight heartbeats briefly on clean stop so GPU finishes before COM objects drop. + if fence_val > 0 && unsafe { device.GetDeviceRemovedReason() }.is_ok() { + let completed = unsafe { state.fence.GetCompletedValue() }; + if completed < fence_val && completed != u64::MAX { + if unsafe { state.fence.SetEventOnCompletion(fence_val, state.event.as_win_handle()) }.is_ok() { + state.event.wait(SHUTDOWN_DRAIN_MS); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn env_mode_parsing_and_amd_auto_enable() { + assert_eq!(parse_mode(None), Mode::Auto); + assert_eq!(parse_mode(Some("")), Mode::Auto); + assert_eq!(parse_mode(Some("auto")), Mode::Auto); + assert_eq!(parse_mode(Some("unknown")), Mode::Auto); + + for off in ["0", "off", "OFF", "false", "False", " 0 "] { + assert_eq!(parse_mode(Some(off)), Mode::Off, "expected Off for {off:?}"); + } + for on in ["1", "on", "ON", "true", "True", " 1 "] { + assert_eq!(parse_mode(Some(on)), Mode::On, "expected On for {on:?}"); + } + + // Auto enables only for AMD (0x1002); On/Off override regardless of vendor. + assert!(should_enable(Mode::Auto, AMD_VENDOR_ID)); + assert!(!should_enable(Mode::Auto, 0x10DE)); // NVIDIA + assert!(!should_enable(Mode::Auto, 0x8086)); // Intel + assert!(!should_enable(Mode::Off, AMD_VENDOR_ID)); + assert!(should_enable(Mode::On, 0x10DE)); + assert!(should_enable(Mode::On, 0x8086)); + } + + #[test] + fn heartbeat_hlsl_compiles_with_d3dcompile() { + let bc = compile_heartbeat_cs().expect("HEARTBEAT_HLSL failed D3DCompile(cs_5_0)"); + assert!(bc.len() >= 32, "expected valid DXBC container, got {} bytes", bc.len()); + assert_eq!(&bc[..4], b"DXBC", "expected DXBC magic header"); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 42e4a80a74..3ca707783b 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -23,11 +23,13 @@ pub mod dred; mod fence_x; mod format_alias; pub mod frame; +pub(crate) mod gpu_awake; pub mod guard; mod late_release; pub mod layout; pub mod list_x; pub mod null; +pub(crate) mod pcores; mod place_times; pub mod present; pub mod pso_async; diff --git a/crates/xcl/src/hle/d3d12x/pcores.rs b/crates/xcl/src/hle/d3d12x/pcores.rs new file mode 100644 index 0000000000..802db928af --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/pcores.rs @@ -0,0 +1,270 @@ +//! Hybrid CPU P-core pinning (`XCL_FAST_CORES`). +//! +//! On hybrid CPUs (such as Intel 12th/13th/14th-gen processors with both Performance and Efficiency +//! cores), Windows can schedule latency-sensitive render/submit threads onto slower E-cores, +//! introducing frame-time spikes and delaying GPU submissions. This module queries +//! `GetSystemCpuSetInformation` dynamically from `kernel32.dll`, selects the Group 0 CPU set IDs +//! belonging to the highest `EfficiencyClass` when at least two distinct efficiency classes exist +//! (automatically a no-op on homogeneous CPUs such as AMD Ryzen), and pins calling threads via +//! `SetThreadSelectedCpuSets`. +//! +//! Controlled by `XCL_FAST_CORES`: `0` / `off` / `false` disables; default enabled on hybrid CPUs. + +use std::cell::Cell; +use std::ffi::c_void; +use std::sync::{Once, OnceLock}; + +/// `CPU_SET_INFORMATION_TYPE::CpuSetInformation` in `winnt.h`. +const CPU_SET_INFORMATION_TYPE_CPU_SET: u32 = 0; +/// Minimum byte size of a valid `SYSTEM_CPU_SET_INFORMATION` header + `CpuSet` fields through +/// `EfficiencyClass` and `AllFlags` / `Reserved` (`offset 0..24`). +const MIN_CPU_SET_ENTRY_SIZE: usize = 24; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct CpuSetEntry { + id: u32, + group: u16, + efficiency_class: u8, +} + +fn parse_enabled(val: Option<&str>) -> bool { + let Some(raw) = val.map(str::trim).filter(|s| !s.is_empty()) else { + return true; + }; + !(raw.eq_ignore_ascii_case("0") || raw.eq_ignore_ascii_case("off") || raw.eq_ignore_ascii_case("false")) +} + +fn enabled() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| parse_enabled(std::env::var("XCL_FAST_CORES").ok().as_deref())) +} + +/// Parse a raw `GetSystemCpuSetInformation` buffer into `CpuSetEntry` records. +/// +/// Layout of `SYSTEM_CPU_SET_INFORMATION` (`winnt.h`): +/// - `+0`: `DWORD Size` +/// - `+4`: `DWORD Type` (`0` = `CpuSetInformation`) +/// - `+8`: `DWORD Id` +/// - `+12`: `WORD Group` +/// - `+14..18`: `LogicalProcessorIndex`, `CoreIndex`, `LastLevelCacheIndex`, `NumaNodeIndex` +/// - `+18`: `BYTE EfficiencyClass` +fn parse_cpu_set_buffer(buf: &[u8]) -> Vec { + let mut entries = Vec::new(); + let mut offset = 0usize; + while offset + MIN_CPU_SET_ENTRY_SIZE <= buf.len() { + let size = u32::from_le_bytes(buf[offset..offset + 4].try_into().unwrap()) as usize; + if size < MIN_CPU_SET_ENTRY_SIZE || offset + size > buf.len() { + break; + } + let kind = u32::from_le_bytes(buf[offset + 4..offset + 8].try_into().unwrap()); + if kind == CPU_SET_INFORMATION_TYPE_CPU_SET { + let id = u32::from_le_bytes(buf[offset + 8..offset + 12].try_into().unwrap()); + let group = u16::from_le_bytes(buf[offset + 12..offset + 14].try_into().unwrap()); + let efficiency_class = buf[offset + 18]; + entries.push(CpuSetEntry { id, group, efficiency_class }); + } + offset += size; + } + entries +} + +/// Select Group 0 CPU set IDs with the highest `EfficiencyClass`, returning an empty `Vec` unless +/// Group 0 contains at least two distinct efficiency classes (auto-no-op on homogeneous CPUs). +fn select_fast_cpu_sets(entries: &[CpuSetEntry]) -> Vec { + let mut min_eff = u8::MAX; + let mut max_eff = u8::MIN; + let mut any_group0 = false; + for e in entries { + if e.group != 0 { + continue; + } + any_group0 = true; + min_eff = min_eff.min(e.efficiency_class); + max_eff = max_eff.max(e.efficiency_class); + } + if !any_group0 || min_eff == max_eff { + return Vec::new(); + } + entries + .iter() + .filter(|e| e.group == 0 && e.efficiency_class == max_eff) + .map(|e| e.id) + .collect() +} + +type GetSystemCpuSetInformationFn = unsafe extern "system" fn( + information: *mut u8, + buffer_length: u32, + returned_length: *mut u32, + process: *mut c_void, + flags: u32, +) -> i32; + +type SetThreadSelectedCpuSetsFn = unsafe extern "system" fn( + thread: *mut c_void, + cpu_set_ids: *const u32, + cpu_set_id_count: u32, +) -> i32; + +unsafe fn kernel32_proc(name: &[u8]) -> Option<*const c_void> { + use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleA, GetProcAddress}; + let h = GetModuleHandleA(b"kernel32.dll\0".as_ptr()); + if h.is_null() { + return None; + } + GetProcAddress(h, name.as_ptr()).map(|f| f as *const c_void) +} + +fn query_fast_cpu_sets() -> Vec { + if !enabled() { + return Vec::new(); + } + unsafe { + let Some(p) = kernel32_proc(b"GetSystemCpuSetInformation\0") else { + return Vec::new(); + }; + let get_info: GetSystemCpuSetInformationFn = std::mem::transmute(p); + let mut needed: u32 = 0; + let _ = get_info(std::ptr::null_mut(), 0, &mut needed, std::ptr::null_mut(), 0); + if needed < MIN_CPU_SET_ENTRY_SIZE as u32 { + return Vec::new(); + } + let mut buf = vec![0u8; needed as usize]; + let mut returned: u32 = 0; + if get_info(buf.as_mut_ptr(), buf.len() as u32, &mut returned, std::ptr::null_mut(), 0) == 0 { + return Vec::new(); + } + let len = (returned as usize).min(buf.len()); + select_fast_cpu_sets(&parse_cpu_set_buffer(&buf[..len])) + } +} + +fn fast_cpu_sets() -> &'static [u32] { + static IDS: OnceLock> = OnceLock::new(); + IDS.get_or_init(query_fast_cpu_sets) +} + +fn set_thread_cpu_sets_fn() -> Option { + static FN: OnceLock> = OnceLock::new(); + *FN.get_or_init(|| unsafe { + kernel32_proc(b"SetThreadSelectedCpuSets\0").map(|p| std::mem::transmute(p)) + }) +} + +thread_local! { + static THREAD_PINNED: Cell = const { Cell::new(false) }; +} + +/// Pin the calling thread to Group 0 P-core CPU sets on hybrid CPUs. +/// +/// Idempotent and cached per thread via `thread_local!`; no-op on homogeneous CPUs or when +/// `XCL_FAST_CORES=0`. +pub(super) fn pin_current_thread_fast() { + if THREAD_PINNED.with(|p| p.replace(true)) { + return; + } + let ids = fast_cpu_sets(); + if ids.is_empty() { + return; + } + let Some(set_fn) = set_thread_cpu_sets_fn() else { + return; + }; + let ok = unsafe { + let thread = windows_sys::Win32::System::Threading::GetCurrentThread(); + set_fn(thread, ids.as_ptr(), ids.len() as u32) != 0 + }; + if ok { + static LOGGED: Once = Once::new(); + LOGGED.call_once(|| { + crate::xlog_info!( + "D3D12.X: pinned latency-sensitive thread(s) to {} P-core logical CPUs (XCL_FAST_CORES=0 to disable)", + ids.len() + ); + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn env_parsing_enables_by_default_and_disables_on_zero_or_off() { + assert!(parse_enabled(None)); + assert!(parse_enabled(Some(""))); + assert!(parse_enabled(Some("1"))); + assert!(parse_enabled(Some("on"))); + assert!(parse_enabled(Some("true"))); + assert!(!parse_enabled(Some("0"))); + assert!(!parse_enabled(Some(" 0 "))); + assert!(!parse_enabled(Some("off"))); + assert!(!parse_enabled(Some("OFF"))); + assert!(!parse_enabled(Some("false"))); + } + + #[test] + fn heterogeneous_cpu_selects_highest_efficiency_group0_only() { + // Simulates Intel i5-13600KF (12 P-core threads @ eff 1, 8 E-core threads @ eff 0) + // plus a Group 1 entry with higher eff to verify Group 0 filtering. + let mut entries = Vec::new(); + for id in 0x100u32..0x10C { + entries.push(CpuSetEntry { id, group: 0, efficiency_class: 1 }); + } + for id in 0x10Cu32..0x114 { + entries.push(CpuSetEntry { id, group: 0, efficiency_class: 0 }); + } + entries.push(CpuSetEntry { id: 0x200, group: 1, efficiency_class: 2 }); + + let selected = select_fast_cpu_sets(&entries); + let expected: Vec = (0x100u32..0x10C).collect(); + assert_eq!(selected, expected); + } + + #[test] + fn homogeneous_cpu_is_noop() { + // Homogeneous Ryzen: all logical CPUs report the same EfficiencyClass (0). + let ryzen: Vec = (0..16) + .map(|i| CpuSetEntry { id: 256 + i, group: 0, efficiency_class: 0 }) + .collect(); + assert!(select_fast_cpu_sets(&ryzen).is_empty()); + + // Homogeneous all-1 efficiency class is also a no-op. + let uniform_one: Vec = (0..8) + .map(|i| CpuSetEntry { id: 256 + i, group: 0, efficiency_class: 1 }) + .collect(); + assert!(select_fast_cpu_sets(&uniform_one).is_empty()); + + // Empty list is a no-op. + assert!(select_fast_cpu_sets(&[]).is_empty()); + } + + #[test] + fn raw_buffer_parser_handles_variable_record_sizes_and_other_types() { + let mut buf = Vec::new(); + let push_rec = |buf: &mut Vec, size: usize, kind: u32, id: u32, group: u16, eff: u8| { + let start = buf.len(); + buf.resize(start + size, 0); + buf[start..start + 4].copy_from_slice(&(size as u32).to_le_bytes()); + buf[start + 4..start + 8].copy_from_slice(&kind.to_le_bytes()); + buf[start + 8..start + 12].copy_from_slice(&id.to_le_bytes()); + buf[start + 12..start + 14].copy_from_slice(&group.to_le_bytes()); + buf[start + 18] = eff; + }; + push_rec(&mut buf, 32, CPU_SET_INFORMATION_TYPE_CPU_SET, 0x100, 0, 1); + push_rec(&mut buf, 40, 99, 0x999, 0, 5); // non-CpuSetInformation record skipped + push_rec(&mut buf, 32, CPU_SET_INFORMATION_TYPE_CPU_SET, 0x101, 0, 0); + // Trailing truncated bytes must stop cleanly without panic. + buf.extend_from_slice(&[0u8; 8]); + + let parsed = parse_cpu_set_buffer(&buf); + assert_eq!( + parsed, + vec![ + CpuSetEntry { id: 0x100, group: 0, efficiency_class: 1 }, + CpuSetEntry { id: 0x101, group: 0, efficiency_class: 0 }, + ] + ); + assert_eq!(select_fast_cpu_sets(&parsed), vec![0x100]); + } +} diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index c51d80005d..8a53776ce7 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -8,12 +8,30 @@ //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. use std::collections::HashMap; -use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicU8, AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; /// Sentinel for `Pending::waited_frame`: no frame has spent graphics wait budget on this PSO yet. const UNWAITED: u64 = u64::MAX; +/// Lifecycle states for tracking whether a `Pending` pipeline currently counts toward +/// `WANTED_ACTIVE_COUNT`: +/// - `WANTED_NONE` (0): not wanted yet and not finished +/// - `WANTED_ACTIVE` (1): actively wanted and still queued/building (contributes +1) +/// - `WANTED_DONE` (2): completed, dropped unstarted, or permanently gated (contributes 0) +const WANTED_NONE: u8 = 0; +const WANTED_ACTIVE: u8 = 1; +const WANTED_DONE: u8 = 2; + +/// Number of `wanted` pipelines currently queued or building on workers. While non-zero, +/// speculative `xcl-pso-pre-*` preload pauses so background builds never steal RAM/CPU from +/// pipelines the current frame actually needs. +static WANTED_ACTIVE_COUNT: AtomicUsize = AtomicUsize::new(0); + +fn wanted_active() -> usize { + WANTED_ACTIVE_COUNT.load(Ordering::Acquire) +} + struct Pending { /// the build, until a worker – or a bind that cannot wait for the queue – takes it job: Mutex>, @@ -44,9 +62,17 @@ struct Pending { /// first frame that waited on this graphics PSO within `XCL_PSO_FRAME_BUDGET_MS` (`UNWAITED` /// if never waited yet): later frames skip waiting while workers finish compiling it waited_frame: AtomicU64, + /// tracks whether this entry currently contributes to `WANTED_ACTIVE_COUNT` + wanted_state: AtomicU8, demand: Mutex, } +impl Drop for Pending { + fn drop(&mut self) { + self.clear_wanted_active(); + } +} + /// Whether one of the title's threads waits for the pipeline, and the preload worker building it. #[derive(Default)] struct Demand { @@ -104,6 +130,22 @@ fn build(p: &Arc, job: Job, preload: bool) { } impl Pending { + fn mark_wanted_active(&self) { + if self + .wanted_state + .compare_exchange(WANTED_NONE, WANTED_ACTIVE, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + WANTED_ACTIVE_COUNT.fetch_add(1, Ordering::AcqRel); + } + } + + fn clear_wanted_active(&self) { + if self.wanted_state.swap(WANTED_DONE, Ordering::AcqRel) == WANTED_ACTIVE { + WANTED_ACTIVE_COUNT.fetch_sub(1, Ordering::AcqRel); + } + } + /// One of the title's threads is about to wait for it: the worker building it goes on now, /// at a normal priority. fn want(&self) { @@ -124,6 +166,7 @@ impl Pending { first }; if became_wanted { + self.mark_wanted_active(); crate::gpu::recomp::dxc::notify_wanted(); notify_queue_wanted(); super::real::notify_big_compile_wanted(); @@ -142,6 +185,7 @@ static PENDING: std::sync::RwLock>>> = std::s /// The build is done (`real`: its pipeline, 0 = failed). fn complete(p: &Pending, real: usize) { + p.clear_wanted_active(); if real == 0 { FAILED.fetch_add(1, Ordering::Relaxed); } else { @@ -299,6 +343,7 @@ fn next_needed() -> Option> { /// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. fn drop_unstarted_job(p: &Pending) { + p.clear_wanted_active(); let job = p.job.lock().unwrap().take(); if let Some(job) = job { { @@ -375,14 +420,40 @@ fn notify_queue_wanted() { } } +/// Number of `xcl-pso-*` worker threads: honors `XCL_PSO_THREADS` (or explicit `XCL_DXC_THREADS`), +/// otherwise caps default concurrency to `2..=6` so DXIL translation saturates without triggering +/// a multi-worker AMD LLVM commit/pagefile thrash storm on 32 GB systems. +fn pso_worker_threads() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| { + std::env::var("XCL_PSO_THREADS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&n| n > 0) + .or_else(|| { + std::env::var("XCL_DXC_THREADS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|&n| n > 0) + }) + .map(|n| n.clamp(1, 64)) + .unwrap_or_else(|| crate::gpu::recomp::dxc::compile_threads().min(6).max(2)) + }) +} + +/// Number of low-priority `xcl-pso-pre-*` preload threads (`1..=2` by default). +fn preload_worker_threads() -> usize { + (pso_worker_threads() / 3).clamp(1, 2) +} + fn queue() -> &'static Arc { WORK_QUEUE.get_or_init(|| { let q = Arc::new(PsoQueue::new()); // translation recurses deeply on big programs; DXC itself runs on its own pool - let n = crate::gpu::recomp::dxc::compile_threads(); + let n = pso_worker_threads(); for k in 0..n { let q = q.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { + let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(16 << 20).spawn(move || loop { while let Some(p) = next_needed() { build_queued(&p); } @@ -405,11 +476,12 @@ fn enqueue(p: Arc) { ); } -/// Commit-headroom thresholds (`GlobalMemoryStatusEx::ullAvailPageFile`) for throttling background -/// PSO compilation under memory pressure (`XCL_PSO_MEM_THROTTLE=0`: off). -const PRELOAD_PAUSE_COMMIT: u64 = 4 << 30; -const WORKER_CAP_2_COMMIT: u64 = 4 << 30; -const WORKER_CAP_1_COMMIT: u64 = 2 << 30; +/// Physical RAM & commit headroom thresholds (`min(ullAvailPhys, ullAvailPageFile)`) for +/// throttling background PSO compilation well before Windows starts paging out the title +/// (`XCL_PSO_MEM_THROTTLE=0`: off). +const PRELOAD_PAUSE_COMMIT: u64 = 6 << 30; +const WORKER_CAP_2_COMMIT: u64 = 5 << 30; +const WORKER_CAP_1_COMMIT: u64 = 3 << 30; fn mem_throttle_enabled() -> bool { static ON: OnceLock = OnceLock::new(); @@ -420,11 +492,11 @@ fn avail_commit_bytes() -> Option { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; m.dwLength = std::mem::size_of::() as u32; - (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPageFile) + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPhys.min(m.ullAvailPageFile)) } -/// Maximum concurrent top-level PSO worker builds allowed for the current available commit bytes: -/// `< 2 GiB` -> 1 worker (never 0, no deadlock), `< 4 GiB` -> at most 2, otherwise `max_workers`. +/// Maximum concurrent top-level PSO worker builds allowed for the current available RAM/commit: +/// `< 3 GiB` -> 1 worker (never 0, no deadlock), `< 5 GiB` -> at most 2, otherwise `max_workers`. fn worker_cap_for_commit(avail_commit: Option, max_workers: usize) -> usize { let max_workers = max_workers.max(1); match avail_commit { @@ -434,11 +506,17 @@ fn worker_cap_for_commit(avail_commit: Option, max_workers: usize) -> usize } } -/// Pause speculative `xcl-pso-pre-*` preload builds while available commit is below 4 GiB. +/// Pause speculative `xcl-pso-pre-*` preload builds while available RAM/commit is below 6 GiB. fn should_pause_preload(avail_commit: Option) -> bool { avail_commit.is_some_and(|avail| avail < PRELOAD_PAUSE_COMMIT) } +/// Pause speculative preload whenever ANY `wanted` pipeline is actively queued/in-flight OR +/// available RAM/commit headroom is below `PRELOAD_PAUSE_COMMIT`. +fn should_pause_preload_with_demand(avail_commit: Option, wanted: usize) -> bool { + wanted > 0 || should_pause_preload(avail_commit) +} + struct ActiveWorkerGate { active: Mutex, cv: Condvar, @@ -469,7 +547,7 @@ fn acquire_worker_slot(max_workers: usize) -> ActiveWorkerGuard { static LOGGED: std::sync::Once = std::sync::Once::new(); LOGGED.call_once(|| { crate::xlog_info!( - "D3D12.X: throttling PSO workers to {cap} under low commit headroom ({} MiB free)", + "D3D12.X: throttling PSO workers to {cap} under low RAM/commit headroom ({} MiB free)", avail.unwrap_or(0) >> 20 ); }); @@ -487,7 +565,7 @@ fn build_queued(p: &Arc) { drop_unstarted_job(p); return; } - let _slot = acquire_worker_slot(crate::gpu::recomp::dxc::compile_threads()); + let _slot = acquire_worker_slot(pso_worker_threads()); if p.orphan.load(Ordering::Acquire) { drop_unstarted_job(p); return; @@ -512,7 +590,7 @@ pub(super) fn build_pieces(jobs: Vec) -> Vec { }; // the helpers build for this worker's pipeline: the title waiting for it waits for them too let parent = BUILDING.with(|b| b.borrow().clone()); - for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { + for _ in 1..count.min(pso_worker_threads()) { let (drain, parent_run, parent_q) = (drain.clone(), parent.clone(), parent.clone()); queue().push( Box::new(move || { @@ -596,6 +674,7 @@ fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64, flag bvh_traversal: std::sync::atomic::AtomicBool::new(flags.bvh_traversal), deprioritized: std::sync::atomic::AtomicBool::new(flags.deprioritized), waited_frame: AtomicU64::new(UNWAITED), + wanted_state: AtomicU8::new(WANTED_NONE), demand: Default::default(), }); PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); @@ -1055,9 +1134,9 @@ fn preload() -> Option<&'static Preload> { }) .as_ref()?; STARTED.call_once(|| { - let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + let n = preload_worker_threads(); for k in 0..n { - let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { + let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(16 << 20).spawn(move || { unsafe { use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); @@ -1086,19 +1165,28 @@ fn preload() -> Option<&'static Preload> { { continue; } - // Pause speculative preload under low commit headroom (< 4 GiB) unless a bind - // actively wants this pipeline; leave `p.job` untouched so binds can take it. - while mem_throttle_enabled() - && !p.orphan.load(Ordering::Acquire) + // Pause speculative preload whenever ANY `wanted` pipeline is actively + // queued/in-flight or free RAM/commit headroom is below 6 GiB; leave `p.job` + // untouched so binds can take it immediately. + while !p.orphan.load(Ordering::Acquire) && !p.demand.lock().unwrap().wanted && p.job.lock().unwrap().is_some() - && should_pause_preload(avail_commit_bytes()) { - static PAUSED_LOG: std::sync::Once = std::sync::Once::new(); - PAUSED_LOG.call_once(|| { - crate::xlog_info!("D3D12.X: pausing speculative PSO preload under low commit headroom (< 4 GiB)"); - }); - std::thread::sleep(std::time::Duration::from_millis(50)); + let avail = mem_throttle_enabled().then(avail_commit_bytes).flatten(); + let low_mem = should_pause_preload(avail); + if !should_pause_preload_with_demand(avail, wanted_active()) { + break; + } + if low_mem { + static PAUSED_LOG: std::sync::Once = std::sync::Once::new(); + PAUSED_LOG.call_once(|| { + crate::xlog_info!( + "D3D12.X: pausing speculative PSO preload under low RAM/commit headroom (< 6 GiB, {} MiB free)", + avail.unwrap_or(0) >> 20 + ); + }); + } + std::thread::sleep(std::time::Duration::from_millis(25)); } if p.orphan.load(Ordering::Acquire) { drop_unstarted_job(&p); @@ -1252,7 +1340,7 @@ mod used_tests { #[test] fn a_pipeline_a_submit_needs_is_built_before_the_queue() { let order = Arc::new(Mutex::new(Vec::new())); - let backlog = 8 * crate::gpu::recomp::dxc::compile_threads(); + let backlog = 8 * pso_worker_threads(); let standins: Vec = (0..=backlog).map(|i| 0x7E57_E000usize + i).collect(); for &standin in &standins { let order = order.clone(); @@ -1613,7 +1701,7 @@ mod used_tests { } } - let n = crate::gpu::recomp::dxc::compile_threads(); + let n = pso_worker_threads(); let (started_tx, started_rx) = mpsc::channel(); let gate = Arc::new((Mutex::new(false), Condvar::new())); let mut blockers = Vec::with_capacity(n); @@ -1707,7 +1795,7 @@ mod used_tests { fn a_submit_builds_a_late_pipeline_no_worker_has_started() { let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); use std::time::{Duration, Instant}; - let n = crate::gpu::recomp::dxc::compile_threads(); + let n = pso_worker_threads(); let (started_tx, started_rx) = mpsc::channel(); let gate = Arc::new((Mutex::new(false), Condvar::new())); let mut blockers = Vec::with_capacity(n); @@ -1827,7 +1915,7 @@ mod used_tests { } // Saturate normal workers and verify released() drops the queued job immediately. - let n = crate::gpu::recomp::dxc::compile_threads(); + let n = pso_worker_threads(); let (started_tx, started_rx) = mpsc::channel(); let gate = Arc::new((Mutex::new(false), Condvar::new())); let open_normal = OpenGate(gate.clone()); @@ -1869,7 +1957,7 @@ mod used_tests { } // Saturate preload workers and verify released() drops the preloaded job immediately. - let m = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + let m = preload_worker_threads(); let (p_tx, p_rx) = mpsc::channel(); let p_gate = Arc::new((Mutex::new(false), Condvar::new())); let open_pre = OpenGate(p_gate.clone()); @@ -1952,6 +2040,7 @@ pub fn submit_gated(standin: usize, driver: usize) { bvh_traversal: std::sync::atomic::AtomicBool::new(true), deprioritized: std::sync::atomic::AtomicBool::new(true), waited_frame: AtomicU64::new(UNWAITED), + wanted_state: AtomicU8::new(WANTED_DONE), demand: Default::default(), }); PENDING.write().unwrap().get_or_insert_with(HashMap::new).insert(standin, p); @@ -2584,6 +2673,7 @@ mod pso_queue_tests { bvh_traversal: Default::default(), deprioritized: std::sync::atomic::AtomicBool::new(deprioritized), waited_frame: AtomicU64::new(UNWAITED), + wanted_state: AtomicU8::new(WANTED_NONE), demand: Mutex::new(Demand { wanted, by_submit: false, preload_thread: 0 }), }) } @@ -2605,6 +2695,7 @@ mod pso_queue_tests { bvh_traversal: Default::default(), deprioritized: Default::default(), waited_frame: AtomicU64::new(UNWAITED), + wanted_state: AtomicU8::new(WANTED_NONE), demand: Mutex::new(Demand { wanted, by_submit: false, preload_thread: 0 }), }) } @@ -2670,19 +2761,43 @@ mod pso_queue_tests { #[test] fn commit_headroom_throttles_workers_and_pauses_preload() { - assert_eq!(worker_cap_for_commit(None, 8), 8); - assert_eq!(worker_cap_for_commit(Some(6 << 30), 8), 8); - assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT), 8), 8); - assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT - 1), 8), 2); - assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_1_COMMIT), 8), 2); - assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_1_COMMIT - 1), 8), 1); - assert_eq!(worker_cap_for_commit(Some(0), 8), 1, "must never drop to 0 workers"); + assert_eq!(PRELOAD_PAUSE_COMMIT, 6 << 30); + assert_eq!(WORKER_CAP_2_COMMIT, 5 << 30); + assert_eq!(WORKER_CAP_1_COMMIT, 3 << 30); + + assert_eq!(worker_cap_for_commit(None, 6), 6); + assert_eq!(worker_cap_for_commit(Some(7 << 30), 6), 6); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT), 6), 6); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT - 1), 6), 2); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_1_COMMIT), 6), 2); + assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_1_COMMIT - 1), 6), 1); + assert_eq!(worker_cap_for_commit(Some(0), 6), 1, "must never drop to 0 workers"); assert_eq!(worker_cap_for_commit(Some(WORKER_CAP_2_COMMIT - 1), 1), 1); assert!(!should_pause_preload(None)); assert!(!should_pause_preload(Some(PRELOAD_PAUSE_COMMIT))); assert!(should_pause_preload(Some(PRELOAD_PAUSE_COMMIT - 1))); assert!(should_pause_preload(Some(0))); + + // Any active wanted pipeline pauses speculative preload even with ample free RAM. + assert!(!should_pause_preload_with_demand(Some(16 << 30), 0)); + assert!(should_pause_preload_with_demand(Some(16 << 30), 1)); + assert!(should_pause_preload_with_demand(None, 2)); + assert!(should_pause_preload_with_demand(Some(PRELOAD_PAUSE_COMMIT - 1), 0)); + + // Preload worker pool stays tightly bounded (1..=2). + let m = preload_worker_threads(); + assert!((1..=2).contains(&m), "expected preload_worker_threads in 1..=2, got {m}"); + + // Active wanted counter transitions cleanly without leaking on complete/drop. + let p = dummy_pending(false, false); + p.mark_wanted_active(); + p.mark_wanted_active(); // idempotent + assert!(wanted_active() >= 1); + p.clear_wanted_active(); + p.clear_wanted_active(); // idempotent + p.mark_wanted_active(); // post-DONE must not re-increment + assert_eq!(p.wanted_state.load(Ordering::Acquire), WANTED_DONE); } #[test] diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9d7af8caa7..b83e8ea755 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -570,6 +570,7 @@ pub fn init() -> Result { for (adapter, desc) in list { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { driver_cache::note_vendor(desc.VendorId); + super::gpu_awake::start(&dev, desc.VendorId); device = Some(dev); name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; @@ -5227,12 +5228,12 @@ fn big_compile_headroom(dxil_len: usize) -> u64 { (3u64 << 30).max(dxil_len as u64 * 512) } -/// That much commit is free (true when that is not known). +/// That much physical RAM and commit is free (true when that is not known). fn big_compile_commit_free(need: u64) -> bool { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; m.dwLength = std::mem::size_of::() as u32; - unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPageFile >= need } + unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPhys.min(m.ullAvailPageFile) >= need } } #[cfg(test)] @@ -9138,6 +9139,8 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis stop_if_device_removed(); return; } + super::pcores::pin_current_thread_fast(); + super::gpu_awake::note_activity(); // from here to the end: XCL's uploads and tile mappings before the lists, then the driver's // own work in the submission. Where that takes long, it is not the title's time // (`pso_async::title_held`) From a5233050aef2c78a68f238a69a90ea31cd23f8df Mon Sep 17 00:00:00 2001 From: Alp Pesen <5701011+AlpPesen@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:10:41 +0300 Subject: [PATCH 191/258] DXIL: fix compact SGPR liveness for RMW/CMOV SALU and Wave32 masks inst_sreg_scc_use_def now treats all S_CMOV* as conditional writes and S_ADDK_I32/S_MULK_I32/S_BITSET* as read-modify-write on SDST, and clamps Wave32 VALU 64-bit mask defs to 1 SGPR so live s[v+1] slots are not killed. Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/compact.rs | 75 ++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 63ae012587..6da31c6425 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -28,12 +28,16 @@ fn is_pure_nop(name: &str) -> bool { /// Conservative `(use_mask, def_mask)` over `s0..s105` (bits `0..106`) and `SCC` (bit `VAR_SCC`). /// Any register not provably unconditionally overwritten is omitted from `def_mask`; any unknown /// or indexed SGPR read sets all bits in `use_mask`. -fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded) -> (u128, u128) { +fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded, wave64: bool) -> (u128, u128) { use crate::gpu::rdna2::{field_value, register_scale, Variant}; if d.inst.name.starts_with("S_MOVREL") { return (ALL_SGPRS_MASK, 0); } - let cond_write = d.inst.name == "S_CMOVK_I32"; + let cond_write = d.inst.name.starts_with("S_CMOV"); + let rmw_dst = matches!( + d.inst.name, + "S_ADDK_I32" | "S_MULK_I32" | "S_BITSET0_B32" | "S_BITSET1_B32" | "S_BITSET0_B64" | "S_BITSET1_B64" + ); let (mut u, mut def) = (0u128, 0u128); for o in d.ienc.operands { if o.ty == "OPR_SSRC_SPECIAL_SCC" { @@ -76,11 +80,16 @@ fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded) -> (u128, u128) { continue; } let n = (o.size as u64).div_ceil(32).max(1); + // Wave32 VALU mask writers (V_CMP_*, V_ADD_CO_*, etc.) only write the low SGPR; do not + // mark s[v + 1] as killed. + let def_n = if !wave64 && o.output && o.size == 64 && !d.inst.name.starts_with("S_") { 1 } else { n }; for r in v..(v + n).min(106) { - if o.input || cond_write { + if o.input || (o.output && (cond_write || rmw_dst)) { u |= 1u128 << r; } - if o.output && !cond_write { + } + if o.output && !cond_write { + for r in v..(v + def_n).min(106) { def |= 1u128 << r; } } @@ -88,19 +97,19 @@ fn inst_sreg_scc_use_def(d: &crate::gpu::rdna2::Decoded) -> (u128, u128) { (u, def) } -fn compute_live_out(cfg: &Cfg, mblocks: &[MicroBlock], end_live: u128) -> Vec { +fn compute_live_out(cfg: &Cfg, mblocks: &[MicroBlock], end_live: u128, wave64: bool) -> Vec { let n = mblocks.len(); let mut b_use = vec![0u128; n]; let mut b_def = vec![0u128; n]; for (idx, blk) in mblocks.iter().enumerate() { let (mut u, mut d) = (0u128, 0u128); for &i in &blk.insts { - let (iu, id) = inst_sreg_scc_use_def(&cfg.insts[i]); + let (iu, id) = inst_sreg_scc_use_def(&cfg.insts[i], wave64); u |= iu & !d; d |= id; } if let Term::Cond(ci, ..) = blk.term { - let (iu, _) = inst_sreg_scc_use_def(&cfg.insts[ci]); + let (iu, _) = inst_sreg_scc_use_def(&cfg.insts[ci], wave64); u |= iu & !d; } b_use[idx] = u; @@ -378,7 +387,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { // bypass empty non-header jump blocks so neither `xcl_blocks` nor `FUNCTION` pays for them. let end_live = if lw.res.is_some() { ALL_SGPRS_MASK | SCC_LIVE_BIT } else { 0 }; if allow_split { - let live_out = compute_live_out(cfg, &mblocks, end_live); + let live_out = compute_live_out(cfg, &mblocks, end_live, lw.wave64); for (idx, blk) in mblocks.iter_mut().enumerate() { if let Some(r) = resolved_far_jump_reg(cfg, blk) { let clobber = (1u128 << r) | (1u128 << (r + 1)) | SCC_LIVE_BIT; @@ -492,7 +501,7 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { } let final_live_out = if allow_split { - compute_live_out(cfg, &mblocks, end_live) + compute_live_out(cfg, &mblocks, end_live, lw.wave64) } else { vec![ALL_SGPRS_MASK | SCC_LIVE_BIT; mblocks.len()] }; @@ -962,3 +971,51 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block } Ok(()) } + +#[cfg(test)] +mod liveness_tests { + use super::*; + use crate::gpu::rdna2; + + fn dec(name: &str, enc: &str, fields: &[(&str, u64)]) -> rdna2::Decoded { + let bytes = rdna2::encode(name, enc, fields, None).unwrap(); + rdna2::decode(&bytes, 0).unwrap() + } + + #[test] + fn cmov_and_rmw_salu_read_sdst_and_wave32_valu_keeps_hi_sgpr() { + // S_CMOV_B32 / S_CMOV_B64: conditional write reads SDST and must not kill it. + let cmov32 = dec("S_CMOV_B32", "ENC_SOP1", &[("SDST", 4), ("SSRC0", 2)]); + let (u, d) = inst_sreg_scc_use_def(&cmov32, true); + assert_ne!(u & (1u128 << 4), 0, "S_CMOV_B32 must use SDST"); + assert_eq!(d & (1u128 << 4), 0, "S_CMOV_B32 must not kill SDST"); + + let cmov64 = dec("S_CMOV_B64", "ENC_SOP1", &[("SDST", 6), ("SSRC0", 2)]); + let (u, d) = inst_sreg_scc_use_def(&cmov64, true); + assert_eq!(u & ((1u128 << 6) | (1u128 << 7)), (1u128 << 6) | (1u128 << 7)); + assert_eq!(d & ((1u128 << 6) | (1u128 << 7)), 0); + + // RMW SALU ops (S_ADDK_I32, S_MULK_I32, S_BITSET0_B32, S_BITSET1_B64): both use and def SDST. + for (name, enc, fields, width) in [ + ("S_ADDK_I32", "ENC_SOPK", &[("SDST", 8), ("SIMM16", 1)][..], 1u64), + ("S_MULK_I32", "ENC_SOPK", &[("SDST", 9), ("SIMM16", 3)][..], 1u64), + ("S_BITSET0_B32", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 128)][..], 1u64), + ("S_BITSET1_B64", "ENC_SOP1", &[("SDST", 12), ("SSRC0", 128)][..], 2u64), + ] { + let inst = dec(name, enc, fields); + let (u, d) = inst_sreg_scc_use_def(&inst, true); + let base = fields[0].1; + let mask = if width == 2 { (1u128 << base) | (1u128 << (base + 1)) } else { 1u128 << base }; + assert_eq!(u & mask, mask, "{name} must use SDST"); + assert_eq!(d & mask, mask, "{name} must def SDST"); + } + + // Wave32 VALU mask writer (V_CMP_EQ_U32 VOP3) writes only s4, leaving s5 live. + let vcmp = dec("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 256), ("SRC1", 257)]); + let (_, d32) = inst_sreg_scc_use_def(&vcmp, false); + assert_ne!(d32 & (1u128 << 4), 0, "Wave32 V_CMP must def s4"); + assert_eq!(d32 & (1u128 << 5), 0, "Wave32 V_CMP must not kill s5"); + let (_, d64) = inst_sreg_scc_use_def(&vcmp, true); + assert_eq!(d64 & ((1u128 << 4) | (1u128 << 5)), (1u128 << 4) | (1u128 << 5)); + } +} From e346b778efa4c311be8d36fe9e7fe90d818bc9b2 Mon Sep 17 00:00:00 2001 From: Alp Pesen <5701011+AlpPesen@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:11:14 +0300 Subject: [PATCH 192/258] Recompiler: match all VOP3 encoding names in ps_masks Use contains(VOP3) instead of starts_with(ENC_VOP3) in ps_masks so VOP3_SDST_ENC and VOP3*_INST_LITERAL instructions inspect SRC2 properly and scalar-vs-literal compares recognize Form::Uniform. Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/recomp/ps_masks.rs | 46 +++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/ps_masks.rs b/crates/xcl/src/gpu/recomp/ps_masks.rs index 28013110a2..026f8a2a4b 100644 --- a/crates/xcl/src/gpu/recomp/ps_masks.rs +++ b/crates/xcl/src/gpu/recomp/ps_masks.rs @@ -80,7 +80,7 @@ fn per_lane(d: &Decoded) -> u128 { return 0; } match fv(d, "SRC2") { - Some(v) if d.enc.name.starts_with("ENC_VOP3") => regs(v, 2), + Some(v) if d.enc.name.contains("VOP3") => regs(v, 2), _ => VCC, } } @@ -296,7 +296,7 @@ pub fn forms(insts: &[Decoded]) -> BTreeMap { continue; } // both operands scalar / constant: the mask is `cond ? EXEC : 0`, no ballot needed - let uniform = d.enc.name.starts_with("ENC_VOP3") && fv(d, "SRC0").is_some_and(|v| v < 256) && fv(d, "SRC1").is_some_and(|v| v < 256); + let uniform = d.enc.name.contains("VOP3") && fv(d, "SRC0").is_some_and(|v| v < 256) && fv(d, "SRC1").is_some_and(|v| v < 256); if uniform { out.insert(d.pc, Form::Uniform); } else if run(insts, &succ, &indirect, &z, ®ion, site).is_ok() { @@ -536,4 +536,46 @@ mod tests { ]; assert_eq!(forms_of(&prog), [Some(Form::Local)]); } + + #[test] + fn vop3_sdst_and_literal_encodings_are_recognized() { + // VOP3_SDST_ENC: V_ADD_CO_CI_U32 and V_SUB_CO_CI_U32 read carry-in from SRC2, not VCC. + for (op, src2) in [("V_ADD_CO_CI_U32", 20u64), ("V_SUB_CO_CI_U32", 22u64)] { + let bytes = rdna2::encode( + op, + "VOP3_SDST_ENC", + &[("VDST", 1), ("SDST", 106), ("SRC0", V + 2), ("SRC1", V + 3), ("SRC2", src2)], + None, + ) + .unwrap(); + let inst = rdna2::decode(&bytes, 0).unwrap(); + assert_eq!(inst.enc.name, "VOP3_SDST_ENC"); + assert_eq!(per_lane(&inst), regs(src2, 2)); + } + + // Scalar-vs-literal VOP3 compare is recognized as Form::Uniform. + let mut bytes = Vec::new(); + bytes.extend(rdna2::encode("S_WQM_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 126)], None).unwrap()); + let cmp_pc = bytes.len() as u64; + bytes.extend( + rdna2::encode( + "V_CMP_LT_F32", + "ENC_VOP3", + &[("VDST", 106), ("SRC0", 4), ("SRC1", 255)], + Some(0x3F80_0000), + ) + .unwrap(), + ); + bytes.extend(rdna2::encode("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 22), ("SSRC0", 106)], None).unwrap()); + bytes.extend(rdna2::encode("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", V + 3)], None).unwrap()); + bytes.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + let mut insts = Vec::new(); + let mut off = 0; + while off < bytes.len() { + let d = rdna2::decode(&bytes[off..], off as u64).unwrap(); + off += d.len; + insts.push(d); + } + assert_eq!(forms(&insts).get(&cmp_pc), Some(&Form::Uniform)); + } } From 5f21c68e403a7633adc4c8c43f91d07ea8db3473 Mon Sep 17 00:00:00 2001 From: Decodere <98278826+Decodere@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:06:09 +0300 Subject: [PATCH 193/258] Recompiler: mark SRC_VCCZ/SRC_EXECZ whole-live in x64_masks S_MOVREL and VOP3 mask ops Fix two soundness bugs in split-wave64 mask liveness (`x64_masks::uses` and `uses_fallback`): 1. `S_MOVREL*` with `SSRC0 == 251` (`SRC_VCCZ`) or `252` (`SRC_EXECZ`) clamped `raw` to `124` and dropped the whole-`VCC` read; union `scalar_code(raw, 1)` alongside `range(src, 124 - src)` so `SRC_VCCZ` marks `VCC` whole-live without setting spurious bit 125 for `SSRC0 == 124`. 2. `ENC_VOP3` / `VOP3_SDST_ENC` per-lane mask consumers (`V_CNDMASK_B32`, `V_ADD_CO_CI_U32`, `V_SUB_CO_CI_U32`, `V_SUBREV_CO_CI_U32`) skipped `SRC2` unconditionally, dropping whole-`VCC` / `EXEC` reads when `SRC2` is `251` (`SRC_VCCZ`) or `252` (`SRC_EXECZ`). Record `is_per_lane_mask` on `DynOp` (mirrored in `uses_fallback`) so `251`/`252` stay whole-live while lane-local SGPR/`VCC` (`106`) mask pairs remain omitted from `whole`. Also add a guard test verifying `ENC_VOP2` carry-out SDWA (`VOP2_VOP_SDWA`, including `OMOD = 2` with bit 47 set) always overwrites `VCC` and extend `use_plan_matches_fallback_across_all_rdna2_instructions` to `Variant::Sdwa`. Part of #675 Part of #1833 Part of #1269 Assisted-by: Google Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/recomp/x64_masks.rs | 128 ++++++++++++++++++++++--- 1 file changed, 115 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs index cc8b830edd..7796017f78 100644 --- a/crates/xcl/src/gpu/recomp/x64_masks.rs +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -109,6 +109,7 @@ struct DynOp { n: u8, is_write: bool, is_src0: bool, + is_per_lane_mask: bool, } impl DynOp { @@ -118,6 +119,7 @@ impl DynOp { n: 1, is_write: false, is_src0: false, + is_per_lane_mask: false, }; } @@ -199,9 +201,6 @@ impl UsePlanTable { { continue; } - if !o.output && per_lane && f == "SRC2" { - continue; - } let idx = plan.op_len as usize; if idx < MAX_DYN_OPS && n <= u8::MAX as u64 { plan.ops[idx] = DynOp { @@ -210,6 +209,7 @@ impl UsePlanTable { n: n as u8, is_write: o.output && !keeps, is_src0: f == "SRC0", + is_per_lane_mask: !o.output && per_lane && f == "SRC2", }; plan.op_len += 1; } else { @@ -271,8 +271,9 @@ fn use_plans() -> &'static UsePlanTable { fn uses_fallback(d: &Decoded) -> (Regs, Regs) { let name = d.inst.name; if name.starts_with("S_MOVREL") { - let src = rdna2::field_value(d.enc, &d.words, "SSRC0").unwrap_or(0).min(124); - return (range(src, 124 - src) | M0 | EXEC, 0); + let raw = rdna2::field_value(d.enc, &d.words, "SSRC0").unwrap_or(0); + let src = raw.min(124); + return (range(src, 124 - src) | scalar_code(raw, 1) | M0 | EXEC, 0); } let (mut whole, mut written) = (0 as Regs, 0 as Regs); let per_lane = reads_mask_per_lane(name); @@ -293,10 +294,10 @@ fn uses_fallback(d: &Decoded) -> (Regs, Regs) { } for o in d.ienc.operands { let n = (o.size as u64).div_ceil(32).max(1); - let regs = match (o.field, o.ty) { - (_, "OPR_VCC") => VCC, - (_, "OPR_EXEC" | "OPR_SDST_EXEC") => EXEC, - (_, "OPR_SDST_M0") => M0, + let (regs, code) = match (o.field, o.ty) { + (_, "OPR_VCC") => (VCC, None), + (_, "OPR_EXEC" | "OPR_SDST_EXEC") => (EXEC, None), + (_, "OPR_SDST_M0") => (M0, None), (None, _) | (Some("LITERAL"), _) => continue, (Some(f), ty) => { if o.implicit || !["SREG", "SSRC", "SDST", "OPR_SRC", "SMEM_OFFSET"].iter().any(|k| ty.contains(k)) { @@ -305,7 +306,8 @@ fn uses_fallback(d: &Decoded) -> (Regs, Regs) { if f == "SRC0" && d.variant != Variant::Plain { continue; } - scalar_code(rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f), n) + let code = rdna2::field_value(d.enc, &d.words, f).unwrap_or(0) * rdna2::register_scale(f); + (scalar_code(code, n), Some(code)) } }; if o.output { @@ -314,7 +316,11 @@ fn uses_fallback(d: &Decoded) -> (Regs, Regs) { } else { written |= regs; } - } else if !(per_lane && (o.ty == "OPR_VCC" || o.field == Some("SRC2"))) { + } else if per_lane && o.field == Some("SRC2") { + if matches!(code, Some(251 | 252)) { + whole |= regs; + } + } else if !(per_lane && o.ty == "OPR_VCC") { whole |= regs; } } @@ -335,8 +341,9 @@ fn uses_with_table(d: &Decoded, table: &UsePlanTable) -> (Regs, Regs) { // `smovrel`: s[src + m0] is read, s[dst + m0] written (s_movrelsd_2: both) – any // register from the encoded one up to s123, VCC included; nothing for certain // overwritten - let src = extract_ranges(&d.words, plan.movrel_ssrc0).min(124); - return (range(src, 124 - src) | M0 | EXEC, 0); + let raw = extract_ranges(&d.words, plan.movrel_ssrc0); + let src = raw.min(124); + return (range(src, 124 - src) | scalar_code(raw, 1) | M0 | EXEC, 0); } let mut whole = plan.const_whole; let mut written = plan.const_written; @@ -361,6 +368,12 @@ fn uses_with_table(d: &Decoded, table: &UsePlanTable) -> (Regs, Regs) { continue; } let code = extract_ranges(&d.words, op.ranges) * op.scale as u64; + if op.is_per_lane_mask { + if matches!(code, 251 | 252) { + whole |= scalar_code(code, op.n as u64); + } + continue; + } let regs = scalar_code(code, op.n as u64); if op.is_write { written |= regs; @@ -997,6 +1010,85 @@ mod tests { assert!(mask_needed(&whole_live_out(&p, false), 0, 106)); } + #[test] + fn sdwa_vop2_carry_always_overwrites_vcc_even_with_omod_bit47() { + const CBRANCH_VCCZ: I = ("S_CBRANCH_VCCZ", "ENC_SOPP", &[("SIMM16", 0)]); + // RDNA2 VOP2 carry-out SDWA uses VOP2_VOP_SDWA ([47:40] = DST_SEL/DST_UNUSED/CLAMP/OMOD), + // never VOP2_VOP_SDWA_SDST_ENC: OMOD=2 sets bit 47, yet carry-out still overwrites VCC. + for name in ["V_ADD_CO_CI_U32", "V_SUB_CO_CI_U32", "V_SUBREV_CO_CI_U32"] { + let f = [ + ("VDST", 4), ("SRC0", 0xF9), ("VSRC0", 0), ("VSRC1", 1), + ("SRC0_SEL", 6), ("SRC1_SEL", 6), + ("DST_SEL", 6), ("DST_UNUSED", 2), ("CLAMP", 1), ("OMOD", 2), + ]; + let bytes: Vec = [ + rdna2::encode(CMP.0, CMP.1, CMP.2, None).unwrap(), + rdna2::encode(name, "VOP2_VOP_SDWA", &f, None).unwrap(), + rdna2::encode(CBRANCH_VCCZ.0, CBRANCH_VCCZ.1, CBRANCH_VCCZ.2, None).unwrap(), + rdna2::encode(ENDPGM.0, ENDPGM.1, ENDPGM.2, None).unwrap(), + ] + .concat(); + let p = program(&bytes); + assert_eq!(uses(&p[1]), uses_fallback(&p[1])); + assert_eq!(uses(&p[1]).1, VCC, "{name} VOP2_VOP_SDWA OMOD=2 must overwrite only VCC"); + let live = whole_live_out(&p, false); + assert!(!mask_needed(&live, 0, 106) && mask_needed(&live, 1, 106), "{name} kills prior VCC"); + } + } + + #[test] + fn s_movreld_with_src_vccz_marks_vcc_whole_live() { + for name in ["S_MOVRELD_B32", "S_MOVRELD_B64"] { + let p = asm(&[CMP, (name, "ENC_SOP1", &[("SDST", 2), ("SSRC0", 251)]), ENDPGM]); + assert_eq!(uses(&p[1]), uses_fallback(&p[1])); + assert_eq!(uses(&p[1]).0 & VCC, VCC, "{name} SSRC0=251 must read whole VCC"); + assert_eq!(uses(&p[1]).1, 0, "{name} must not kill destination"); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106), "{name} SSRC0=251 keeps VCC live"); + let execz = asm(&[(name, "ENC_SOP1", &[("SDST", 2), ("SSRC0", 252)]), ENDPGM]); + assert_eq!(uses(&execz[0]), uses_fallback(&execz[0])); + assert_eq!(uses(&execz[0]).0, M0 | EXEC, "{name} SSRC0=252 reads M0 | EXEC"); + let m0_src = asm(&[(name, "ENC_SOP1", &[("SDST", 2), ("SSRC0", 124)]), ENDPGM]); + assert_eq!(uses(&m0_src[0]).0, M0 | EXEC, "{name} SSRC0=124 sets no spurious bit 125"); + } + } + + #[test] + fn vop3_per_lane_mask_ops_with_src_vccz_mark_vcc_whole_live() { + let cases: [(&str, &str, &[(&str, u64)]); 4] = [ + ("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 251)]), + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2), ("SDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 251)]), + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2), ("SDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 251)]), + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2), ("SDST", 4), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 251)]), + ]; + for (name, enc, f) in cases { + let p = asm(&[CMP, (name, enc, f), ENDPGM]); + assert_eq!(uses(&p[1]), uses_fallback(&p[1])); + assert_eq!(uses(&p[1]).0 & VCC, VCC, "{name} SRC2=251 must read whole VCC"); + assert!(mask_needed(&whole_live_out(&p, false), 0, 106), "{name} SRC2=251 keeps VCC live"); + } + // SRC2=106 (VCC) and SRC2=2 (s[2:3]) stay lane-local; SRC2=252 (SRC_EXECZ) marks whole EXEC. + const CMP_S2: I = ("V_CMP_EQ_U32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", V + 1)]); + for (src2, cmp, pair) in [(106, CMP, 106), (2, CMP_S2, 2)] { + for (name, enc, extra) in [ + ("V_CNDMASK_B32", "ENC_VOP3", None), + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", Some(("SDST", 4))), + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", Some(("SDST", 4))), + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", Some(("SDST", 4))), + ] { + let mut f = vec![("VDST", 2), ("SRC0", V), ("SRC1", V + 1), ("SRC2", src2)]; + if let Some(s) = extra { f.push(s); } + let bytes: Vec = [rdna2::encode(cmp.0, cmp.1, cmp.2, None).unwrap(), rdna2::encode(name, enc, &f, None).unwrap(), rdna2::encode(ENDPGM.0, ENDPGM.1, ENDPGM.2, None).unwrap()].concat(); + let p = program(&bytes); + assert_eq!(uses(&p[1]), uses_fallback(&p[1])); + assert_eq!(uses(&p[1]).0 & range(pair, 2), 0, "{name} SRC2={src2} stays lane-local"); + assert!(!mask_needed(&whole_live_out(&p, false), 0, pair), "{name} SRC2={src2} needs no exchange"); + } + } + let execz = asm(&[("V_CNDMASK_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", V), ("SRC1", V + 1), ("SRC2", 252)]), ENDPGM]); + assert_eq!(uses(&execz[0]), uses_fallback(&execz[0])); + assert_eq!(uses(&execz[0]).0 & EXEC, EXEC, "V_CNDMASK_B32 SRC2=252 must read whole EXEC"); + } + /// Reference instruction-level solver matching the original implementation verbatim. fn whole_live_out_reference(insts: &[Decoded], end_reads_all: bool) -> Vec { let pcs: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); @@ -1133,6 +1225,16 @@ mod tests { }; assert_eq!(uses(&d), uses_fallback(&d), "{} ({}, {variant:?})", inst.name, enc.name); } + if matches!(enc.name, "ENC_VOP1" | "ENC_VOP2" | "ENC_VOPC") { + for bits in 0u32..8 { + let ext = (next_u32() & !((1 << 15) | (1 << 23) | (1 << 31))) + | ((bits & 1) << 15) + | (((bits >> 1) & 1) << 23) + | (((bits >> 2) & 1) << 31); + let d = Decoded { pc: 0, inst, ienc, enc, words: vec![next_u32(), ext], len: 8, literal: None, variant: Variant::Sdwa, far_target: None }; + assert_eq!(uses(&d), uses_fallback(&d), "{} ({}, Sdwa bits={bits})", inst.name, enc.name); + } + } } } } From 9ce9a435224d60cef3a2efa7531af27f01ba9107 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:08:37 +0100 Subject: [PATCH 194/258] d3d12x: clear stale unaligned-delta and depth-UAV twin state on buffer UAV rewrite --- crates/xcl/src/hle/d3d12x/real.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index b83e8ea755..2836c02009 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -3005,6 +3005,8 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u let v = (view as *const D3D12_UNORDERED_ACCESS_VIEW_DESC).read_unaligned(); if v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER { let Some(slot) = super::console_heap::slot(cpu) else { return }; + note_unaligned_delta_uav(slot.pc_uav as usize, false); + super::depth_uav::clear_uav_twin(slot.pc_uav as usize); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw, false); From 9ca4ffc72a53f560420703c7e7bdb382dd29c947 Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:30:10 -0500 Subject: [PATCH 195/258] D3D12.X: a list submitted again waits for its previous submit On the PC a command list must not be executed again before its previous execution is done (debug layer id 553). A console lets a title do it, and a retail title submits the same recording again about once a second in its world. XCL only noted it (note_resubmits). In a run on an NVIDIA RTX 5090 that had done it 128 times the device was removed with shader memory faults (nvlddmkm: "Graphics SM Warp Exception: MMU Fault", 0x887a0006) 2 min 40 s into the world, with DRED inside an ExecuteIndirect of a small compute program that reads nothing by an address of its own. A run of the same build with the debug layer on, which slows the submits enough that no list was ever submitted again while still on the GPU, ended after 442 s without a fault. That is one run each: the link is not proven. A submit now waits for the previous submits of its lists that the GPU has not finished, 2 s at most for all of them (XCL_RESUBMIT_WAIT_MS; 0: as before), polling XCL's own fence of that submit; past the limit the lists go as they are, logged. Tested: cargo test --release -p xcl --lib alloc_pool on the software adapter: 8 passed, 0 failed (new: a_resubmit_waits_for_the_previous_submit: the limit ends a wait for a submit that never finishes, no limit means no wait, a submit that finishes ends the wait). Not run on a title yet. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 115 ++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/real.rs | 6 +- 2 files changed, 120 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 0368c4898b..65c650f0b0 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -197,6 +197,78 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize found } +/// How long a submit waits for the previous submits of its lists (`XCL_RESUBMIT_WAIT_MS`, 2 000; +/// 0: not at all, as before). +fn resubmit_wait() -> std::time::Duration { + static MS: std::sync::OnceLock = std::sync::OnceLock::new(); + std::time::Duration::from_millis(*MS.get_or_init(|| std::env::var("XCL_RESUBMIT_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2000))) +} + +/// `lists` are about to be submitted: the ones whose previous submit the GPU has not finished +/// (`note_resubmits`) wait for it first, `limit` at most for all of them; then they go as they +/// are. On the PC a list must not be executed again before its previous execution is done (debug +/// layer id 553); a console lets a title do it, and a retail title did it about once a second in +/// its world – 128 times before its device was removed with shader memory faults, and not once in +/// a run that ended well. Returns (lists waited for, of them not done in time). +pub unsafe fn wait_for_previous_submits(lists: &[*mut c_void]) -> (usize, usize) { + wait_for_previous_submits_within(lists, resubmit_wait()) +} + +unsafe fn wait_for_previous_submits_within(lists: &[*mut c_void], limit: std::time::Duration) -> (usize, usize) { + if !enabled() || limit.is_zero() { + return (0, 0); + } + // (the fences are taken out: nothing is waited for with STATE held) + let pending: Vec<(ID3D12Fence, u64)> = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return (0, 0) }; + lists + .iter() + .filter_map(|&l| s.last_submit.get(&(l as usize))) + .filter(|l| super::real::fence_completed(&l.fence) < l.value) + .map(|l| (l.fence.clone(), l.value)) + .collect() + }; + if pending.is_empty() { + return (0, 0); + } + let start = std::time::Instant::now(); + let mut late = 0; + for (fence, value) in &pending { + // (XCL's own fence, read without the title's hook; a removed device reads as the largest + // value: no wait then. Such a submit is milliseconds from done: a short poll) + let mut polls = 0u32; + while super::real::fence_completed(fence) < *value { + if start.elapsed() >= limit { + late += 1; + break; + } + if polls < 64 { + std::thread::yield_now(); + } else { + std::thread::sleep(std::time::Duration::from_micros(200)); + } + polls += 1; + } + } + static WAITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = WAITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + if late > 0 { + crate::xlog_warn!( + "D3D12.X: {late} of {} previous submits of lists submitted again were not done after {} ms – they go as they are (#{n} such submits)", + pending.len(), + limit.as_millis() + ); + } else if n <= 8 || n.is_power_of_two() { + crate::xlog_info!( + "D3D12.X: a submit waited {:.1} ms for the previous submits of {} of its lists (#{n} such submits)", + start.elapsed().as_secs_f64() * 1e3, + pending.len() + ); + } + (pending.len(), late) +} + /// Whether the GPU has not finished the last submit of the PC list `list` (#1452: it must not be /// submitted again before that; `title_list` records the title's next recording elsewhere). pub fn in_flight(list: usize) -> bool { @@ -921,4 +993,47 @@ mod tests { assert!(resets.is_empty(), "already-reset aside backings should not be reset again"); } } + + /// A list whose previous submit still runs is waited for before it is submitted again: until + /// that submit is done, or the limit; a list with nothing running is not waited for. + #[test] + fn a_resubmit_waits_for_the_previous_submit() { + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + // a fence the GPU has not reached stands for a submit still running + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let mut ids = Box::new([0u8; 2]); + let (alloc, list) = (ids.as_mut_ptr() as usize, ids.as_mut_ptr() as usize + 1); + created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let recording = s.recordings[&list]; + s.last_submit.insert(list, LastSubmit { queue: 0x10, fence: fence.clone(), value: 1, recording }); + } + let lists = [list as *mut c_void]; + // it never finishes: the limit ends the wait, and says so + let t = std::time::Instant::now(); + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::from_millis(30)), (1, 1)); + assert!(t.elapsed() >= std::time::Duration::from_millis(30)); + // no limit: no wait + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::ZERO), (0, 0)); + // it finishes meanwhile: the wait ends then, far before the limit + let signal = fence.clone(); + let done = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(20)); + signal.Signal(1).unwrap(); + }); + let t = std::time::Instant::now(); + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::from_secs(20)), (1, 0)); + assert!(t.elapsed() < std::time::Duration::from_secs(10), "the wait ends when the submit is done"); + done.join().unwrap(); + // nothing runs now: nothing to wait for + assert_eq!(wait_for_previous_submits_within(&lists, std::time::Duration::from_secs(20)), (0, 0)); + forget_list(list); + forget(alloc); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 2836c02009..9b94f829b4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9164,7 +9164,11 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis } super::list_x::note_queue_for_lists(this as usize, &mapped); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { - let _ = super::alloc_pool::note_resubmits(this, chunk); + // a list still on the GPU from its previous submit: that one first (the PC does not take + // a list again before then) + if super::alloc_pool::note_resubmits(this, chunk) > 0 { + super::alloc_pool::wait_for_previous_submits(chunk); + } f(this, chunk.len() as u32, chunk.as_ptr()); super::list_x::copy_scratch_submitted(this, chunk); super::alloc_pool::executed(this, chunk); From 6e83f82817443046a1664ad4ebf857f192c2e0eb Mon Sep 17 00:00:00 2001 From: MacieGx Date: Wed, 25 Nov 2026 11:18:04 +0100 Subject: [PATCH 196/258] Recompiler: loads through s_getpc_b64 read the constant data after the program Console programs keep constant tables after s_endpgm and read them PC-relative (s_getpc_b64 + s_load_dword* / global_load_dword*). The translation gave s_getpc_b64 the program offset with high dword 0, so in a title these loads read memory window 0 at a low offset: zeros. 676 of the 26503 shader records of a retail title use this, among them all postfx_aces LUT bakes, whose 64-cube output LUT came out as one constant texel, so the presented image was flat. The data blocks after the program (xbox::Fssm::rodata, the new Options::rodata) now go with the translation: - HLSL: emit.rs embeds them as `static const uint xcl_rodata[]`, and s_load and FLAT / GLOBAL dword loads go through xcl_gload*, which take the dwords at a code address inside a block from the table. With several memory windows s_getpc_b64's high dword is CODE_ADDRESS_HI (0xC0DE, above any user-space address), so a code address is told from the title's memory at the same low dword; with one window it is the program's offset as before. - Direct DXIL: the same, as an internal constant array of the module (Lw::rodata_loads in lower_window.rs); with windows s_buffer_load reads it too. kernel::translate_entry_rodata carries the data. The per-lane form (XCL_PER_LANE) has no table and leaves such programs to the per-instruction form. TRANSLATOR_VERSION 9 -> 10. - pso.rs passes the data on the compute, VS / PS and mesh paths (HLSL and direct), and `xcl shaders` (precompile, direct sweep) does too. Not covered: byte / short global loads, MUBUF buffer_load, the legacy GS path and the per-lane form still read memory at such addresses. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 980eb78bd71077d43056e1d78387d5cce21d1989) --- crates/xcl/src/gpu/dxil/core_tests.rs | 94 ++++++++++++++++++++++++- crates/xcl/src/gpu/dxil/coverage.rs | 17 ++--- crates/xcl/src/gpu/dxil/kernel.rs | 35 ++++++++- crates/xcl/src/gpu/dxil/lower.rs | 10 ++- crates/xcl/src/gpu/dxil/lower_mem.rs | 14 +++- crates/xcl/src/gpu/dxil/lower_window.rs | 70 ++++++++++++++++++ crates/xcl/src/gpu/recomp/emit.rs | 47 +++++++++++-- crates/xcl/src/gpu/recomp/mod.rs | 13 +++- crates/xcl/src/gpu/recomp/pso.rs | 48 +++++++++---- crates/xcl/src/gpu/recomp/tests.rs | 82 +++++++++++++++++++++ crates/xcl/src/gpu/xbox.rs | 13 ++++ crates/xcl/src/shaders.rs | 8 +-- 12 files changed, 412 insertions(+), 39 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 9f7d5f220a..164a8e97dd 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -561,7 +561,7 @@ fn ps_get_lod_with_a_static_sampler() { let k = super::kernel::translate_pixel(&code, ko, &psi).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); assert_eq!(k.static_samplers, vec![(linear, false)], "one static sampler, shared by get_lod and sample"); if crate::gpu::recomp::dxc::location().is_ok() { - super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); + super::coverage::translate_mode(&code, &Mode::Pixel(psi), ko, true, &[]).unwrap_or_else(|e| panic!("{}", &e[..e.len().min(800)])); } } @@ -1110,3 +1110,95 @@ fn scratch_reads_addr_only_in_the_sv_form() { assert!(kernel(0x7D, 2) != kernel(0x7D, 3), "SV (SADDR 0x7d) addresses VADDR + offset"); assert!(kernel(0x7F, 2) != kernel(0x7D, 2), "ST is not the SV form"); } + +/// Constant data after the program (`kernel::translate_entry_rodata`), as the HLSL kernel's +/// `gpu_loads_read_the_constant_data_after_the_program`: `s_getpc_b64` plus the compiler's +/// offset is its address, and `s_load` / `global_load` (with windows `s_buffer_load` too) read +/// it from the module's table – with one window, two windows (switch) and heap windows, where +/// window 0 holds other bytes at the table's offset. Any other address still reads the memory. +#[test] +fn gpu_direct_loads_read_the_constant_data_after_the_program() { + use super::kernel::{translate_entry_rodata, Entry}; + use crate::gpu::recomp::{runner, HEAP_WINDOWS}; + let body = |table: u32| { + prog(&[ + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)], None), // s[0:1] = 4 + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 255)], Some(table.wrapping_sub(4))), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)], None), + ("GLOBAL_LOAD_DWORDX3", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 10), ("SADDR", 0), ("OFFSET", 0)], None), + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 0), ("OFFSET", 4), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)], None), + // memory, not the data: v[12:13] and s[2:3] + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 8), ("ADDR", 12), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 28), ("SBASE", 1), ("OFFSET", 0), ("SOFFSET", 125)], None), + // the V# s[4:7] + ("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 30), ("SBASE", 2), ("OFFSET", 4), ("SOFFSET", 125)], None), + ]) + }; + // as in retail data: program, guard s_endpgm, block (u32 N, N dwords, s_endpgm) + let block = body(0).len() as u32 + 4; + let code = body(block + 4); + let table: Vec = (0..8).map(|i| 0x7AB1_E000 + i).collect(); + let mut data = vec![table.len() as u32]; + data.extend(&table); + data.push(0xBF81_0000); + let rodata = vec![(block, data)]; + let split = runner::split_wave64(); + let direct = |windows: u32, rodata: &[(u32, Vec)]| { + let o = KernelOptions { wave64: true, split, mem_windows: windows, sampler_base: 0 }; + translate_entry_rodata(&code, o, Entry::Kernel, rodata).unwrap_or_else(|e| panic!("windows {windows:#x}: {}", &e[..e.len().min(800)])) + }; + // (translations are validated in test builds) + let one = direct(1, &rodata).dxil; + assert_eq!(direct(1, &[]).dxil, translate(&code, KernelOptions { wave64: true, split, mem_windows: 1, sampler_base: 0 }).unwrap(), "no data, no table"); + assert_ne!(one, direct(1, &[]).dxil); + match (runner::adapter(), runner::wave64_programs_supported()) { + (Ok(_), Ok(true)) => {} + (a, w) => return runner::skip_test(if a.is_err() || w.is_err() { "no GPU" } else { "no wave64" }), + } + let check = |r: &runner::KernelResult, buffer: [u32; 2], what: &str| { + assert_eq!(r.sgpr[20], table[1], "{what}: s_load_dword of the table"); + assert_eq!(r.sgpr[24..28], table[2..6], "{what}: s_load_dwordx4 of the table"); + assert_eq!(r.sgpr[28..30], [4242, 4343], "{what}: s_load from memory"); + assert_eq!(r.sgpr[30..32], buffer, "{what}: s_buffer_load"); + for l in 0..64usize { + let k = l % 6; + assert_eq!(r.vgpr[l][5..8], table[k..k + 3], "{what}, lane {l}: three dwords of the table from {k}"); + assert_eq!(r.vgpr[l][8], 7000 + l as u32, "{what}, lane {l}: memory outside the data"); + } + }; + // one window: nothing of the code is in the memory (and a V# is always memory) + let mut st = runner::KernelState::default(); + st.sgpr[2] = 0x900; + st.sgpr[4..7].copy_from_slice(&[0x900, 0, 64]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[10] = 4 * (l as u32 % 6); + r[12] = 0x800 + 4 * l as u32; + } + let mut mem = vec![0u32; 1024]; + mem[0x240..0x243].copy_from_slice(&[4242, 4343, 4444]); + for l in 0..64 { + mem[0x200 + l] = 7000 + l as u32; + } + check(&runner::run(&one, &st, &mem).unwrap(), [4343, 4444], "one window"); + // several windows: a code address is in none of them, and window 0 holds other bytes at + // the table's offset; the V# is on the table + let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for k in 0..16u64 { + *word(w0 + block as u64 + 4 * k) = 0xBAD0_0000 + k as u32; + } + *word(w1 + 0x900) = 4242; + *word(w1 + 0x904) = 4343; + st.sgpr[2..4].copy_from_slice(&[(w1 + 0x900) as u32, (w1 >> 32) as u32]); + st.sgpr[4..7].copy_from_slice(&[block + 4, crate::gpu::recomp::CODE_ADDRESS_HI, 64]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + *word(w1 + 0x800 + 4 * l as u64) = 7000 + l as u32; + r[12] = (w1 + 0x800 + 4 * l as u64) as u32; + r[13] = (w1 >> 32) as u32; + } + for (windows, what) in [(2, "two windows"), (2 | HEAP_WINDOWS, "heap windows")] { + check(&runner::run_in_arena(&direct(windows, &rodata).dxil, &st, &arena).unwrap(), [table[1], table[2]], what); + } +} diff --git a/crates/xcl/src/gpu/dxil/coverage.rs b/crates/xcl/src/gpu/dxil/coverage.rs index 4ac26cb707..f9a463308d 100644 --- a/crates/xcl/src/gpu/dxil/coverage.rs +++ b/crates/xcl/src/gpu/dxil/coverage.rs @@ -246,14 +246,15 @@ pub fn percentiles(v: &[u64]) -> (u64, u64, u64) { /// One program through the direct translator for `mode`. Panics (outside the translator's /// own thread) come back as `"panic: …"`; `validate` runs DXC's validator on the result -/// (the translator itself only validates in debug / test builds). -pub fn translate_mode(code: &[u8], mode: &Mode, o: KernelOptions, validate: bool) -> Result, String> { +/// (the translator itself only validates in debug / test builds). `rodata`: the constant data +/// after the program (`xbox::Fssm::rodata`). +pub fn translate_mode(code: &[u8], mode: &Mode, o: KernelOptions, validate: bool, rodata: &[(u32, Vec)]) -> Result, String> { let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| match mode { - Mode::Kernel => kernel::translate_full(code, o), - Mode::Compute(cs) => kernel::translate_compute(code, o, cs), - Mode::Vertex(vs) => kernel::translate_vertex(code, KernelOptions { split: false, ..o }, vs), - Mode::Pixel(ps) => kernel::translate_pixel(code, KernelOptions { split: false, ..o }, ps), - Mode::Mesh(ms) => kernel::translate_mesh(code, o, ms), + Mode::Kernel => kernel::translate_entry_rodata(code, o, kernel::Entry::Kernel, rodata), + Mode::Compute(cs) => kernel::translate_entry_rodata(code, o, kernel::Entry::Compute(cs.clone()), rodata), + Mode::Vertex(vs) => kernel::translate_entry_rodata(code, KernelOptions { split: false, ..o }, kernel::Entry::Vertex(vs.clone()), rodata), + Mode::Pixel(ps) => kernel::translate_entry_rodata(code, KernelOptions { split: false, ..o }, kernel::Entry::Pixel(ps.clone()), rodata), + Mode::Mesh(ms) => kernel::translate_entry_rodata(code, o, kernel::Entry::Mesh(ms.clone()), rodata), Mode::Geometry(g) => kernel::translate_geometry(code, o, g), })); let k = match r { @@ -405,7 +406,7 @@ mod tests { let mut r = Report::default(); for (name, code, mode) in [("ok", ok.clone(), Mode::Kernel), ("gs", ok, Mode::Geometry(Default::default()))] { let t0 = std::time::Instant::now(); - let res = translate_mode(&code, &mode, o, false).map(|d| d.len()); + let res = translate_mode(&code, &mode, o, false, &[]).map(|d| d.len()); r.add(name, &Sample { stage: stage_name(&mode), result: res, time: t0.elapsed(), hlsl_size: None }); } assert_eq!(r.stages["kernel"].translated, 1, "{}", r.text(5)); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 98c834e5cd..a7f8bbaabd 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 = 10; +pub const TRANSLATOR_VERSION: u32 = 11; /// `XCL_DIRECT_DXIL=1`: console compute shaders (and the kernel tests) go through this /// translator, with the HLSL path as the fallback for what it cannot translate yet. @@ -139,7 +139,12 @@ pub enum Entry { /// A compute-mode program (the CS ABI of `cs`). pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result { - translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None) + translate_compute_rodata(code, o, cs, &[]) +} + +/// `translate_compute` with the constant data after the program (`translate_entry_rodata`). +pub fn translate_compute_rodata(code: &[u8], o: KernelOptions, cs: &CsInterface, rodata: &[(u32, Vec)]) -> Result { + translate_entry_with(code, o, Entry::Compute(cs.clone()), compact_mode(), None, rodata.to_vec()) } fn translate_entry( @@ -148,6 +153,26 @@ fn translate_entry( entry: Entry, compact: Option, nest: Option, +) -> Result { + translate_entry_with(code, o, entry, compact, nest, Vec::new()) +} + +/// A program at `entry` with the constant data the console compiler put after it in the code +/// region (`xbox::Fssm::rodata`, the recompiler's `Options::rodata`): `s_getpc_b64` plus the +/// compiler's offset is its address, and dword loads at such an address read the table the +/// module carries (`Lw::rodata_loads`). +pub fn translate_entry_rodata(code: &[u8], o: KernelOptions, entry: Entry, rodata: &[(u32, Vec)]) -> Result { + let compact = if matches!(entry, Entry::Kernel | Entry::Compute(_)) { compact_mode() } else { None }; + translate_entry_with(code, o, entry, compact, None, rodata.to_vec()) +} + +fn translate_entry_with( + code: &[u8], + o: KernelOptions, + entry: Entry, + compact: Option, + nest: Option, + rodata: Vec<(u32, Vec)>, ) -> Result { // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs @@ -155,7 +180,7 @@ fn translate_entry( std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest)) + .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, rodata)) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -185,6 +210,7 @@ fn translate_on_this_thread( entry: Entry, compact: Option, nest: Option, + rodata: Vec<(u32, Vec)>, ) -> Result { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), @@ -201,6 +227,7 @@ fn translate_on_this_thread( let split = o.wave64 && o.split && !gfx; let leaders: BTreeSet = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let mut lw = Lw::new(&cfg.insts, &leaders, o, &entry); + lw.rodata = rodata; let uses_lds = lw.lds.is_some(); let res = lw.res; let io = lw.init.io.expect("the I/O buffer"); @@ -521,6 +548,8 @@ impl Lw { heap_flat: heap_mem.is_some() && o.mem_windows & crate::gpu::recomp::HEAP_FLAT != 0, res, fmt_table: None, + rodata: Vec::new(), + rodata_table: None, fmt_desc_cache: HashMap::new(), fmt_comp1_cache: HashMap::new(), reload: None, diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index c2424a16ab..34a4eb021a 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -194,6 +194,11 @@ pub struct Lw { pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, + /// constant data after the program in the code region (`recomp::Options::rodata`: + /// (address from the program's start, dwords)) and its table, created on first use + /// (`rodata_loads`) + pub rodata: Vec<(u32, Vec)>, + pub rodata_table: Option, /// cached decoded format descriptors hoisted to `d3`'s defining block pub fmt_desc_cache: HashMap<(Value, Option), super::lower_mem::FmtDesc>, /// cached single-component format decode parameters hoisted to `d3`'s defining block @@ -1328,6 +1333,8 @@ impl Lw { return err(d, "indirect branch"); } if name == "s_getpc_b64" { + // the code region is addressed from 0 – with constant data after the program and + // several memory windows, above them all (`rodata_loads`), as the HLSL kernel let lo = match self.compact_blk_pc { Some((blk_pc, rep_blk_pc)) => { let rel = (d.pc + d.len as u64).wrapping_sub(rep_blk_pc) as u32; @@ -1335,7 +1342,8 @@ impl Lw { } None => self.c((d.pc + d.len as u64) as u32), }; - let hi = self.c(0); + let code_hi = if self.rodata.is_empty() || !self.windowed() { 0 } else { crate::gpu::recomp::CODE_ADDRESS_HI }; + let hi = self.c(code_hi); self.write64(&dst, lo, hi); return Ok(()); } diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index 950d327a75..60eaab5916 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -1189,6 +1189,9 @@ impl Lw { let base = self.add(d0, off); let base_aligned = self.andc(base, !3); let raw = self.mem_ld_chunks(base_aligned, count); + // (a V# on the constant data in the code: only with windows, where its high + // dword tells it from the title's memory) + let raw = if self.windowed() { self.rodata_loads(base_aligned, raw) } else { raw }; let z = self.c(0); (0..count) .map(|i| { @@ -1215,7 +1218,9 @@ impl Lw { let a = self.add(b, k); let a = self.add(a, soff); let base_aligned = self.andc(a, !3); - self.mem_ld_chunks(base_aligned, count) + let raw = self.mem_ld_chunks(base_aligned, count); + // (constant data in the code) + self.rodata_loads(base_aligned, raw) }; let coherent = ["GLC", "DLC"].iter().any(|f| rdna2::field_value(d.enc, &d.words, f) == Some(1)); if self.split && coherent { @@ -2066,6 +2071,13 @@ impl Lw { } else { let vd = Self::fv(d, "VDST"); let loaded = self.mem_ld_n(Some(act), a, count as u32); + // (constant data in the code) + let loaded = if self.rodata.is_empty() { + loaded + } else { + let a = self.andc(a, !3); + self.rodata_loads(a, loaded) + }; for i in 0..count { self.write32(&Dst::V(vd + i), loaded[i as usize]); } diff --git a/crates/xcl/src/gpu/dxil/lower_window.rs b/crates/xcl/src/gpu/dxil/lower_window.rs index 1f41e5817d..4ab2f70b16 100644 --- a/crates/xcl/src/gpu/dxil/lower_window.rs +++ b/crates/xcl/src/gpu/dxil/lower_window.rs @@ -151,6 +151,76 @@ impl Lw { self.wr(VAR_WIN, w); } + /// `Lw::rodata` (the HLSL kernel's `xcl_gload`): the dwords `vals` a load read from memory + /// at `a`, `a + 4`.. (`a` dword-aligned), with those at a code address inside one of the + /// program's constant data blocks replaced by the block's dword. A code address has the + /// high dword `CODE_ADDRESS_HI` with several windows (`s_getpc_b64`; the window of the + /// access was just selected: `VAR_WIN`) and is the program's offset with one. `vals` as + /// they are without data. + pub(crate) fn rodata_loads(&mut self, a: Value, vals: Vec) -> Vec { + let total: usize = self.rodata.iter().map(|b| b.1.len()).sum(); + if total == 0 { + return vals; + } + let table = match self.rodata_table { + Some(g) => g, + None => { + let words: Vec = self.rodata.iter().flat_map(|b| b.1.iter().copied()).collect(); + let words: Vec = words.into_iter().map(|w| self.s.m.i32c(w)).collect(); + let i32 = self.s.m.i32(); + let at = self.s.m.array(total as u64, i32); + let init = self.s.m.aggregate(at, &words); + let g = self.s.m.global("xcl_rodata", at, 0, Some(init), true, 4); + self.rodata_table = Some(g); + g + } + }; + let code = if self.windowed() { + let w = self.rd(VAR_WIN); + let base = self.uma_base(); + let hi = self.c(crate::gpu::recomp::CODE_ADDRESS_HI); + let cw = self.sub(hi, base); + Some(self.cmp(Pred::Eq, w, cw)) + } else { + None + }; + // per block: `a`'s offset in it, its dword's index in the table, the block's bytes + let mut first = 0u32; + let mut blocks = Vec::new(); + for (at, len) in self.rodata.iter().map(|b| (b.0, b.1.len() as u32)).filter(|b| b.1 > 0).collect::>() { + let k = self.c(at); + let off = self.sub(a, k); + let q = self.lshrc(off, 2); + let q = self.addc(q, first); + blocks.push((off, q, 4 * len)); + first += len; + } + let z = self.c(0); + vals.into_iter() + .enumerate() + .map(|(i, v)| { + let i = i as u32; + let (mut inside, mut idx) = (None, z); + for &(off, q, bytes) in &blocks { + let (o, q) = if i == 0 { (off, q) } else { (self.addc(off, 4 * i), self.addc(q, i)) }; + let c = self.cmpc(Pred::ULt, o, bytes); + idx = self.sel(c, q, idx); + inside = Some(match inside { + Some(x) => self.or(x, c), + None => c, + }); + } + let mut inside = inside.expect("a block"); + if let Some(cw) = code { + inside = self.and(inside, cw); + } + let p = self.s.m.gep(table, &[z, idx]); + let t = self.s.m.load(p, 4); + self.sel(inside, t, v) + }) + .collect() + } + /// The window of a buffer access: V# base `d1[15:0]:d0` plus `adds` (the stride bits /// `d1[29:16]` are not part of the address). pub fn buffer_window(&mut self, d0: Value, d1: Value, adds: &[Ea], write: bool) { diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index f80146e78e..e2e184eacb 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -1628,9 +1628,11 @@ impl Em { return Err("indirect branch"); } if name == "s_getpc_b64" { - // the code region is addressed from 0 in this model + // the code region is addressed from 0 in this model – with constant data after the + // program and several memory windows, above them all (`rodata_loader`) let pc = d.pc + d.len as u64; - self.write64(&dst, &hex(pc as u32), "0u"); + let hi = if self.opt.rodata.is_empty() || self.opt.mem_windows <= 1 { "0u".to_string() } else { hex(super::CODE_ADDRESS_HI) }; + self.write64(&dst, &hex(pc as u32), &hi); return Ok(()); } if matches!(name, "s_bitset0_b64" | "s_bitset1_b64") { @@ -2002,18 +2004,20 @@ impl Em { } else { self.line(&format!("uint {t}_a = ({b} + {} + {soff}) & ~3u;", hex(imm))); } + // (with constant data in the code, which `s_load` reads too: `rodata_loader`) + let load = if self.opt.rodata.is_empty() { "mem.Load" } else { "xcl_gload" }; match count { 1 => { - self.line(&format!("uint {t}_0 = mem.Load({t}_a);")); + self.line(&format!("uint {t}_0 = {load}({t}_a);")); vals.push(format!("{t}_0")); } 2 => { - self.line(&format!("uint2 {t}_g0 = mem.Load2({t}_a);")); + self.line(&format!("uint2 {t}_g0 = {load}2({t}_a);")); vals.extend([format!("{t}_g0.x"), format!("{t}_g0.y")]); } _ => { for g in 0..count / 4 { - self.line(&format!("uint4 {t}_g{g} = mem.Load4({t}_a + {}u);", 16 * g)); + self.line(&format!("uint4 {t}_g{g} = {load}4({t}_a + {}u);", 16 * g)); vals.extend(["x", "y", "z", "w"].iter().map(|c| format!("{t}_g{g}.{c}"))); } } @@ -4484,7 +4488,9 @@ impl Em { st.push(format!("mem.Store(({t}_a + {}u) & ~3u, {v});", 4 * i)); } else { let v = self.vreg(f("VDST") + i); - st.push(format!("{v} = mem.Load(({t}_a + {}u) & ~3u);", 4 * i)); + // (with constant data in the code: `rodata_loader`) + let load = if self.opt.rodata.is_empty() { "mem.Load" } else { "xcl_gload" }; + st.push(format!("{v} = {load}(({t}_a + {}u) & ~3u);", 4 * i)); } } self.line(&format!("if ({act}) {{ {} }}", st.join(" "))); @@ -4912,6 +4918,7 @@ impl Em { } else { h.push_str(LOADX4_ONE_WINDOW); } + h.push_str(&rodata_loader(&self.opt.rodata, windows > 1)); for (i, (_, cmp)) in self.static_used.iter().enumerate() { let k = self.opt.static_sampler_base as usize + i; let ty = if *cmp { "SamplerComparisonState" } else { "SamplerState" }; @@ -5816,6 +5823,34 @@ fn float_minmax_mem(min: bool, x2: bool, a: &str, v: &str, old: &str, t: &str) - /// Placeholder where the memory window accessors go (after the `mem` declarations). const MEM_ACCESSORS_HERE: &str = "//XCL_MEM_ACCESSORS\n"; +/// `Options::rodata`: the program's constant data as an array of the shader, and the dword +/// loads of `s_load` and FLAT / GLOBAL instructions that read it – a code address +/// (`s_getpc_b64` plus the compiler's offset: `CODE_ADDRESS_HI` with several memory windows, +/// the program's offset with one) inside one of the blocks gives the block's dword, any other +/// address the memory's. Nothing without data. +fn rodata_loader(rodata: &[(u32, Vec)], windows: bool) -> String { + let total: usize = rodata.iter().map(|b| b.1.len()).sum(); + if total == 0 { + return String::new(); + } + let words: Vec = rodata.iter().flat_map(|b| b.1.iter()).map(|w| format!("0x{w:08X}u")).collect(); + let mut s = format!("static const uint xcl_rodata[{total}] = {{ {} }};\nuint xcl_gload(uint a) {{\n", words.join(", ")); + let w0 = if windows { format!("xcl_w == {:#X}u - xcl_uma_base && ", super::CODE_ADDRESS_HI) } else { String::new() }; + let mut first = 0usize; + let mut inside = Vec::new(); + for (at, block) in rodata.iter().filter(|b| !b.1.is_empty()) { + let _ = writeln!(s, " [branch] if ({w0}a - {at}u < {}u) {{ return xcl_rodata[{first}u + ((a - {at}u) >> 2)]; }}", 4 * block.len()); + inside.push(format!("a - {at}u < {}u", 4 * block.len())); + first += block.len(); + } + s.push_str(" return mem.Load(a);\n}\n"); + // several dwords from `a` (`s_load_dwordx2` and up): one look at the address for all of them + let inside = format!("{w0}({})", inside.join(" || ")); + let _ = writeln!(s, "uint2 xcl_gload2(uint a) {{ [branch] if ({inside}) {{ return uint2(xcl_gload(a), xcl_gload(a + 4u)); }} return mem.Load2(a); }}"); + let _ = writeln!(s, "uint4 xcl_gload4(uint a) {{ [branch] if ({inside}) {{ return uint4(xcl_gload(a), xcl_gload(a + 4u), xcl_gload(a + 8u), xcl_gload(a + 12u)); }} return mem.Load4(a); }}"); + s +} + /// Four dwords at four addresses (scalar buffer loads with their bounds checks); with several /// windows `mem_accessors` defines it, with one switch for all four. const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }\n"; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index fee9d16dab..26a1b74a3b 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -227,6 +227,11 @@ pub const IO_UMA_BASE_HI: usize = 112; pub const IO_GROUP_LIMIT: usize = 113; /// Groups a folded dispatch has in X. pub const FOLD_X: u32 = 65_535; +/// High dword `s_getpc_b64` gives a program that has constant data in its code region +/// (`Options::rodata`) and several memory windows: its code addresses are then above every +/// address a title can have (user space ends at 0x7FFF_FFFF_FFFF), so a load from the data is +/// told from a load of the title's memory at the same low dword (descriptor tables in window 0). +pub const CODE_ADDRESS_HI: u32 = 0xC0DE; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) @@ -656,11 +661,17 @@ pub struct Options { /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, + /// constant data the console compiler put in the code region after the program + /// (`xbox::Fssm::rodata`): (address from the program's start, dwords). The program finds + /// it with `s_getpc_b64` and reads it with `s_load` / `global_load`; the title's memory does + /// not hold the code, so a load at a code address in one of these ranges takes the dwords + /// from the shader (`CODE_ADDRESS_HI`) + pub rodata: Vec<(u32, Vec)>, } impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true, rodata: Vec::new() } } } diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 72bf5f3058..2eff3853b9 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -963,6 +963,21 @@ fn direct_fallback(stage: &str, err: &str) { crate::xlog_info!("[SHADER] direct DXIL fallback stage={stage} reason=\"{reason}\" detail=\"{}\" – HLSL path", err.lines().next().unwrap_or("")); } +/// Whether the program takes an address in its code region for something else than a far jump +/// (`rdna2::resolve_far_jumps`): an `s_getpc_b64` the compiler emits to reach the constant +/// data after the program. +fn takes_code_address(code: &[u8]) -> bool { + let mut insts = Vec::new(); + let mut off = 0usize; + while off + 4 <= code.len() { + let Ok(d) = crate::gpu::rdna2::decode(&code[off..], off as u64) else { return false }; + off += d.len; + insts.push(d); + } + crate::gpu::rdna2::resolve_far_jumps(&mut insts); + (0..insts.len()).any(|i| insts[i].inst.name == "S_GETPC_B64" && !insts.get(i + 3).is_some_and(|s| s.far_target.is_some())) +} + /// A console compute shader through the direct DXIL translator (`gpu::dxil::kernel`). /// FSPX (driver) containers are left to the HLSL path. fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bool) -> Result { @@ -971,10 +986,13 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; + // the constant data the program reads from its own code region (`Options::rodata`) + let rodata = f.rodata(p); let wave64 = super::fssm_wave64(f, code); let o = crate::gpu::dxil::kernel::KernelOptions { wave64, split: wave64 && split_wave64, mem_windows: windows, sampler_base }; // `XCL_PER_LANE=1`: the per-lane form first, #1426's per-instruction form where it refuses - if super::lower_dxil::enabled() { + // (and for a program that reads constant data in its code: the per-lane form has no table) + if super::lower_dxil::enabled() && !(!rodata.is_empty() && takes_code_address(code)) { match super::lower_dxil::compute_with(code, &cs, o) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("CS per-lane"); @@ -987,7 +1005,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } } } - let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?; + let k = crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, &rodata)?; dump_direct(blob, &k.dxil); Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) } @@ -1018,11 +1036,12 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; let o = crate::gpu::dxil::kernel::KernelOptions { wave64: super::fssm_wave64(f, code), split: false, mem_windows: windows, sampler_base }; - let k = match (&mode, stage) { - (Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::translate_vertex(code, o, vs)?, - (Mode::Pixel(ps), Stage::Pixel) => crate::gpu::dxil::kernel::translate_pixel(code, o, ps)?, + let entry = match (&mode, stage) { + (Mode::Vertex(vs), Stage::Vertex) => crate::gpu::dxil::kernel::Entry::Vertex(vs.clone()), + (Mode::Pixel(ps), Stage::Pixel) => crate::gpu::dxil::kernel::Entry::Pixel(ps.clone()), _ => return Err("the shader stage does not match its slot in the PSO".into()), }; + let k = crate::gpu::dxil::kernel::translate_entry_rodata(code, o, entry, &f.rodata(p))?; dump_direct(blob, &k.dxil); Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }) } @@ -1062,7 +1081,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, rodata: f.rodata(p), ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1105,6 +1124,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option fn compile_console_mesh( blob: &[u8], code: &[u8], + rodata: Vec<(u32, Vec)>, ms: &super::MsInterface, wave64: bool, windows: u32, @@ -1121,7 +1141,7 @@ fn compile_console_mesh( mem_windows: windows, sampler_base: 0, }; - match crate::gpu::dxil::kernel::translate_mesh(code, o, ms) { + match crate::gpu::dxil::kernel::translate_entry_rodata(code, o, crate::gpu::dxil::kernel::Entry::Mesh(ms.clone()), &rodata) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); @@ -1130,7 +1150,7 @@ fn compile_console_mesh( Err(e) => direct_fallback("MS", &e), } } - let t = super::translate_mesh(code, ms.clone(), wave64, split_wave64, windows)?; + let t = translate(code, &Options { mode: Mode::Mesh(ms.clone()), wave64, split_wave64, mem_windows: windows, rodata, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1146,7 +1166,7 @@ fn console_mesh_with( windows: u32, cache_dir: &std::path::Path, cache: &Mutex, - compile: impl FnOnce(&[u8], &super::MsInterface, bool) -> Result, + compile: impl FnOnce(&[u8], Vec<(u32, Vec)>, &super::MsInterface, bool) -> Result, ) -> Result { let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 7)).ok_or("no NGG hardware variant")?; @@ -1157,7 +1177,7 @@ fn console_mesh_with( let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::fssm_wave64(f, code); let split = wave64 && split_wave64; - let compile_one = || compile(code, ms, wave64); + let compile_one = || compile(code, f.rodata(p), ms, wave64); // Cache the mesh compute pass in RAM (`ShaderCache` + in-flight coalescing) and on disk // (`translated/v2`, namespaced by backend) across all `(MS, PS)` pipelines that share it. let cs = if cache_allowed(Stage::Mesh, |name| std::env::var_os(name).is_some()) { @@ -1182,8 +1202,8 @@ fn console_mesh_with( pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { let windows = mem_windows(); let dir = dxc::cache_dir(); - console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, ms, wave64| { - compile_console_mesh(blob, code, ms, wave64, windows, split_wave64) + console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, rodata, ms, wave64| { + compile_console_mesh(blob, code, rodata, ms, wave64, windows, split_wave64) }) } @@ -2259,9 +2279,9 @@ mod shader_cache_tests { let compiles = AtomicUsize::new(0); let run = |c: &Mutex| { - console_mesh_with(&blob, None, false, 1, &dir, c, |code, ms, wave64| { + console_mesh_with(&blob, None, false, 1, &dir, c, |code, rodata, ms, wave64| { compiles.fetch_add(1, Ordering::SeqCst); - compile_console_mesh(&blob, code, ms, wave64, 1, false) + compile_console_mesh(&blob, code, rodata, ms, wave64, 1, false) }) }; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index b0ef053ff8..c069fd0971 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -4783,6 +4783,88 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() { } } +/// Constant data after the program (`Options::rodata`): `s_getpc_b64` plus the compiler's +/// offset is its address, and `s_load` / `global_load` read it from the shader. The memory +/// does not hold the code (a retail tone-map LUT bake read zeros for its spline coefficients +/// there and wrote one colour to every texel); any other address still reads the memory. +#[test] +fn gpu_loads_read_the_constant_data_after_the_program() { + let body = |table: u32| { + prog(&[ + ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)], None), // s[0:1] = 4 + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 255)], Some(table.wrapping_sub(4))), + ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)], None), + ("GLOBAL_LOAD_DWORDX3", "ENC_FLAT_GLBL", &[("VDST", 5), ("ADDR", 10), ("SADDR", 0), ("OFFSET", 0)], None), + ("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 20), ("SBASE", 0), ("OFFSET", 4), ("SOFFSET", 125)], None), + ("S_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 0), ("OFFSET", 8), ("SOFFSET", 125)], None), + // memory, not the data: v[12:13] and s[2:3] + ("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 8), ("ADDR", 12), ("SADDR", 0x7D), ("OFFSET", 0)], None), + ("S_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 28), ("SBASE", 1), ("OFFSET", 0), ("SOFFSET", 125)], None), + ]) + }; + // as in retail data: program, guard s_endpgm, block (u32 N, N dwords, s_endpgm) + let block = body(0).len() as u32 + 4; + let code = body(block + 4); + let table: Vec = (0..8).map(|i| 0x7AB1_E000 + i).collect(); + let mut data = vec![table.len() as u32]; + data.extend(&table); + data.push(0xBF81_0000); + let rodata = vec![(block, data)]; + assert!(!translate(&code, &Options::default()).unwrap().hlsl.contains("xcl_gload"), "no data, no loader"); + if !gpu_ready() { + return; + } + let check = |r: &runner::KernelResult, what: &str| { + assert_eq!(r.sgpr[20], table[1], "{what}: s_load_dword of the table"); + assert_eq!(r.sgpr[24..28], table[2..6], "{what}: s_load_dwordx4 of the table"); + assert_eq!(r.sgpr[28..30], [4242, 4343], "{what}: s_load from memory"); + for l in 0..64usize { + let k = l % 6; + assert_eq!(r.vgpr[l][5..8], table[k..k + 3], "{what}, lane {l}: three dwords of the table from {k}"); + assert_eq!(r.vgpr[l][8], 7000 + l as u32, "{what}, lane {l}: memory outside the data"); + } + }; + // one window: nothing of the code is in the memory + let mut st = KernelState::default(); + st.sgpr[2] = 0x900; + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[10] = 4 * (l as u32 % 6); + r[12] = 0x800 + 4 * l as u32; + } + let mut mem = vec![0u32; 1024]; + mem[0x240..0x242].copy_from_slice(&[4242, 4343]); + for l in 0..64 { + mem[0x200 + l] = 7000 + l as u32; + } + let t = translate(&code, &Options { rodata: rodata.clone(), ..runner::options(Mode::Kernel) }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + check(&runner::run(&dxil, &st, &mem).unwrap(), "one window"); + // several windows: a code address is in none of them, and window 0 holds other bytes at + // the table's offset + let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap(); + let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64); + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for k in 0..16u64 { + *word(w0 + block as u64 + 4 * k) = 0xBAD0_0000 + k as u32; + } + *word(w1 + 0x900) = 4242; + *word(w1 + 0x904) = 4343; + st.sgpr[2..4].copy_from_slice(&[(w1 + 0x900) as u32, (w1 >> 32) as u32]); + for (l, r) in st.vgpr.iter_mut().enumerate() { + *word(w1 + 0x800 + 4 * l as u64) = 7000 + l as u32; + r[12] = (w1 + 0x800 + 4 * l as u64) as u32; + r[13] = (w1 >> 32) as u32; + } + for heap in [false, true] { + let t = translate(&code, &on_gpu(Options { mem_windows: 2, heap_windows: heap, rodata: rodata.clone(), ..Default::default() })).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported); + assert!(t.hlsl.contains(&format!("if (xcl_w == 0xC0DEu - xcl_uma_base && a - {block}u < 40u)")), "the data is at code addresses only:\n{}", t.hlsl); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap(); + check(&runner::run_in_arena(&dxil, &st, &arena).unwrap(), if heap { "heap windows" } else { "two windows" }); + } +} + /// Experiment: does OpenExistingHeapFromAddress accept a reservation with only part committed? #[test] #[ignore] diff --git a/crates/xcl/src/gpu/xbox.rs b/crates/xcl/src/gpu/xbox.rs index d24ef4aca0..28a1abf0da 100644 --- a/crates/xcl/src/gpu/xbox.rs +++ b/crates/xcl/src/gpu/xbox.rs @@ -151,6 +151,19 @@ impl Fssm { self.version == 0x101 && rd32(&self.data, 0xD4).is_some_and(|w| w != 0xDEAD_BEEF && w & 0x20 != 0) } + /// The constant data blocks that follow program `p` in the code region, as the program + /// addresses them (`s_getpc_b64`: from its own start): (address, dwords of the block). + pub fn rodata(&self, p: &Program) -> Vec<(u32, Vec)> { + self.data_blocks + .iter() + .filter(|b| b.offset >= p.offset + p.len) + .filter_map(|b| { + let bytes = self.data.get(b.offset..b.offset + b.len)?; + Some(((b.offset - p.offset) as u32, bytes.chunks_exact(4).map(|w| u32::from_le_bytes(w.try_into().unwrap())).collect())) + }) + .collect() + } + pub fn stage_label(&self) -> String { if self.stages.is_empty() { return "?".into(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index eacbe52019..b92fbe9fc0 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1804,7 +1804,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // as `pso` translates: with the title's memory windows (`console_translation`, // `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; - let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, ..Default::default() }; + let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, rodata: f.rodata(p), ..Default::default() }; let Ok(t) = recomp::translate(code, &opt) else { continue }; if !t.complete() { continue; @@ -2480,9 +2480,9 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> let t = std::time::Instant::now(); let r = { let (tx, rx) = std::sync::mpsc::channel(); - let (c, m) = (code.to_vec(), mode.clone()); + let (c, m, rodata) = (code.to_vec(), mode.clone(), f.rodata(p)); std::thread::spawn(move || { - let _ = tx.send(coverage::translate_mode(&c, &m, o, validate)); + let _ = tx.send(coverage::translate_mode(&c, &m, o, validate, &rodata)); }); rx.recv_timeout(timeout).unwrap_or_else(|_| Err(format!("timeout: over {} s", timeout.as_secs()))) }; @@ -2524,7 +2524,7 @@ fn direct_sweep(input: &Input, opts: &ShadersOptions, t0: std::time::Instant) -> recomp::Mode::Pixel(_) => "ps_6_6", _ => "cs_6_6", }; - let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: wave64 && split, mem_windows: windows, ..Default::default() }; + let opt = recomp::Options { mode: mode.clone(), wave64, split_wave64: wave64 && split, mem_windows: windows, rodata: f.rodata(p), ..Default::default() }; let t = recomp::translate(code, &opt).ok().filter(|t| t.complete())?; dump("hlsl", t.hlsl.as_bytes()); let d = recomp::dxc::compile(&t.hlsl, "main", profile, &[]).ok()?; From 6a1e3a6513142df0f2812a87810e7e58d979265a Mon Sep 17 00:00:00 2001 From: theaustinayers <153482135+theaustinayers@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:13:39 -0500 Subject: [PATCH 197/258] Recompiler: an S# set before a branch is a static sampler after it, in the stages that draw A program's S# constants were known only inside the block that set them. The console compiler sets an S# before a loop or an if and samples inside it; those samples went through sampler-heap entry 0 (point, wrap, mip 0): banded gradients, stepped glows, a lookup that wraps. In vertex and pixel programs the constants are followed through the branches: a register is a constant at a block's start when every block that leads there leaves it with the same one. Not in the other programs: read this way on a retail title, compute programs gave ExecuteIndirect 2 055 counts out of range in 75 s (none before) and the device hung after 140 s. Why is not known yet. Co-Authored-By: Claude Fable 5.2 --- crates/xcl/src/gpu/dxil/kernel.rs | 2 +- crates/xcl/src/gpu/recomp/mod.rs | 138 +++++++++++++++++++++-------- crates/xcl/src/gpu/recomp/tests.rs | 47 ++++++++++ 3 files changed, 151 insertions(+), 36 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index a7f8bbaabd..6c0f56a41d 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -628,7 +628,7 @@ impl Lw { slot = slot.max(w); } } - lw.static_samplers = crate::gpu::recomp::constant_samplers(insts, leaders); + lw.static_samplers = crate::gpu::recomp::constant_samplers(insts, leaders, matches!(entry, Entry::Vertex(_) | Entry::Pixel(_))); let group_threads: Option = match entry { Entry::Vertex(_) | Entry::Pixel(_) => None, Entry::Kernel => None, diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 26a1b74a3b..1cbdd39519 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1564,47 +1564,115 @@ fn scalar_constant(d: &Decoded, code: u64) -> Option { } /// S# built from constants in the code – how the console compiler places the static -/// samplers of a root signature: for each MIMG instruction whose four sampler SGPRs were all -/// set by s_mov / s_movk / s_brev with constants earlier in its block, those words. -pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet) -> BTreeMap { - let mut known: std::collections::HashMap = std::collections::HashMap::new(); - let mut out = BTreeMap::new(); - for d in insts { - if leaders.contains(&d.pc) { - known.clear(); - } - let f = |n: &str| rdna2::field_value(d.enc, &d.words, n); - if d.enc.name == "ENC_MIMG" { - if let Some(s) = f("SSAMP").map(|v| v * rdna2::register_scale("SSAMP")) { - if let (Some(a), Some(b), Some(c), Some(e)) = (known.get(&s), known.get(&(s + 1)), known.get(&(s + 2)), known.get(&(s + 3))) { - out.insert(d.pc, [*a, *b, *c, *e]); +/// samplers of a root signature: for each MIMG instruction whose four sampler SGPRs hold +/// constants set by s_mov / s_movk / s_brev on every path that reaches it, those words. +/// +/// The constants are followed through the program's branches (the compiler sets an S# before a +/// loop or an `if` and samples inside it): a register is a constant at a block's start when +/// every block that leads there leaves it with the same one. A program with a branch whose +/// target is not known is read block by block, as nothing is known at a block's start then. +/// +/// `follow`: the stages that draw (vertex and pixel programs). The other programs are read +/// block by block as before: on a retail title, compute programs read this way gave garbage +/// counts to `ExecuteIndirect` (2 055 in 75 s, none before) and the device hung. +pub(crate) fn constant_samplers(insts: &[Decoded], leaders: &BTreeSet, follow: bool) -> BTreeMap { + type Known = std::collections::HashMap; + // one block's instructions on `known`; the S# of its MIMG instructions into `out` + fn run(block: &[Decoded], known: &mut Known, mut out: Option<&mut BTreeMap>) { + for d in block { + let f = |n: &str| rdna2::field_value(d.enc, &d.words, n); + if d.enc.name == "ENC_MIMG" { + if let (Some(out), Some(s)) = (out.as_deref_mut(), f("SSAMP").map(|v| v * rdna2::register_scale("SSAMP"))) { + if let (Some(a), Some(b), Some(c), Some(e)) = (known.get(&s), known.get(&(s + 1)), known.get(&(s + 2)), known.get(&(s + 3))) { + out.insert(d.pc, [*a, *b, *c, *e]); + } } } - } - let set: Vec<(u64, u32)> = match d.inst.name { - "S_MOV_B32" => f("SDST").zip(f("SSRC0").and_then(|c| scalar_constant(d, c))).map(|(r, v)| vec![(r, v)]).unwrap_or_default(), - "S_MOVK_I32" => f("SDST").zip(f("SIMM16")).map(|(r, v)| vec![(r, v as u16 as i16 as i32 as u32)]).unwrap_or_default(), - // a constant with only high bits set, as the compiler writes it: `s_brev_b32 s66, 40` - "S_BREV_B32" => f("SDST").zip(f("SSRC0").and_then(|c| scalar_constant(d, c))).map(|(r, v)| vec![(r, v.reverse_bits())]).unwrap_or_default(), - // 64-bit moves of inline integers (sign-extended): S# words that are 0 / -1 - "S_MOV_B64" => match (f("SDST"), f("SSRC0")) { - (Some(r), Some(c @ 128..=208)) => { - let v = scalar_constant(d, c).unwrap() as i32 as i64; - vec![(r, v as u32), (r + 1, (v >> 32) as u32)] - } + let set: Vec<(u64, u32)> = match d.inst.name { + "S_MOV_B32" => f("SDST").zip(f("SSRC0").and_then(|c| scalar_constant(d, c))).map(|(r, v)| vec![(r, v)]).unwrap_or_default(), + "S_MOVK_I32" => f("SDST").zip(f("SIMM16")).map(|(r, v)| vec![(r, v as u16 as i16 as i32 as u32)]).unwrap_or_default(), + // a constant with only high bits set, as the compiler writes it: `s_brev_b32 s66, 40` + "S_BREV_B32" => f("SDST").zip(f("SSRC0").and_then(|c| scalar_constant(d, c))).map(|(r, v)| vec![(r, v.reverse_bits())]).unwrap_or_default(), + // 64-bit moves of inline integers (sign-extended): S# words that are 0 / -1 + "S_MOV_B64" => match (f("SDST"), f("SSRC0")) { + (Some(r), Some(c @ 128..=208)) => { + let v = scalar_constant(d, c).unwrap() as i32 as i64; + vec![(r, v as u32), (r + 1, (v >> 32) as u32)] + } + _ => Vec::new(), + }, _ => Vec::new(), - }, - _ => Vec::new(), - }; - for w in rdna2::sgpr_uses(d).1 { - known.remove(&w); + }; + for w in rdna2::sgpr_uses(d).1 { + known.remove(&w); + } + for (r, v) in set { + if r < 106 { + known.insert(r, v); + } + } + } + } + // the blocks, in address order + let mut starts: Vec = insts.iter().enumerate().filter(|(i, d)| *i == 0 || leaders.contains(&d.pc)).map(|(i, _)| i).collect(); + starts.push(insts.len()); + let blocks: Vec<&[Decoded]> = starts.windows(2).map(|w| &insts[w[0]..w[1]]).filter(|b| !b.is_empty()).collect(); + let at: std::collections::HashMap = blocks.iter().enumerate().map(|(k, b)| (b[0].pc, k)).collect(); + // where each block goes on; None: somewhere that is not known + let next: Option>> = blocks + .iter() + .enumerate() + .map(|(k, b)| { + let d = b.last().unwrap(); + let after = (k + 1 < blocks.len()).then_some(k + 1); + Some(match (rdna2::branch_target(d), d.inst.name) { + (Some(t), n) if n.starts_with("S_CBRANCH") => after.into_iter().chain([*at.get(&t)?]).collect(), + (Some(t), "S_BRANCH" | "S_SETPC_B64") => vec![*at.get(&t)?], + (Some(_), _) => return None, + (None, "S_ENDPGM") => Vec::new(), + (None, _) if d.inst.flags & rdna2::F_TERMINATOR != 0 => return None, + _ => after.into_iter().collect(), + }) + }) + .collect(); + let mut out = BTreeMap::new(); + let Some(next) = next.filter(|_| follow) else { + for b in &blocks { + run(b, &mut Known::new(), Some(&mut out)); } - for (r, v) in set { - if r < 106 { - known.insert(r, v); + return out; + }; + // what is known at each block's start (None: not reached yet): what every way in agrees on + let mut start: Vec> = vec![None; blocks.len()]; + let mut work: Vec = Vec::new(); + if !blocks.is_empty() { + start[0] = Some(Known::new()); + work.push(0); + } + while let Some(k) = work.pop() { + let mut known = start[k].clone().unwrap_or_default(); + run(blocks[k], &mut known, None); + for &n in &next[k] { + let changed = match &mut start[n] { + slot @ None => { + *slot = Some(known.clone()); + true + } + Some(have) => { + let before = have.len(); + have.retain(|r, v| known.get(r) == Some(v)); + have.len() != before + } + }; + if changed { + work.push(n); } } } + for (k, b) in blocks.iter().enumerate() { + // (a block nothing leads to: nothing known at its start) + run(b, &mut start[k].clone().unwrap_or_default(), Some(&mut out)); + } out } @@ -1688,7 +1756,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { let mut em = emit::Em::new(opt.clone()); em.coherent_mem = matches!(opt.mode, Mode::Compute(_)) && needs_coherent_mem(&insts); em.configure_round_modes(&insts, branches == 0); - em.static_ss = constant_samplers(&insts, &leaders); + em.static_ss = constant_samplers(&insts, &leaders, matches!(opt.mode, Mode::Vertex(_) | Mode::Pixel(_))); // split wave64: masks only read lane by lane skip the halves' exchange (geometry mode // continues from the ES into the GS through s_setpc: left as it is); pixel shaders: they // skip the quad reads that give the helper lanes' bits diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index c069fd0971..2b4200a73e 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -3115,6 +3115,53 @@ fn static_sampler_word_from_s_brev_is_a_constant() { assert!(!t.hlsl.contains("SamplerDescriptorHeap"), "no sampler heap lookup left"); } +/// An S# set before a branch and sampled after it (the compiler sets the S# of a blur's taps +/// before the loop, of an effect before its `if`) is a static sampler all the same: the +/// constants are followed into the next block. Before, a block's start forgot them and the +/// shader sampled through sampler-heap entry 0 (point, wrap, mip 0). +#[test] +fn static_sampler_set_before_a_branch_is_a_constant_after_it() { + let clamp = 2 | 2 << 3 | 2 << 6; + let linear = [clamp, 0x00FF_F000u32, 0x0050_0000u32, 0]; + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 255)], Some(linear[0])), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 25), ("SSRC0", 255)], Some(linear[1])), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 26), ("SSRC0", 255)], Some(linear[2])), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 27), ("SSRC0", 128)], None), + // (both ways go to the next instruction: it starts a block) + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 0)], None), + ("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 1)], None), + ]); + let pixel = Options { mode: Mode::Pixel(crate::gpu::recomp::PsInterface::default()), ..Default::default() }; + let t = translate(&code, &pixel).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + assert_eq!(t.static_samplers, vec![(linear, false)], "the S# set before the branch is a static sampler"); + assert!(!t.hlsl.contains("SamplerDescriptorHeap"), "no sampler heap lookup left"); + // a program that does not draw is read block by block, as before + let t = translate(&code, &Options::default()).unwrap(); + assert!(t.static_samplers.is_empty(), "{:?}", t.static_samplers); +} + +/// Two ways into a block that leave different words in an S# register: not a constant there, +/// the sampler is looked up as before. +#[test] +fn an_s_word_that_differs_by_the_way_in_is_no_constant() { + let clamp = 2 | 2 << 3 | 2 << 6; + let code = prog(&[ + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 24), ("SSRC0", 255)], Some(clamp)), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 25), ("SSRC0", 255)], Some(0x00FF_F000)), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 26), ("SSRC0", 255)], Some(0x0050_0000)), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 27), ("SSRC0", 128)], None), + // over the next move (two dwords): one way keeps the first s26, the other sets another + ("S_CBRANCH_EXECZ", "ENC_SOPP", &[("SIMM16", 2)], None), + ("S_MOV_B32", "ENC_SOP1", &[("SDST", 26), ("SSRC0", 255)], Some(0)), + ("IMAGE_SAMPLE_LZ", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("SSAMP", 6), ("DMASK", 0xF), ("DIM", 1)], None), + ]); + let pixel = Options { mode: Mode::Pixel(crate::gpu::recomp::PsInterface::default()), ..Default::default() }; + let t = translate(&code, &pixel).unwrap(); + assert!(t.static_samplers.is_empty(), "{:?}", t.static_samplers); +} + /// The same program on the GPU: the texel a point sampler picks at a texel boundary. #[test] fn gpu_static_sampler_word_from_s_brev() { From 2f918710eff1b39bbf6e955de326649764bd57da Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:08:05 +0300 Subject: [PATCH 198/258] D3D12.X: default XCL_INLINE_GUARD_BATCH off to avoid dead 64 KiB scratch allocations and AMD page faults --- crates/xcl/src/hle/d3d12x/bind.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 4cffb0a3b7..902287a155 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -269,9 +269,17 @@ const INLINE_GUARD_BATCH_MAX: u32 = 256; const INLINE_GUARD_JOBS_BYTES: usize = 16 + INLINE_GUARD_BATCH_MAX as usize * 32; const INLINE_GUARD_DST_BYTES: u64 = INLINE_GUARD_BATCH_MAX as u64 * 256; +fn parse_inline_guard_batch(val: Option<&str>) -> bool { + val.is_some_and(|v| v.trim() == "1") +} + +/// Opt-in inline 256-slot guard batching (`XCL_INLINE_GUARD_BATCH=1`). Defaults off because +/// `execute_indirect` clears `s.inline_guard` after each dispatch (so batching never exceeds 1) +/// while allocating 64 KiB scratch + 8 KiB coherent UMA per dispatch and triggering page faults on +/// AMD RDNA4; the default `guard_indirect_heap_pipeline` uses 32-bit root constants and 256 B scratch. fn inline_guard_batch_on() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_INLINE_GUARD_BATCH").map_or(true, |v| v.trim() != "0")) + *ON.get_or_init(|| parse_inline_guard_batch(std::env::var("XCL_INLINE_GUARD_BATCH").ok().as_deref())) } /// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its @@ -4810,6 +4818,15 @@ mod tests { use super::*; use std::sync::atomic::AtomicUsize; + #[test] + fn inline_guard_batch_defaults_off_and_opts_in() { + assert!(!parse_inline_guard_batch(None)); + assert!(!parse_inline_guard_batch(Some("0"))); + assert!(!parse_inline_guard_batch(Some(""))); + assert!(parse_inline_guard_batch(Some("1"))); + assert!(parse_inline_guard_batch(Some(" 1 "))); + } + /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. #[test] fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() { From 39a2e7e8583e872d97f1b4067a1705e837866944 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:34:11 +0100 Subject: [PATCH 199/258] D3D12.X / UMA: 64 KiB arena blocks, UMA-full prelude fallback, dispatch_chain bind-fail hold, deferred alloc_release, and sparse readback CPU-write guard --- crates/xcl/src/gpu/uma.rs | 8 +- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 97 ++++++++++++++++++- crates/xcl/src/hle/d3d12x/bind.rs | 83 +++++++++++++--- crates/xcl/src/hle/d3d12x/console_list.rs | 2 +- crates/xcl/src/hle/d3d12x/present.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 18 +++- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 21 +++- crates/xcl/src/hle/d3d12x/sparse.rs | 63 +++++++++--- 8 files changed, 260 insertions(+), 33 deletions(-) diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index faa2d32dbc..73b08b4644 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -756,8 +756,12 @@ pub struct Arena { end: usize, } -/// block size of an `Arena` -pub const ARENA_BLOCK: usize = 4 * GRAIN; +/// block size of an `Arena` (64 KiB grain keeps ~190 live allocators under ~25 MB instead of ~100 MB) +pub const ARENA_BLOCK: usize = GRAIN; + +/// Maximum `AllocateUploadMemory` request routed through the per-list arena (keeps the 128 KiB +/// threshold unchanged after shrinking `ARENA_BLOCK` from 256 KiB to 64 KiB). +pub const UPLOAD_IN_ARENA_MOST: usize = 2 * GRAIN; impl Arena { /// `n` bytes at an `align`-aligned address in committed unified memory (not zeroed), or diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 65c650f0b0..9434daaf90 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -56,6 +56,16 @@ struct State { /// PC list → recordings so far (a Reset or creation starts the next one) recordings: HashMap, resubmits: u64, + /// Title allocators released while their submitted GPU fences are still running: held until + /// every fence completes (`release_finished`, polled at `PresentX`) so VRAM `io` slabs and + /// dispatch-chain scratch are never freed out from under active GPU work. + pending_releases: Vec, +} + +struct PendingRelease { + marks: Vec<(ID3D12Fence, u64)>, + made: Vec, + cleanup: Box, } struct LastSubmit { @@ -225,7 +235,7 @@ unsafe fn wait_for_previous_submits_within(lists: &[*mut c_void], limit: std::ti lists .iter() .filter_map(|&l| s.last_submit.get(&(l as usize))) - .filter(|l| super::real::fence_completed(&l.fence) < l.value) + .filter(|l| l.fence.GetCompletedValue() < l.value) .map(|l| (l.fence.clone(), l.value)) .collect() }; @@ -238,7 +248,7 @@ unsafe fn wait_for_previous_submits_within(lists: &[*mut c_void], limit: std::ti // (XCL's own fence, read without the title's hook; a removed device reads as the largest // value: no wait then. Such a submit is milliseconds from done: a short poll) let mut polls = 0u32; - while super::real::fence_completed(fence) < *value { + while fence.GetCompletedValue() < *value { if start.elapsed() >= limit { late += 1; break; @@ -320,6 +330,89 @@ pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { busy } +/// Like `forget`, but when `alloc` (or any of its put-aside backings) still has unfinished GPU +/// fence marks, defers running `cleanup` (and dropping any XCL-created spare PC allocators) until +/// all those fences complete (`release_finished`). Returns `true` if deferred, `false` if all +/// GPU work was already done and the caller should run cleanup immediately. +pub unsafe fn release_when_done(alloc: usize, cleanup: Box) -> bool { + let (deferred, immediate_made) = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { + return false; + }; + s.types.remove(&alloc); + let mut mine: Vec = s.aside.remove(&alloc).unwrap_or_default(); + mine.extend(s.cur.remove(&alloc)); + mine.push(alloc); + let mut pending_marks: Vec<(ID3D12Fence, u64)> = Vec::new(); + let mut made_busy: Vec = Vec::new(); + let mut made_free: Vec = Vec::new(); + for b in mine { + let mut busy = false; + if let Some(gone) = s.backings.remove(&b) { + for l in gone.users { + s.of_list.remove(&l); + } + for (_, (f, v)) in gone.marks { + if f.GetCompletedValue() < v { + pending_marks.push((f, v)); + busy = true; + } + } + } + if b != alloc { + if busy { + made_busy.push(b); + } else { + made_free.push(b); + } + } + } + if pending_marks.is_empty() { + (false, made_free) + } else { + s.pending_releases.push(PendingRelease { + marks: pending_marks, + made: made_busy, + cleanup, + }); + (true, made_free) + } + }; + for b in immediate_made { + drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); + } + deferred +} + +/// Run deferred `release_when_done` cleanups whose GPU fences have all completed (polled once +/// per `PresentX`, outside `STATE` so cleanups and COM drops cannot re-enter `STATE`). +pub unsafe fn release_finished() { + let done: Vec = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if s.pending_releases.is_empty() { + return; + } + let mut ready = Vec::new(); + let mut i = 0; + while i < s.pending_releases.len() { + if s.pending_releases[i].marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v) { + ready.push(s.pending_releases.swap_remove(i)); + } else { + i += 1; + } + } + ready + }; + for item in done { + (item.cleanup)(); + for b in item.made { + drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); + } + } +} + /// The title's allocator `alloc` is gone (its last Release): nothing of it stays here – a later /// allocator may get its address, and must not go on with this one's PC allocators. The ones /// made here go with it (those lists still record on are left alone: not freed, not tracked). diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 902287a155..9e48c5dd39 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -212,6 +212,8 @@ struct State { prelude_draws: Vec, prelude_owned: Option, prelude_built: Option, + /// Dedicated non-pooled CUSTOM write-back L0 buffers backing prelude job tables when UMA is full + prelude_job_bufs: Vec, /// true after an `INDIRECT_ARGUMENT` transition has ordered prior writes on this list and /// no compute/mesh dispatch has run since (skips redundant `fresh_indirect_arguments` barriers /// across runs of consecutive indirect graphics draws). @@ -315,6 +317,7 @@ static ALLOC_IO: Mutex>>> = Mutex::new(None); static FREE_IO: Mutex> = Mutex::new(Vec::new()); static ALLOC_PRELUDE: Mutex>>> = Mutex::new(None); static FREE_PRELUDE: Mutex> = Mutex::new(Vec::new()); +static ALLOC_PRELUDE_JOBS: Mutex>>> = Mutex::new(None); fn hold_res_until_reset(allocator: usize, mut bufs: Vec<(ID3D12Resource, u64, usize)>) { if bufs.is_empty() || allocator == 0 { @@ -338,6 +341,13 @@ fn hold_prelude_until_reset(allocator: usize, entry: Option) { ALLOC_PRELUDE.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().push(entry); } +fn hold_prelude_jobs_until_reset(allocator: usize, mut bufs: Vec) { + if bufs.is_empty() || allocator == 0 { + return; + } + ALLOC_PRELUDE_JOBS.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().append(&mut bufs); +} + /// Return `items` into `free` whenever `keep(&pool, &item)` holds, dropping overflow items /// *after* releasing `free` so COM `Release` hooks that re-enter `release_allocator_res` /// cannot self-deadlock on the pool mutex. @@ -382,6 +392,9 @@ pub(super) fn release_allocator_res(allocator: usize) { if let Some(entries) = entries { recycle_into_pool(&FREE_PRELUDE, entries, |pool, _| pool.len() < FREE_PRELUDE_CAP); } + // Never pooled: drop outside lock so COM Release hooks cannot re-enter `ALLOC_PRELUDE_JOBS`. + let job_bufs = ALLOC_PRELUDE_JOBS.lock().unwrap().as_mut().and_then(|m| m.remove(&allocator)); + drop(job_bufs); } /// Whether `FREE_RES`, holding `count` buffers of `held` bytes, keeps one of `bytes` more. @@ -590,7 +603,7 @@ fn backing_allocator(list: *mut c_void, allocator: usize) -> usize { /// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { let backing = backing_allocator(list, allocator); - let (old, blocks, res_bufs, io_blocks, prelude) = with(list, |s| { + let (old, blocks, res_bufs, io_blocks, prelude, job_bufs) = with(list, |s| { let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.pso = initial_pso; @@ -613,6 +626,7 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { s.prelude_draws.clear(); let prelude = s.prelude_owned.take(); s.prelude_built = None; + let job_bufs = std::mem::take(&mut s.prelude_job_bufs); s.inline_guard = None; s.root_va_cache = [(0, 0); 16]; s.root_va_next = 0; @@ -637,12 +651,13 @@ pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { } let io_blocks = std::mem::take(&mut s.io_blocks); s.rs_cs = 0; - (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude) + (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude, job_bufs) }); console_list::hold_until_reset(old, blocks); hold_res_until_reset(old, res_bufs); hold_io_until_reset(old, io_blocks); hold_prelude_until_reset(old, prelude); + hold_prelude_jobs_until_reset(old, job_bufs); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults @@ -675,7 +690,7 @@ pub(super) fn clear_state(list: *mut c_void, pso: usize) { /// recording buffers on the old allocator first. pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { let backing = backing_allocator(list, allocator); - let (old, blocks, res_bufs, io_blocks, prelude) = with(list, |s| { + let (old, blocks, res_bufs, io_blocks, prelude, job_bufs) = with(list, |s| { s.heaps_ensured = false; s.pc_abi_gfx = AbiBound::default(); s.pc_abi_cs = AbiBound::default(); @@ -688,11 +703,12 @@ pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { s.prelude_draws.clear(); let prelude = s.prelude_owned.take(); s.prelude_built = None; + let job_bufs = std::mem::take(&mut s.prelude_job_bufs); if s.allocator == backing { for sl in &mut s.scratch { sl.state = D3D12_RESOURCE_STATE_COMMON; } - return (backing, Vec::new(), Vec::new(), Vec::new(), prelude); + return (backing, Vec::new(), Vec::new(), Vec::new(), prelude, job_bufs); } let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); @@ -710,12 +726,13 @@ pub(super) fn rebind_allocator(list: *mut c_void, allocator: usize) { res_bufs.push(b); } let io_blocks = std::mem::take(&mut s.io_blocks); - (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude) + (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude, job_bufs) }); console_list::hold_until_reset(old, blocks); hold_res_until_reset(old, res_bufs); hold_io_until_reset(old, io_blocks); hold_prelude_until_reset(old, prelude); + hold_prelude_jobs_until_reset(old, job_bufs); } /// Carry bound pipeline and root-signature / root-argument state from `from` to `to` across a @@ -726,7 +743,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u let (layout, args, layout_gfx, args_gfx, rs_gfx, rs_cs, pso, heaps) = with(from, |s| { (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.rs_cs, s.pso, s.heaps) }); - let (old, blocks, res_bufs, io_blocks, prelude) = with(to, |s| { + let (old, blocks, res_bufs, io_blocks, prelude, job_bufs) = with(to, |s| { let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.layout = layout; @@ -751,6 +768,7 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u s.prelude_draws.clear(); let prelude = s.prelude_owned.take(); s.prelude_built = None; + let job_bufs = std::mem::take(&mut s.prelude_job_bufs); s.inline_guard = None; s.root_va_cache = [(0, 0); 16]; s.root_va_next = 0; @@ -774,12 +792,13 @@ pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: u res_bufs.push(b); } let io_blocks = std::mem::take(&mut s.io_blocks); - (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude) + (old, std::mem::take(&mut s.uma), res_bufs, io_blocks, prelude, job_bufs) }); console_list::hold_until_reset(old, blocks); hold_res_until_reset(old, res_bufs); hold_io_until_reset(old, io_blocks); hold_prelude_until_reset(old, prelude); + hold_prelude_jobs_until_reset(old, job_bufs); } /// A submit is about to wait for the pipeline `this` has bound. @@ -815,6 +834,7 @@ pub(super) fn forget(list: *mut c_void) { hold_res_until_reset(s.allocator, s.res_retired); hold_io_until_reset(s.allocator, s.io_blocks); hold_prelude_until_reset(s.allocator, s.prelude_owned.take()); + hold_prelude_jobs_until_reset(s.allocator, std::mem::take(&mut s.prelude_job_bufs)); } } @@ -2453,12 +2473,51 @@ pub(super) unsafe fn prelude_list_for(seg: *mut c_void) -> Option<*mut c_void> { std::mem::ManuallyDrop::drop(&mut (*b.Anonymous.Transition).pResource); } - // Helper to upload a packed `u32` job slice into `seg`'s UMA arena. + // Helper to upload a packed `u32` job slice into `seg`'s UMA arena, falling back to a + // dedicated non-pooled CUSTOM write-back L0 buffer when committed unified memory is full + // so the prelude never fails and leaves `seg` running with stale VRAM io / unguarded args. let upload_words = |words: &[u32]| -> Result { let bytes = std::mem::size_of_val(words); - let p = with(seg, |s| s.arena.take(u, bytes.max(16), 256, &mut s.uma)).ok_or("unified memory is full")?; - std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), p, bytes); - super::real::uma_va_of(p as usize).ok_or_else(|| "unified memory is not open on the GPU".into()) + if let Some(p) = with(seg, |s| s.arena.take(u, bytes.max(16), 256, &mut s.uma)) { + std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), p, bytes); + return super::real::uma_va_of(p as usize).ok_or_else(|| "unified memory is not open on the GPU".into()); + } + let alloc_bytes = (bytes.max(16) as u64).next_multiple_of(256); + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, + MemoryPoolPreference: D3D12_MEMORY_POOL_L0, + CreationNodeMask: 1, + VisibleNodeMask: 1, + }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: alloc_bytes, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let mut buf: Option = None; + dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut buf) + .map_err(|e| format!("prelude job fallback buffer: {e}"))?; + let buf = buf.ok_or("prelude job fallback buffer was null")?; + let _ = buf.SetName(windows::core::w!("xcl prelude jobs (UMA full)")); + let mut mapped = std::ptr::null_mut(); + let empty = D3D12_RANGE { Begin: 0, End: 0 }; + buf.Map(0, Some(&empty), Some(&mut mapped)).map_err(|e| format!("prelude job fallback map: {e}"))?; + std::ptr::copy_nonoverlapping(words.as_ptr().cast::(), mapped as *mut u8, bytes); + let written = D3D12_RANGE { Begin: 0, End: bytes }; + buf.Unmap(0, Some(&written)); + let va = buf.GetGPUVirtualAddress(); + if va == 0 { + return Err("prelude job fallback GPU VA is 0".into()); + } + with(seg, |s| s.prelude_job_bufs.push(buf)); + Ok(va) }; let bind_windows = |list: &ID3D12GraphicsCommandList| { @@ -4539,7 +4598,7 @@ pub(super) unsafe extern "system" fn allocate_upload_memory(this: *mut c_void, s }; let size = size.max(16); let align = align.max(16); - if size <= crate::gpu::uma::ARENA_BLOCK / 2 { + if size <= crate::gpu::uma::UPLOAD_IN_ARENA_MOST { if let Some(p) = with(this, |s| s.arena.take(u, size, align, &mut s.uma)) { return p; } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index c5fb014b9e..3824fe7e8b 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -593,7 +593,7 @@ unsafe extern "system" fn cl_allocate_upload_memory(this: *mut c_void, size: usi let Some(u) = crate::gpu::uma::get() else { return std::ptr::null_mut() }; let size = size.max(16); let align = align.max(16); - if size <= crate::gpu::uma::ARENA_BLOCK / 2 { + if size <= crate::gpu::uma::UPLOAD_IN_ARENA_MOST { if let Some(p) = with_list(this as usize, |st| st.arena.take(u, size, align, &mut st.uma)).flatten() { return p; } diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d66186e216..0eefbd460f 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -129,6 +129,7 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u } } super::real::stop_if_device_removed(); + super::alloc_pool::release_finished(); crate::gpu::texture::trim_idle_staging(frames, super::vram::commit_low()); if !PRESENTX.swap(true, Ordering::Relaxed) { crate::xlog_info!("D3D12.X: PresentX – the title presents its own frames ({plane_count} plane(s))"); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9b94f829b4..511c391f7b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8841,10 +8841,20 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { release_taking_first( this, || { - dispatch_chain::allocator_reset(this as usize); - super::console_list::allocator_reset(this); - super::alloc_pool::forget(this as usize); - super::list_x::on_allocator_release(this as usize); + let a = this as usize; + let deferred = super::alloc_pool::release_when_done( + a, + Box::new(move || { + dispatch_chain::allocator_reset(a); + super::console_list::allocator_reset(a as *mut c_void); + super::list_x::on_allocator_release(a); + }), + ); + if !deferred { + dispatch_chain::allocator_reset(a); + super::console_list::allocator_reset(this); + super::list_x::on_allocator_release(a); + } }, drop, ) diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 79162a0b0b..7d31906474 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -741,7 +741,26 @@ pub(in crate::hle::d3d12x) unsafe fn execute_indirect( if slicer_pso != 0 && SLICER_LABELED.swap(slicer_pso, Ordering::Relaxed) != slicer_pso { super::super::dred::label_text(slicer_pso, || "xcl dispatch_chain_slicer".into()); } - bind()?; + if let Err(e) = bind() { + // `record_slicer` already recorded a dispatch writing into `buffer` and `scratch`: + // keep both alive until `allocator` resets so the GPU never page-faults on a freed buffer. + if let Some(first) = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)) { + let indirect = Indirect { + commands: buffer, + at: pso::chain_predicate_offset(rounds, pieces), + rounds, + whole: false, + checked: false, + }; + RECORDINGS + .lock() + .unwrap() + .entry(allocator) + .or_default() + .push(Arc::new(Recording { scratch, first: first.clone(), chain, indirect: Some(indirect) })); + } + return Err(e); + } // under the title's own predication XCL's cannot be set: the slabs past the rounds are lost let full = if predicated { None } else { chain.whole.get().and_then(|o| o.clone()) }; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 6875bed66f..c6ffa489b0 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1058,10 +1058,11 @@ impl State { /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { let Some((rb, p)) = self.readback_buf() else { return }; - let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) + // (va, rb_off, len, pre-wait 64-byte chunk hashes of committed pages) + let mut pending: Vec<(usize, usize, usize, Vec>)> = Vec::new(); let mut used = 0usize; let mut open = false; - let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| { + let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize, Vec>)>, used: &mut usize, p: *mut u8| { if *open { *open = false; if s.rb_list.Close().is_ok() { @@ -1076,8 +1077,11 @@ impl State { s.wait_for(s.value); s.reclaim_ring(); } - for &(dst, off, len) in pending.iter() { - // copy only committed (non-hole) bytes + for (dst, off, len, snap) in pending.iter() { + let (dst, off, len) = (*dst, *off, *len); + let snap_base = dst & !(CHUNK - 1); + // Copy only committed (non-hole) 64-byte chunks whose host memory did not change + // during the GPU readback wait, so concurrent CPU writes are never clobbered. let mut at = dst; let mut src_off = off; let end = dst + len; @@ -1085,14 +1089,36 @@ impl State { let pg = at & !(PAGE - 1); let t = pg & !(TILE - 1); let idx = (pg - t) / PAGE; - let step = (pg + PAGE).min(end) - at; - if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { - std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + let page_end = (pg + PAGE).min(end); + if let Some(entry) = s.mapped.get_mut(&t).filter(|e| e.holes & (1u16 << idx) == 0) { + while at < page_end { + let chunk_va = at & !(CHUNK - 1); + let chunk_end = (chunk_va + CHUNK).min(page_end); + let step = chunk_end - at; + let snap_i = (chunk_va - snap_base) / CHUNK; + let unchanged = snap.get(snap_i).copied().flatten().is_some_and(|expected| { + chunk_hash(std::slice::from_raw_parts(chunk_va as *const u8, CHUNK)) == expected + }); + if unchanged { + std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + let new_h = chunk_hash(std::slice::from_raw_parts(chunk_va as *const u8, CHUNK)); + let k = (chunk_va - pg) / CHUNK; + if let Some(sent) = entry.sent[idx].as_deref_mut() { + sent[k] = new_h; + } else if new_h != ZERO_HASH { + let sent = entry.sent[idx].insert(Box::new(ZERO_HASHES)); + sent[k] = new_h; + } + } + at += step; + src_off += step; + } + } else { + let step = page_end - at; + at += step; + src_off += step; } - at += step; - src_off += step; } - s.sync_sent_range(dst, len); } pending.clear(); *used = 0; @@ -1123,8 +1149,23 @@ impl State { let _ = self.rb_list.Reset(&self.rb_alloc, None); open = true; } + let snap_base = cur & !(CHUNK - 1); + let snap_end = (cur + chunk).saturating_add(CHUNK - 1) & !(CHUNK - 1); + let mut snap = Vec::with_capacity((snap_end - snap_base) / CHUNK); + let mut c = snap_base; + while c < snap_end { + let pg = c & !(PAGE - 1); + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; + if self.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { + snap.push(Some(chunk_hash(std::slice::from_raw_parts(c as *const u8, CHUNK)))); + } else { + snap.push(None); + } + c += CHUNK; + } self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); - pending.push((cur, used, chunk)); + pending.push((cur, used, chunk, snap)); used += chunk; done += chunk; } From 4886319e5a27c474ea31511b4c1d16957df49108 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:52:22 +0100 Subject: [PATCH 200/258] d3d12x: hold native ID3D12CommandAllocator ref in deferred alloc_release until GPU fences finish --- crates/xcl/src/hle/d3d12x/real.rs | 63 ++++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 18 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 511c391f7b..449ac5efaf 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -8838,26 +8838,53 @@ unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { } unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { - release_taking_first( - this, - || { - let a = this as usize; - let deferred = super::alloc_pool::release_when_done( - a, - Box::new(move || { - dispatch_chain::allocator_reset(a); - super::console_list::allocator_reset(a as *mut c_void); - super::list_x::on_allocator_release(a); - }), - ); - if !deferred { + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + if add_ref(this) == 2 { + let a = this as usize; + let deferred = super::alloc_pool::release_when_done( + a, + Box::new(move || { dispatch_chain::allocator_reset(a); - super::console_list::allocator_reset(this); + super::console_list::allocator_reset(a as *mut c_void); super::list_x::on_allocator_release(a); - } - }, - drop, - ) + // Drop the final PC ID3D12CommandAllocator reference only after all GPU + // fences on its backing complete so the D3D12 command pool is never freed + // while still in flight on the GPU. + rel(a as *mut c_void); + }), + ); + if deferred { + // Drop our temporary probe ref, keeping 1 ref alive for the deferred cleanup above, + // and report 0 to the title since its ownership of the allocator has ended. + rel(this); + return 0; + } + dispatch_chain::allocator_reset(a); + super::console_list::allocator_reset(this); + super::list_x::on_allocator_release(a); + rel(this); + return rel(this); + } + rel(this); + let n = rel(this); + if n == 0 { + let a = this as usize; + // Rare race: two threads reached final release concurrently; object is already freed. + if !super::alloc_pool::release_when_done( + a, + Box::new(move || { + dispatch_chain::allocator_reset(a); + super::console_list::allocator_reset(a as *mut c_void); + super::list_x::on_allocator_release(a); + }), + ) { + dispatch_chain::allocator_reset(a); + super::console_list::allocator_reset(this); + super::list_x::on_allocator_release(a); + } + } + n } /// Reset the (adopted) PC allocator `raw` itself. From 5bb421641148603268e15a1b3e35e63b723625a0 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:08:00 +0100 Subject: [PATCH 201/258] d3d12x: target R9G9B9E5 R32_UINT in ambient TemporalResolve and add XCL_FRAME_DUMP_FROM --- crates/xcl/src/hle/d3d12x/ambient.rs | 152 +++++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/present.rs | 27 ++++- 2 files changed, 165 insertions(+), 14 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 8e3f4718a8..72e3ed6848 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -51,13 +51,13 @@ impl Default for Config { fn default() -> Self { Self { mode: Mode::Auto, - gain: 0.55, + gain: 0.22, power: 0.65, - least: 0.025, + least: 0.02, ao: 0.55, - reflect: 0.50, + reflect: 1.50, settle_ms: 250.0, - air: 1.5, + air: 0.0, } } } @@ -240,8 +240,8 @@ static VIEW_SLOTS: RwLock> = RwLock::new(None); static HAS_VIEW_SLOTS: AtomicBool = AtomicBool::new(false); fn is_ambient_uav_format(fmt: i32) -> bool { - // R16G16B16A16_FLOAT (10), R11G11B10_FLOAT (26), R32G32B32A32_FLOAT (2) - matches!(fmt, 10 | 26 | 2) + // R16G16B16A16_FLOAT (10), R11G11B10_FLOAT (26), R32G32B32A32_FLOAT (2), R32_UINT (42, R9G9B9E5 packed) + matches!(fmt, 10 | 26 | 2 | 42) } fn is_depth_srv_format(fmt: i32) -> bool { @@ -356,7 +356,19 @@ fn is_sky_dome_target(rd: &D3D12_RESOURCE_DESC) -> bool { /// Match a screen-space resolve/reflection output UAV against dispatch grid dimensions, returning /// a lower-is-better score when compatible (`None` if incompatible). -/// Uses the UAV view's concrete `view_fmt` so typeless resources (`R16G16B16A16_TYPELESS`) match. +/// `TemporalResolve` writes diffuse screen-probe light as packed `R9G9B9E5` in `R32_UINT` (`fmt 42`); +/// restricting `TemporalResolve` to `R32_UINT` avoids accidentally overwriting a `R11G11B10_FLOAT` +/// (`fmt 26`) HDR scene color buffer bound in the same descriptor heap. +fn score_dispatch_target_for_role(role: PassRole, rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; 3]) -> Option { + if role == PassRole::TemporalResolve && view_fmt != 42 { + return None; + } + if role == PassRole::ReflectionHistory && view_fmt == 42 { + return None; + } + score_dispatch_target(rd, view_fmt, groups) +} + fn score_dispatch_target(rd: &D3D12_RESOURCE_DESC, view_fmt: i32, groups: [u32; 3]) -> Option { if rd.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || rd.DepthOrArraySize != 1 @@ -475,6 +487,7 @@ struct AmbientDevice { reduce_pso: ID3D12PipelineState, fill_pso: ID3D12PipelineState, fill_write_pso: ID3D12PipelineState, + fill_r9_pso: ID3D12PipelineState, reflect_pso: ID3D12PipelineState, air_pso: ID3D12PipelineState, sky_copy: ID3D12Resource, @@ -641,6 +654,88 @@ void main(uint3 tid : SV_DispatchThreadID) { } "#; +/// Screen-space diffuse probe radiance floor + 8-tap IGN-rotated horizon crease AO for +/// `CS_ScreenProbes_TemporalResolve` targets stored as `R9G9B9E5_SHAREDEXP` packed in `R32_UINT`. +const AMBIENT_FILL_R9G9B9E5_HLSL: &str = r#" +Texture2D depth_tex : register(t0); +RWTexture2D out_uav : register(u0); +RWStructuredBuffer sky_level : register(u1); +cbuffer C : register(b0) { + uint width; + uint height; + uint depth_w; + uint depth_h; + uint has_depth; + float ao_strength; + uint sky_ready; + float fallback_level; +}; +float3 unpack_r9g9b9e5(uint v) { + float scale = exp2(float(v >> 27) - 24.0); + return float3(float(v & 511u), float((v >> 9) & 511u), float((v >> 18) & 511u)) * scale; +} +uint pack_r9g9b9e5(float3 c) { + c = clamp(c, 0.0, 65408.0); + float top = max(c.r, max(c.g, c.b)); + int e = clamp(int(floor(log2(max(top, 1e-9)))) + 16, 0, 31); + float inv_s = exp2(float(24 - e)); + uint3 m = min(uint3(floor(c * inv_s + 0.5)), uint3(511u, 511u, 511u)); + return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27); +} +float horizon_crease_ao(uint2 tid, int2 dc, int2 maxc) { + float d0 = depth_tex.Load(int3(dc, 0)); + if (!isfinite(d0) || d0 <= 1e-5 || d0 >= 0.99999) { + return 1.0; + } + float ign = frac(52.9829189 * frac(dot(float2(tid), float2(0.06711056, 0.00583715)))); + float base_ang = ign * 6.2831853; + float max_rad = clamp(float(depth_w) * 0.012, 4.0, 16.0); + float inv_d0 = 1.0 / max(d0, 1e-5); + float occ = 0.0; + [unroll] + for (uint i = 0; i < 4; ++i) { + float ang = base_ang + float(i) * 0.78539816; + float t = frac(ign * 0.61803399 + (float(i) + 0.5) * 0.25); + float rad = clamp(max_rad * sqrt(t), 1.5, 16.0); + int2 ofs = int2(int(round(cos(ang) * rad)), int(round(sin(ang) * rad))); + float dp = depth_tex.Load(int3(clamp(dc + ofs, int2(0, 0), maxc), 0)); + float dn = depth_tex.Load(int3(clamp(dc - ofs, int2(0, 0), maxc), 0)); + float rp = (dp - d0) * inv_d0; + float rn = (dn - d0) * inv_d0; + float wp = (isfinite(dp) && dp > 1e-6 && dp < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rp))) : 0.0; + float wn = (isfinite(dn) && dn > 1e-6 && dn < 0.99999) ? (1.0 - smoothstep(0.15, 0.45, abs(rn))) : 0.0; + float conc = max(0.0, rp * wp + rn * wn); + occ += saturate((conc - 0.003) * 4.5); + } + return saturate(1.0 - ao_strength * saturate(occ * 0.25)); +} +[numthreads(8, 8, 1)] +void main(uint3 tid : SV_DispatchThreadID) { + if (tid.x >= width || tid.y >= height) return; + float3 raw_amb = (sky_ready != 0) ? sky_level[0].rgb : float3(fallback_level, fallback_level, fallback_level); + float3 amb = clamp(raw_amb, 0.0, 0.65); + float ao = 1.0; + if (has_depth != 0 && depth_w > 0 && depth_h > 0) { + int2 dc = int2( + int(min((tid.x * depth_w) / max(width, 1u), depth_w - 1)), + int(min((tid.y * depth_h) / max(height, 1u), depth_h - 1)) + ); + int2 maxc = int2(int(depth_w) - 1, int(depth_h) - 1); + ao = horizon_crease_ao(tid.xy, dc, maxc); + } + float3 amb_ao = amb * ao; + float3 existing = unpack_r9g9b9e5(out_uav[tid.xy]); + if (!all(isfinite(existing))) existing = float3(0.0, 0.0, 0.0); + float amb_lum = max(dot(amb, float3(0.2126, 0.7152, 0.0722)), 0.02); + float cap_lum = 6.0 * amb_lum; + float cur_lum = dot(existing, float3(0.2126, 0.7152, 0.0722)); + if (cur_lum > cap_lum) { + existing *= (cap_lum / max(cur_lum, 1e-6)); + } + out_uav[tid.xy] = pack_r9g9b9e5(max(existing, amb_ao)); +} +"#; + /// Write-only fallback for `TemporalResolve` when typed UAV load is unsupported on `out_uav`. const AMBIENT_FILL_WRITE_HLSL: &str = r#" Texture2D depth_tex : register(t0); @@ -764,6 +859,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let reduce_bc = compile_cs_sm5(SKY_REDUCE_HLSL)?; let fill_bc = compile_cs_sm5(AMBIENT_FILL_HLSL)?; let fill_write_bc = compile_cs_sm5(AMBIENT_FILL_WRITE_HLSL)?; + let fill_r9_bc = compile_cs_sm5(AMBIENT_FILL_R9G9B9E5_HLSL)?; let reflect_bc = compile_cs_sm5(REFLECT_CLAMP_HLSL)?; let air_bc = compile_cs_sm5(AIR_CAP_HLSL)?; @@ -856,6 +952,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { let reduce_pso = make_cs(&reduce_bc)?; let fill_pso = make_cs(&fill_bc)?; let fill_write_pso = make_cs(&fill_write_bc)?; + let fill_r9_pso = make_cs(&fill_r9_bc)?; let reflect_pso = make_cs(&reflect_bc)?; let air_pso = make_cs(&air_bc)?; @@ -927,6 +1024,7 @@ unsafe fn build_device(dev: &ID3D12Device) -> Option { reduce_pso, fill_pso, fill_write_pso, + fill_r9_pso, reflect_pso, air_pso, sky_copy, @@ -1154,6 +1252,7 @@ unsafe fn scan_cbv_indices(va: usize, max_bytes: usize, push_idx: &mut impl FnMu /// (`view_heap_base`), and root/table CBVs to locate its output float UAV (2D screen-space or /// 3D froxel volume when `want_3d` is true) and optional depth SRV for crease AO. unsafe fn find_dispatch_views( + role: PassRole, layout: &Layout, args: &[u8], groups: [u32; 3], @@ -1259,7 +1358,7 @@ unsafe fn find_dispatch_views( let scored = if want_3d { score_volume_target(&rd, ve.fmt, groups).map(|s| (s, rd.DepthOrArraySize as u32)) } else { - score_dispatch_target(&rd, ve.fmt, groups).map(|s| (s, 1u32)) + score_dispatch_target_for_role(role, &rd, ve.fmt, groups).map(|s| (s, 1u32)) }; if let Some((score, depth)) = scored { if uav_hit.is_none_or(|(best, _, _, _, _, _)| score < best) { @@ -1352,7 +1451,7 @@ pub(super) unsafe fn after_compute_dispatch( } let want_3d = role == PassRole::InscatteringVolume; - let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(layout, args, groups, view_heap_base, want_3d); + let (uav_opt, depth_opt, n_tables, n_indices, n_cbvs) = find_dispatch_views(role, layout, args, groups, view_heap_base, want_3d); let Some((uav_res, uav_fmt, w, h, d)) = uav_opt else { static MISS: AtomicU64 = AtomicU64::new(0); if MISS.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1431,7 +1530,13 @@ pub(super) unsafe fn after_compute_dispatch( let (pso, consts, disp) = match role { PassRole::TemporalResolve => ( - if can_typed_load { ad.fill_pso.as_raw() } else { ad.fill_write_pso.as_raw() }, + if uav_fmt == 42 { + ad.fill_r9_pso.as_raw() + } else if can_typed_load { + ad.fill_pso.as_raw() + } else { + ad.fill_write_pso.as_raw() + }, [w, h, depth_w, depth_h, has_depth, cfg.ao.to_bits(), sky_ready as u32, cfg.least.to_bits()], (w.div_ceil(8), h.div_ceil(8), 1), ), @@ -1543,10 +1648,35 @@ mod tests { assert!(compile_cs_sm5(SKY_REDUCE_HLSL).is_some(), "SKY_REDUCE_HLSL failed D3DCompile"); assert!(compile_cs_sm5(AMBIENT_FILL_HLSL).is_some(), "AMBIENT_FILL_HLSL failed D3DCompile"); assert!(compile_cs_sm5(AMBIENT_FILL_WRITE_HLSL).is_some(), "AMBIENT_FILL_WRITE_HLSL failed D3DCompile"); + assert!(compile_cs_sm5(AMBIENT_FILL_R9G9B9E5_HLSL).is_some(), "AMBIENT_FILL_R9G9B9E5_HLSL failed D3DCompile"); assert!(compile_cs_sm5(REFLECT_CLAMP_HLSL).is_some(), "REFLECT_CLAMP_HLSL failed D3DCompile"); assert!(compile_cs_sm5(AIR_CAP_HLSL).is_some(), "AIR_CAP_HLSL failed D3DCompile"); } + #[test] + fn temporal_resolve_targets_r32_uint_and_never_hdr_scene_color() { + let hdr_scene = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 2560, + Height: 1440, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R11G11B10_FLOAT, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let r9_probe = D3D12_RESOURCE_DESC { + Format: DXGI_FORMAT_R32_TYPELESS, + ..hdr_scene + }; + assert!(score_dispatch_target_for_role(PassRole::TemporalResolve, &hdr_scene, DXGI_FORMAT_R11G11B10_FLOAT.0, [320, 360, 1]).is_none()); + assert!(score_dispatch_target_for_role(PassRole::TemporalResolve, &hdr_scene, DXGI_FORMAT_R16G16B16A16_FLOAT.0, [320, 360, 1]).is_none()); + assert!(score_dispatch_target_for_role(PassRole::TemporalResolve, &r9_probe, DXGI_FORMAT_R32_UINT.0, [320, 360, 1]).is_some()); + assert!(score_dispatch_target_for_role(PassRole::ReflectionHistory, &r9_probe, DXGI_FORMAT_R32_UINT.0, [320, 360, 1]).is_none()); + assert!(score_dispatch_target_for_role(PassRole::ReflectionHistory, &hdr_scene, DXGI_FORMAT_R11G11B10_FLOAT.0, [320, 360, 1]).is_some()); + } + #[test] fn inscattering_volume_classification_volume_scoring_and_time_based_settling() { assert_eq!( @@ -1557,7 +1687,7 @@ mod tests { let def = Config::default(); assert!((def.settle_ms - 250.0).abs() < 1e-6); - assert!((def.air - 1.5).abs() < 1e-6); + assert!((def.air - 0.0).abs() < 1e-6); // First capture or settle_ms == 0 snaps immediately; subsequent samples follow 1 - exp(-dt/tau). assert_eq!(settle_alpha(0.016, 250.0, true), 1.0); diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 0eefbd460f..38e204fafc 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -1276,15 +1276,36 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, } /// `XCL_FRAME_DUMP=1`: every 120th shown frame is written to the logs folder (`XCL_FRAME_DUMP=n`, -/// n > 1: every n-th; a title loading at a few frames a second shows few) +/// n > 1: every n-th; a title loading at a few frames a second shows few). +/// `XCL_FRAME_DUMP_FROM=k`: suppress dumps before frame `k`; when set alongside `XCL_FRAME_DUMP=1`, +/// dumps every frame from `k` onward so world frames can be inspected without dumping loading screens. /// (`frame_.bmp`, a quarter of each side; `XCL_FRAME_DUMP_FULL=1`: full size) – what the title presented, before the window. fn frame_dump_due() -> bool { + static FROM: std::sync::OnceLock = std::sync::OnceLock::new(); + let from = *FROM.get_or_init(|| std::env::var("XCL_FRAME_DUMP_FROM").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)); static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); let every = *EVERY.get_or_init(|| match std::env::var("XCL_FRAME_DUMP") { - Ok(v) => v.parse().ok().filter(|&n| n > 1).unwrap_or(120), + Ok(v) => { + let n = v.trim().parse::().ok(); + if from > 0 && n == Some(1) { + 1 + } else { + n.filter(|&n| n > 1).unwrap_or(120) + } + } Err(_) => 0, }); - every > 0 && PRESENTS.load(Ordering::Relaxed) % every == 20.min(every - 1) + if every == 0 { + return false; + } + let cur = PRESENTS.load(Ordering::Relaxed); + if cur < from { + return false; + } + if every == 1 { + return true; + } + cur % every == 20.min(every - 1) } /// Frames shown so far. From c093211ed37007093d7b34a2be8e7338145bc2da Mon Sep 17 00:00:00 2001 From: Greem Date: Thu, 26 Nov 2026 11:58:06 +0100 Subject: [PATCH 202/258] D3D12.X: a placed view's padding does not make a second texture `prepare_placed_srv_desc` and `prepare_placed_uav_desc` key `placed_srvs` / `placed_uavs` by (address, 0x38-byte console resource description) and clear only 0x34.. of it. Bytes 0x04..0x08 are the padding between `Dimension` and `Alignment`; the retail title leaves stack bytes there, so the same view at the same address made a second PC texture (and its views) whenever that padding differed. Both now clear it too. Measured on the retail title (RX 7900 XT, RADV, Wine, amd-dev b5c0275 with the Wine stack), one 200 s run each: `placed_srvs` held 60,925 entries at 190 s without the change and 41,965 with it (-31 %); the same share as main's `resource_at` (#2743, fixed there by #2762). Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/format_alias.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/format_alias.rs b/crates/xcl/src/hle/d3d12x/format_alias.rs index dfb1f15b27..b601fc8f52 100644 --- a/crates/xcl/src/hle/d3d12x/format_alias.rs +++ b/crates/xcl/src/hle/d3d12x/format_alias.rs @@ -186,6 +186,9 @@ pub(super) fn uav_resource_format(rdesc_fmt: u32, view_fmt: u32) -> u32 { /// `ALLOW_UNORDERED_ACCESS` and a UAV-compatible format so PC D3D12 never drops it to a null view. pub(super) fn prepare_placed_uav_desc(rdesc: &[u8; 0x38], view_fmt: u32) -> [u8; 0x38] { let mut x = *rdesc; + // the padding between `Dimension` and `Alignment` (the title leaves stack bytes there): one + // key per view, not one per padding value + x[0x04..0x08].fill(0); x[0x34..].fill(0); let rdesc_fmt = u32::from_le_bytes(x[0x20..0x24].try_into().unwrap()); let mut flags = u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()); @@ -208,6 +211,7 @@ pub(super) fn prepare_placed_uav_desc(rdesc: &[u8; 0x38], view_fmt: u32) -> [u8; /// retire or overwrite GPU-owned target tracking at `va`. pub(super) fn prepare_placed_srv_desc(rdesc: &[u8; 0x38], view_fmt: u32) -> [u8; 0x38] { let mut x = *rdesc; + x[0x04..0x08].fill(0); x[0x34..].fill(0); let rdesc_fmt = u32::from_le_bytes(x[0x20..0x24].try_into().unwrap()); let mut flags = u32::from_le_bytes(x[0x30..0x34].try_into().unwrap()); @@ -1487,6 +1491,22 @@ mod tests { assert_eq!(srv_flags & (FLAG_RENDER_TARGET | FLAG_UAV), 0); } + #[test] + fn placed_descs_ignore_the_padding_after_dimension() { + // bytes 0x04..0x08 are the padding between `Dimension` and `Alignment`; the title leaves + // stack bytes there, and a different value must not make a second key for the same view + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + x[0x10..0x18].copy_from_slice(&256u64.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&256u32.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); // R8G8B8A8_UNORM + let mut garbage = x; + garbage[0x04..0x08].copy_from_slice(&[0xd8, 0x7e, 0x3f, 0x01]); + assert_eq!(prepare_placed_srv_desc(&garbage, 28), prepare_placed_srv_desc(&x, 28)); + assert_eq!(prepare_placed_uav_desc(&garbage, 28), prepare_placed_uav_desc(&x, 28)); + assert_eq!(prepare_placed_srv_desc(&garbage, 28)[0x04..0x08], [0u8; 4]); + } + #[test] fn alias_table_links_in_both_creation_orders() { let mut t = AliasTable::new(); From 53995420bd3e7d6ea39f0e362fd5a8d4781c37b3 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:06:04 +0300 Subject: [PATCH 203/258] DXIL: trigger compact form on branch-heavy shaders to prevent driver compile commit spikes compact::large() previously only checked reachable non-terminator instruction count (>= 20_000), ignoring both terminating branches and basic-block count. Branch-heavy unrolled compute shaders just below 20k non-terminator instructions (for example, cs 56c0cd3b82a00c6e) skipped compact lowering and emitted >2.6 MiB monolithic DXIL (~588k IR lines, ~32k blocks, ~36k PHIs), causing the driver compiler to commit >36 GiB of virtual memory and stall compilation. In compact form the same shader shrinks to ~160 KiB (~975 blocks, 108 PHIs). Lower the non-terminator threshold to 10_000 and add a reachable basic-block threshold (>= 2_000) in compact::large(); compact::wanted() still gates adoption on >70% deduplication and bounded table size. --- crates/xcl/src/gpu/dxil/compact.rs | 11 ++++++++++- crates/xcl/src/gpu/dxil/compact_tests.rs | 6 +++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 6da31c6425..618e7b3004 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -254,9 +254,18 @@ pub fn wanted(cfg: &Cfg, p: &Plan) -> bool { large(cfg) && once * 10 < all * 3 && p.words() <= MAX_TABLE_WORDS } +/// Reachable non-terminator instruction count threshold for trying the compact form. +const LARGE_INSTS: usize = 10_000; +/// Reachable basic-block count threshold for trying the compact form: branch-heavy +/// unrolled programs with thousands of small blocks (even below `LARGE_INSTS` +/// non-terminator instructions) expand into tens of thousands of DXIL blocks and PHIs +/// in plain form, causing excessive driver-compiler memory commit spikes. +const LARGE_BLOCKS: usize = 2_000; + /// Whether a program is large enough for `wanted` to be asked. pub fn large(cfg: &Cfg) -> bool { - cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= 20_000 + cfg.rpo.len() >= LARGE_BLOCKS + || cfg.rpo.iter().map(|&b| cfg.blocks[b].insts.len()).sum::() >= LARGE_INSTS } pub const END: u32 = u32::MAX; diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index bdf4da66e8..6fbd19c699 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -49,7 +49,11 @@ fn a_large_program_that_repeats_itself_takes_the_compact_form() { return; } let o = KernelOptions { wave64: true, split: true, mem_windows: 1, sampler_base: 0 }; - for (copies, compact) in [(2500, true), (2000, false)] { + // `repeated(copies)` has 4 basic blocks and 9 non-terminator instructions per copy: + // - 2500 copies (10k blocks, 22.5k insts) and 500 copies (2k blocks, 4.5k insts) cross + // the compact threshold and take the compact form; + // - 400 copies (1.6k blocks, 3.6k insts) stay below both thresholds and keep plain form. + for (copies, compact) in [(2500, true), (500, true), (400, false)] { assert_eq!(translate_full(&repeated(copies), o).unwrap().dxil.len(), size(copies, o, compact), "{copies} copies"); } } From c64ac897acf57b91d281f9efba44d83469171d66 Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:46:59 +0300 Subject: [PATCH 204/258] D3D12.X: invalidate sparse watch ranges when commit_range unmasks a VRAM-only tile --- crates/xcl/src/hle/d3d12x/sparse.rs | 83 +++++++++++++++++++++++------ 1 file changed, 66 insertions(+), 17 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index c6ffa489b0..d65556100d 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1749,27 +1749,49 @@ pub unsafe fn decommitted(a: usize, n: usize) { s.decommit_range(a, n); } +/// Clear per-page hole bits in `[a, a + n)` for already-mapped tiles; if any VRAM-only tile +/// transitions from all-holes (`0xFFFF`) to watchable (`!= 0xFFFF`), invalidate cached watchable +/// tile runs and bump `MAPPED_GEN`. +fn unmask_committed_holes( + mapped: &mut FxHashMap, + runs: &mut Option>, + a: usize, + n: usize, +) -> bool { + let mut pg = a & !(PAGE - 1); + let end = a.saturating_add(n); + let mut unmasked = false; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = t.saturating_add(TILE).min(end); + if let Some(entry) = mapped.get_mut(&t) { + let was_all_holes = entry.holes == 0xFFFF; + let mut p = pg; + while p < tile_end { + entry.holes &= !(1u16 << ((p - t) / PAGE)); + p += PAGE; + } + if was_all_holes && entry.holes != 0xFFFF { + unmasked = true; + } + } + if tile_end <= pg { + break; + } + pg = tile_end; + } + if unmasked { + *runs = None; + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + unmasked +} + impl State { /// `committed` with the state locked unsafe fn commit_range(&mut self, a: usize, n: usize) { self.ensure_mapped(a, n, |_| 0xFFFF); - let mut pg = a & !(PAGE - 1); - let end = a.saturating_add(n); - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = t.saturating_add(TILE).min(end); - if let Some(entry) = self.mapped.get_mut(&t) { - let mut p = pg; - while p < tile_end { - entry.holes &= !(1u16 << ((p - t) / PAGE)); - p += PAGE; - } - } - if tile_end <= pg { - break; - } - pg = tile_end; - } + unmask_committed_holes(&mut self.mapped, &mut self.runs, a, n); } /// Clear hole masks for 64 KiB tiles lazily CPU-committed by `kernelx::lazy` (#2582). @@ -3488,4 +3510,31 @@ mod tests { assert_ne!(VirtualFree(tile as *mut c_void, 0, MEM_RELEASE), 0); } } + + #[test] + fn commit_range_unmasking_vram_only_tile_invalidates_runs_and_gen() { + let mut mapped: FxHashMap = FxHashMap::default(); + let t0 = 0x2000_0000usize; + mapped.insert(t0, TileEntry::with_holes((0, 0), 0xFFFF)); + + // Prime cached watchable runs while tile is VRAM-only (all holes). + let mut runs = Some(watchable_tile_runs(&mapped)); + assert_eq!(runs, Some(Vec::new())); + + let gen_before = MAPPED_GEN.load(Ordering::Acquire); + assert!(unmask_committed_holes(&mut mapped, &mut runs, t0, PAGE)); + assert_eq!(mapped[&t0].holes, 0xFFFE); + assert!(runs.is_none(), "cached runs must be invalidated when a VRAM-only tile becomes watchable"); + assert!(MAPPED_GEN.load(Ordering::Acquire) > gen_before, "MAPPED_GEN must increment on unmask"); + + // Recomputing watchable runs now includes the unmasked tile. + let recomputed = watchable_tile_runs(&mapped); + assert_eq!(recomputed, vec![(t0, t0 + TILE)]); + + // A subsequent page commit on an already-watchable tile does not spuriously invalidate runs. + runs = Some(recomputed); + assert!(!unmask_committed_holes(&mut mapped, &mut runs, t0 + PAGE, PAGE)); + assert_eq!(mapped[&t0].holes, 0xFFFC); + assert!(runs.is_some()); + } } From aa9d48de7a3b7f866e1d1c34e96ee0258bcccca1 Mon Sep 17 00:00:00 2001 From: itsSio <31954644+itsSio@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:00:09 +0100 Subject: [PATCH 205/258] Recompiler: Wave32 pixel mask writes kill one SGPR, not a pair In a Wave32 pixel shader a VALU mask write (a carry or compare SDST) and a scalar SAVEEXEC / WREXEC write one dword: write_mask calls write32 when the program is not wave64. The liveness that decides whether a mask needs the helper lanes' quad reads (x64_masks) took its kill sets from the ISA tables, which describe the wave64 pair. So `v_add_co_u32 v3, s20, ...` was taken to overwrite s21 as well; an earlier carry into s21 that `v_bcnt_u32_b32 v4, s21, 0` reads later was taken for a lane-local mask and built with ballot_px_local, and with WQM on its helper lanes' bits were missing at triangle edges (#2584). For Wave32 pixel shaders those writes now kill one dword, and a mask write takes the full ballot when either this liveness or the existing pair rule says its destination can be read whole, so no mask that took the full ballot before loses it. Split wave64 and wave64 pixel shaders keep the pair rule; the direct DXIL path (by_pc) is unchanged. Tests: x64_masks::tests::wave32_carry_into_s20_preserves_a_whole_read_of_s21 and gpu_wave32_pixel_carry_preserves_adjacent_mask_at_triangle_edges, which draws the issue's program on two triangles. Fix and tests by akimfomin (akimfomin/xcl@d3e7725), carried onto main without its README line. Refs xcl-dev/xcl#2584 Co-authored-by: akimfomin Assisted-by: Google Antigravity CLI (Claude Opus 5.5 (High)) --- crates/xcl/src/gpu/recomp/emit.rs | 11 ++-- crates/xcl/src/gpu/recomp/mod.rs | 4 +- crates/xcl/src/gpu/recomp/tests.rs | 39 ++++++++++++++ crates/xcl/src/gpu/recomp/x64_masks.rs | 73 ++++++++++++++++++++++++-- 4 files changed, 115 insertions(+), 12 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index e2e184eacb..379d4e014a 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -46,10 +46,9 @@ pub(super) struct Em { /// split wave64 (`x64`): words one exchange carries (1: masks and lane reads, up to 16: /// coherent scalar loads, 32: `ds_bpermute`) x64_words: usize, - /// split wave64 and pixel shaders: pc → SGPRs whose whole value may be read after that - /// instruction (`x64_masks`); a mask written to none of them is only read lane by lane - /// (split: stays in its half, no exchange; pixel: no quad reads for the helper lanes) - pub mask_whole_live: BTreeMap, + /// Mask-producing instruction PC and starting SGPR destinations that require + /// full reconstruction (split-wave exchange or pixel helper quad reads). + pub full_mask_destinations: BTreeMap, /// wave64 VS / PS on a GPU with 32-lane waves only: what the console's lanes 32..63 hold /// where the program reads them (`upper_lanes`), used when the wave has 32 lanes pub upper: Option, @@ -633,7 +632,7 @@ impl Em { uses_lds: false, uses_scratch: false, x64_words: 1, - mask_whole_live: BTreeMap::new(), + full_mask_destinations: BTreeMap::new(), upper: None, cur_pc: 0, static_ss: BTreeMap::new(), @@ -993,7 +992,7 @@ impl Em { // lane (the half's own word, the lane's own bit are enough), that goes nowhere, or that // is 0 in every lane anyway let local = match *dst { - Dst::S(n) => n < 126 && self.mask_whole_live.get(&self.cur_pc).is_some_and(|live| live & (3u128 << n) == 0), + Dst::S(n) => n < 126 && self.full_mask_destinations.get(&self.cur_pc).is_some_and(|live| live & (1u128 << n) == 0), Dst::Null => true, Dst::V(_) => false, }; diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 1cbdd39519..589219b1e6 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1761,9 +1761,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // continues from the ES into the GS through s_setpc: left as it is); pixel shaders: they // skip the quad reads that give the helper lanes' bits if opt.wave64 && opt.split_wave64 && matches!(opt.mode, Mode::Kernel | Mode::Compute(_) | Mode::Mesh(_)) && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { - em.mask_whole_live = x64_masks::by_pc(&insts, matches!(opt.mode, Mode::Kernel)); + em.full_mask_destinations = x64_masks::full_mask_destinations(&insts, matches!(opt.mode, Mode::Kernel), true); } else if matches!(opt.mode, Mode::Pixel(_)) { - em.mask_whole_live = x64_masks::by_pc(&insts, false); + em.full_mask_destinations = x64_masks::full_mask_destinations(&insts, false, opt.wave64); } // a wave64 VS / PS on a GPU that can run 32-lane waves: what lanes 32..63 hold where the // program reads them (the driver may still pick 64 lanes: decided at run time); only a diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 2b4200a73e..5bb42de654 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1813,6 +1813,45 @@ fn el(name: &str, index: u32, sv: u32, ct: u32, reg: u32, mask: u8) -> crate::gp crate::gpu::dxbc::SigElement { name: name.into(), index, system_value: sv, component_type: ct, register: reg, mask, rw_mask: mask, stream: 0 } } +#[test] +fn gpu_wave32_pixel_carry_preserves_adjacent_mask_at_triangle_edges() { + if !gpu_ready() { + return; + } + use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32_FLOAT; + // GFX1030 wave32. Expected green counts the odd lanes of WQM EXEC. Red + // counts the same lanes through s21, after writing the neighboring s20. + let words: &[u32] = &[ + 0xbefe097e, // s_wqm_b32 exec_lo, exec_lo + 0x8706ff7e, 0xaaaaaaaa, // s_and_b32 s6, exec_lo, 0xaaaaaaaa + 0xbe870f06, // s_bcnt1_i32_b32 s7, s6 + 0xd7650002, 0x020100c1, // v_mbcnt_lo_u32_b32 v2, -1, 0 + 0x36040481, // v_and_b32 v2, 1, v2 + 0xd70f1503, 0x020204c1, // v_add_co_u32 v3, s21, -1, v2 + 0xd70f1403, 0x02020480, // v_add_co_u32 v3, s20, 0, v2 + 0xd7640004, 0x02010015, // v_bcnt_u32_b32 v4, s21, 0 + 0x7e080d04, 0x7e0a0c07, 0x7e0c02f2, // convert v4 and s7 to float, set v6 to 1.0 + 0xf800180f, 0x06060504, 0xbf810000, // exp mrt0 v4, v5, v6, v6 done vm; end + ]; + let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + let ps = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 15)], + outputs: vec![el("SV_Target", 0, 64, 3, 0, 15)], input_ena: 0x300, attrs: None }; + let t = translate(&code, &Options { wave64: false, mode: Mode::Pixel(ps), ..Default::default() }).unwrap(); + assert!(t.complete(), "{:?}", t.unsupported_why); + let ps = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap(); + let vs = super::dxc::compile("float4 main(float2 p:POSITION):SV_Position { return float4(p,0.5,1); }", + "main", "vs_6_6", &[]).unwrap(); + let layout = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32_FLOAT, offset: 0 }]; + let triangles = [-1.,-1., 1.,-1., -1.,1., 1.,-1., 1.,1., -1.,1.]; + let pixels = runner::draw(&vs, &ps, &layout, &triangles, 8, &[], &[], 32, [-99.; 4]).unwrap(); + assert_eq!(pixels.len(), 1024); + for (i, c) in pixels.iter().enumerate() { + assert_eq!((c[2], c[3]), (1., 1.), "raster coverage at {i}"); + assert!((1.0..=16.0).contains(&c[1]), "odd active lanes at {i}: {c:?}"); + assert_eq!(c[0], c[1], "mask popcount at {i}"); + } +} + /// VS + PS pair recompiled to graphics stages and drawn on the GPU: VS inputs from the /// fetch-shader VGPRs, exp pos0/param0, PS interpolation through v_interp, discard via v_cmpx. #[test] diff --git a/crates/xcl/src/gpu/recomp/x64_masks.rs b/crates/xcl/src/gpu/recomp/x64_masks.rs index 7796017f78..bd523b7a86 100644 --- a/crates/xcl/src/gpu/recomp/x64_masks.rs +++ b/crates/xcl/src/gpu/recomp/x64_masks.rs @@ -411,7 +411,20 @@ struct Block { has_exit: bool, } -fn whole_live_out_unsorted(insts: &[Decoded], end_reads_all: bool, table: &UsePlanTable) -> Vec { +/// Pixel VALU mask writes and scalar saveexec/wrexec write one dword in +/// XCL's wave32 lowering. The instruction tables describe their wave64 pairs. +/// Dropping a neighboring kill is conservative if two destinations touch. +fn liveness_uses(d: &Decoded, table: &UsePlanTable, wave64: bool) -> (Regs, Regs) { + let (whole, written) = uses_with_table(d, table); + let name = d.inst.name; + if !wave64 && (name.starts_with("V_") || name.contains("SAVEEXEC") || name.contains("WREXEC")) { + (whole, written & !(written << 1)) + } else { + (whole, written) + } +} + +fn whole_live_out_unsorted(insts: &[Decoded], end_reads_all: bool, table: &UsePlanTable, wave64: bool) -> Vec { let pcs: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); let at_end = if end_reads_all { ALL } else { EXEC }; let succ: Vec>> = insts @@ -442,7 +455,7 @@ fn whole_live_out_unsorted(insts: &[Decoded], end_reads_all: bool, table: &UsePl .iter() .map(|d| loops.iter().filter(|&&(a, b)| a <= d.pc && d.pc < b).map(|&(_, b)| pcs.range(b..).next().map(|(_, &j)| j)).collect()) .collect(); - let gen_kill: Vec<(Regs, Regs)> = insts.iter().map(|d| uses_with_table(d, table)).collect(); + let gen_kill: Vec<(Regs, Regs)> = insts.iter().map(|d| liveness_uses(d, table, wave64)).collect(); let mut live_in = vec![0 as Regs; insts.len()]; let mut live_out = vec![0 as Regs; insts.len()]; loop { @@ -528,13 +541,17 @@ fn nested_loop_ranges(mut raw: Vec<(u64, u64)>) -> Vec<(u64, u64)> { /// For each instruction (index in `insts`): the SGPRs whose whole value may be read after it. /// `end_reads_all`: the program's end reads every SGPR (kernel mode). pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { + whole_live_out_for_width(insts, end_reads_all, true) +} + +fn whole_live_out_for_width(insts: &[Decoded], end_reads_all: bool, wave64: bool) -> Vec { let n = insts.len(); if n == 0 { return Vec::new(); } let table = use_plans(); if !insts.windows(2).all(|w| w[0].pc < w[1].pc) { - return whole_live_out_unsorted(insts, end_reads_all, table); + return whole_live_out_unsorted(insts, end_reads_all, table, wave64); } let at_end = if end_reads_all { ALL } else { EXEC }; @@ -602,7 +619,7 @@ pub fn whole_live_out(insts: &[Decoded], end_reads_all: bool) -> Vec { } let num_blocks = block_starts.len(); - let gen_kill: Vec<(Regs, Regs)> = insts.iter().map(|d| uses_with_table(d, table)).collect(); + let gen_kill: Vec<(Regs, Regs)> = insts.iter().map(|d| liveness_uses(d, table, wave64)).collect(); // Summarize each basic block: because `(X & !k) | X == X` for bitmasks, the constant // per-block `left | EXEC` term collapses out of the intra-block composition into: @@ -756,6 +773,22 @@ pub fn by_pc(insts: &[Decoded], end_reads_all: bool) -> BTreeMap { insts.iter().map(|d| d.pc).zip(whole_live_out(insts, end_reads_all)).collect() } +/// Bit n blocks a local ballot for a mask written at SGPR n. Keep the original +/// pair-wide admission rule. A Wave32 pixel mask also needs the full ballot +/// when its actual single output word can still be observed as a whole. +pub fn full_mask_destinations(insts: &[Decoded], end_reads_all: bool, wave64: bool) -> BTreeMap { + let mut blocked = whole_live_out(insts, end_reads_all); + for bits in &mut blocked { + *bits |= *bits >> 1; + } + if !wave64 { + for (veto, actual) in blocked.iter_mut().zip(whole_live_out_for_width(insts, end_reads_all, false)) { + *veto |= actual; + } + } + insts.iter().map(|d| d.pc).zip(blocked).collect() +} + #[cfg(test)] mod tests { use super::*; @@ -858,6 +891,38 @@ mod tests { const BCNT_S20: I = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 20)]); const BCNT_VCC: I = ("S_BCNT1_I32_B64", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 106)]); + #[test] + fn wave32_carry_into_s20_preserves_a_whole_read_of_s21() { + let carry = |dst| rdna2::encode("V_ADD_CO_U32", "VOP3_SDST_ENC", + &[("VDST", 3), ("SDST", dst), ("SRC0", 193), ("SRC1", V + 2)], None).unwrap(); + let mut code = carry(21); + code.extend(carry(20)); + code.extend(rdna2::encode("V_BCNT_U32_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 21), ("SRC1", 128)], None).unwrap()); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let p = program(&code); + assert_ne!(full_mask_destinations(&p, false, false)[&p[0].pc] & (1 << 21), 0); + assert_eq!(liveness_uses(&p[1], use_plans(), true).1, 3 << 20); + assert_eq!(liveness_uses(&p[1], use_plans(), false).1, 1 << 20); + + // A neighbor live across a second write to s20 did not observe s20. + // An unconditional branch makes the read a distinct successor block. + let mut other = carry(20); + other.extend(carry(20)); + other.extend(rdna2::encode("S_BRANCH", "ENC_SOPP", &[("SIMM16", 1)], None).unwrap()); + other.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + other.extend(rdna2::encode("V_BCNT_U32_B32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 21), ("SRC1", 128)], None).unwrap()); + other.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let q = program(&other); + assert_ne!(whole_live_out_for_width(&q, false, false)[0] & (1 << 21), 0); + let blocked = full_mask_destinations(&q, false, false); + assert_eq!(blocked[&q[0].pc] & (1 << 20), 0); + assert_ne!(blocked[&q[1].pc] & (1 << 20), 0, "retain the original conservative refusal"); + + // An actual scalar pair write still kills both words at either width. + let scalar = asm(&[("S_MOV_B64", "ENC_SOP1", &[("SDST", 20), ("SSRC0", 128)])]); + assert_eq!(liveness_uses(&scalar[0], use_plans(), false).1, 3 << 20); + } + // review findings: writes that are not full overwrites, reads the operand tables miss #[test] From 8739581386b2a24e1598b092d5311677217d55cd Mon Sep 17 00:00:00 2001 From: MacieGx Date: Thu, 26 Nov 2026 13:28:56 +0100 Subject: [PATCH 206/258] D3D12.X: stencil views get a uint T# format, so shaders load them as integers The PC's stencil view formats, X24_TYPELESS_G8_UINT and X32_TYPELESS_G8X24_UINT, are not in the GFX10 format table, so `view_shape_desc` gave their T# format 0. Translated shaders pick the image's class from that format (`img_cls`), and 0 is the float class: an image_load of a stencil view became a float load of a UINT view, which D3D12 leaves undefined. These views now get 8_UINT. In the newer retail title (#505) the material classification reads the G-buffer stencil and a D16S8 mask buffer's stencil through such views from compute (tiled lighting, subsurface tiles, final gather). The kernel test runner can now make a stencil test texture: a D2 texture in a stencil view format is a depth-stencil buffer whose stencil plane holds the data, with its SRV on plane 1. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/recomp/runner.rs | 34 +++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 92 ++++++++++++++++++++++++++++- 2 files changed, 119 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 49cf68e923..b59e459f5c 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -158,7 +158,23 @@ impl TexDim { } } -/// A texture for kernel tests: SRV at heap index 2·i, UAV (if `uav`) at 2·i + 1. +/// The typeless depth-stencil format of a stencil view format (None: not a stencil view). +fn stencil_resource(view: DXGI_FORMAT) -> Option { + match view { + DXGI_FORMAT_X24_TYPELESS_G8_UINT => Some(DXGI_FORMAT_R24G8_TYPELESS), + DXGI_FORMAT_X32_TYPELESS_G8X24_UINT => Some(DXGI_FORMAT_R32G8X24_TYPELESS), + _ => None, + } +} + +/// The plane a test texture's data and SRV are in: 1 for a stencil view. +fn first_plane(t: &TestTexture) -> u32 { + u32::from(stencil_resource(t.format).is_some()) +} + +/// A texture for kernel tests: SRV at heap index 2·i, UAV (if `uav`) at 2·i + 1. A D2 texture in +/// a stencil view format (X24_TYPELESS_G8_UINT, X32_TYPELESS_G8X24_UINT) is a depth-stencil +/// buffer whose stencil plane holds `data` (one byte a texel); its SRV is that view of plane 1. pub struct TestTexture { pub dim: TexDim, pub format: DXGI_FORMAT, @@ -274,15 +290,21 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t Height: t.height, DepthOrArraySize: depth_or_array as u16, MipLevels: 1, - Format: t.format, + Format: stencil_resource(t.format).unwrap_or(t.format), SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Flags: if t.uav { D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS } else { D3D12_RESOURCE_FLAG_NONE }, + Flags: if t.uav { + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS + } else if stencil_resource(t.format).is_some() { + D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL + } else { + D3D12_RESOURCE_FLAG_NONE + }, ..Default::default() } }; let subs = if t.dim == TexDim::D3 { 1 } else { t.depth }; let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); subs as usize]; let mut size = 0u64; - dev.GetCopyableFootprints(&rd, 0, subs, total, Some(fps.as_mut_ptr()), None, None, Some(&mut size)); + dev.GetCopyableFootprints(&rd, first_plane(t), subs, total, Some(fps.as_mut_ptr()), None, None, Some(&mut size)); total = (total + size + 511) & !511; plans.push(fps); descs.push(rd); @@ -340,7 +362,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t list.CopyBufferRegion(&r, 0, upload.as_ref().unwrap(), fps[0].Offset, rd.Width); } for (k, fp) in fps.iter().enumerate().filter(|_| t.dim != TexDim::Buffer) { - let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 } }; + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(&r), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: first_plane(t) + k as u32 } }; let src = D3D12_TEXTURE_COPY_LOCATION { pResource: transmute_copy(upload.as_ref().unwrap()), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, @@ -361,7 +383,7 @@ unsafe fn bind_resources(dev: &ID3D12Device, list: &ID3D12GraphicsCommandList, t } TexDim::D2 => { sv.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; - sv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() }; + sv.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: 1, PlaneSlice: first_plane(t), ..Default::default() }; uv.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2D; } TexDim::D2Array => { diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 449ac5efaf..9a27949855 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -1246,7 +1246,7 @@ fn view_shape_desc( ) -> Option<(u32, crate::gpu::desc::ImageType, u32, u32, u32, u32, u32, u32)> { use crate::gpu::desc::ImageType as T; let f = if format == windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_UNKNOWN { r.Format } else { format }; - let fmt = crate::gpu::desc::gfx10_format(f).unwrap_or(0); + let fmt = view_tsharp_format(f); let (w, h, d) = (r.Width as u32, r.Height, r.DepthOrArraySize as u32); let ty = view_dim_to_image_type(dim)?; let depth = match ty { @@ -1272,6 +1272,16 @@ fn view_shape_desc( Some((fmt, ty, w, h, depth, base_level, last_level, max_mip)) } +/// The GFX10 format in the T# of a view in PC format `f` (0, a float image, when the table has +/// none). The PC's stencil views (X32_TYPELESS_G8X24_UINT, X24_TYPELESS_G8_UINT) are not in the +/// table but are UINT views: they get 8_UINT, so that translated shaders load them as integers +/// (`img_cls`); a float load of a UINT view is undefined in D3D12. +fn view_tsharp_format(f: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT) -> u32 { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UINT, DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT}; + let f = if f == DXGI_FORMAT_X24_TYPELESS_G8_UINT || f == DXGI_FORMAT_X32_TYPELESS_G8X24_UINT { DXGI_FORMAT_R8_UINT } else { f }; + crate::gpu::desc::gfx10_format(f).unwrap_or(0) +} + /// Build the XCL shader-ABI T# for an SRV, populating GFX10 `BASE_LEVEL` (`t[3][15:12]`), /// `LAST_LEVEL` (`t[3][19:16]`, or `log2(SampleDesc.Count)` for MSAA), and `MAX_MIP` (`t[5][7:4]`). fn srv_tsharp_from_desc(slot_index: u32, r: &D3D12_RESOURCE_DESC, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option<[u32; 8]> { @@ -8412,6 +8422,86 @@ mod pso_blend_and_tsharp_tests { let img_arr = crate::gpu::desc::image(&srv_tsharp_from_desc(11, &msaa_arr, Some(&msaa_arr_srv)).unwrap()).unwrap(); assert_eq!((img_arr.ty, img_arr.depth, img_arr.base_level, img_arr.last_level), (crate::gpu::desc::ImageType::D2MsaaArray, 4, 0, 2)); } + + /// A stencil view is a UINT view: its T# has a uint format, so translated shaders load it as + /// integers (`img_cls`: the buffer-format table's numeric type 4); the depth view stays float. + #[test] + fn srv_tsharp_of_a_stencil_view_has_a_uint_format() { + let class = |fmt: u32| (crate::gpu::recomp::emit::buf_format_info(fmt as usize) >> 3) & 7; + for (resource, stencil, depth) in [ + (DXGI_FORMAT_R24G8_TYPELESS, DXGI_FORMAT_X24_TYPELESS_G8_UINT, DXGI_FORMAT_R24_UNORM_X8_TYPELESS), + (DXGI_FORMAT_R32G8X24_TYPELESS, DXGI_FORMAT_X32_TYPELESS_G8X24_UINT, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS), + ] { + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 2560, + Height: 1440, + DepthOrArraySize: 1, + MipLevels: 1, + Format: resource, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let view = |format, plane| D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: format, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: plane, ResourceMinLODClamp: 0.0 }, + }, + }; + let s = crate::gpu::desc::image(&srv_tsharp_from_desc(5, &rd, Some(&view(stencil, 1))).unwrap()).unwrap(); + assert_eq!((s.format, class(s.format)), (5, 4), "stencil view {stencil:?}: T# format 8_UINT, uint class"); + assert_eq!((s.width, s.height), (2560, 1440)); + let d = crate::gpu::desc::image(&srv_tsharp_from_desc(6, &rd, Some(&view(depth, 0))).unwrap()).unwrap(); + assert_ne!(class(d.format), 4, "depth view {depth:?} stays a float image"); + } + } + + /// A translated `image_load` of a stencil view (the T# `srv_tsharp_from_desc` writes for it) + /// gives the stencil values: in the second component, as the PC view has them. + #[test] + fn gpu_image_load_of_a_stencil_view_gives_the_stencil() { + use crate::gpu::recomp::runner::{self, KernelState, TestTexture, TexDim}; + use crate::gpu::rdna2::encode; + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R24G8_TYPELESS, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + ..Default::default() + }; + let view = D3D12_SHADER_RESOURCE_VIEW_DESC { + Format: DXGI_FORMAT_X24_TYPELESS_G8_UINT, + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 1, PlaneSlice: 1, ResourceMinLODClamp: 0.0 } }, + }; + // the runner's SRV of texture 0 is at heap index 0 + let t = srv_tsharp_from_desc(0, &rd, Some(&view)).unwrap(); + let mut code = encode("IMAGE_LOAD", "ENC_MIMG", &[("VDATA", 10), ("VADDR", 0), ("SRSRC", 4), ("DMASK", 0x2), ("DIM", 1), ("UNORM", 1)], None).unwrap(); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let mut st = KernelState::default(); + st.sgpr[16..24].copy_from_slice(&t); + for (l, r) in st.vgpr.iter_mut().enumerate() { + r[0] = (l % 8) as u32; + r[1] = (l / 8) as u32; + } + let stencil: Vec = (0..64).map(|k| 0x40 + k as u8).collect(); + let tex = [TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_X24_TYPELESS_G8_UINT, width: 8, height: 8, depth: 1, texel_bytes: 1, data: stencil, uav: false }]; + let r = runner::run_code_with(&code, &st, &[], &tex, &[]).unwrap(); + let bad: Vec = (0..64).filter(|&l| r.vgpr[l][10] != 0x40 + l as u32).map(|l| format!("lane {l}: {:#x}", r.vgpr[l][10])).collect(); + assert!(bad.is_empty(), "image_load of a stencil view (want 0x40 + lane):\n{}", bad.join("\n")); + } } enum StreamPipeline { From 76f8c2b3d93827e2a86a2ae711211ec8036643af Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:55:15 +0300 Subject: [PATCH 207/258] D3D12.X: omit VRAM-only sparse tiles and GPU-written textures from write-watch ranges --- crates/xcl/src/hle/d3d12x/sparse.rs | 58 +++++++++++++++++---- crates/xcl/src/hle/d3d12x/title_textures.rs | 48 ++++++++++++++++- 2 files changed, 95 insertions(+), 11 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index d65556100d..f4412c58bb 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1802,11 +1802,19 @@ impl State { return; } let pages = std::mem::take(&mut *LAZY_COMMITS.lock().unwrap_or_else(|e| e.into_inner())); + let mut unmasked = false; for page in pages { if let Some(entry) = self.mapped.get_mut(&(page & !(TILE - 1))) { + if entry.holes == 0xFFFF { + unmasked = true; + } entry.holes = 0; } } + if unmasked { + self.runs = None; + MAPPED_GEN.fetch_add(1, Ordering::Release); + } } /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps @@ -2103,22 +2111,36 @@ fn collect_known_queue_ptrs(extra: Option<&ID3D12CommandQueue>) -> Vec<*mut c_vo raw_ptrs } +fn watchable_tile_runs(mapped: &FxHashMap) -> Vec<(usize, usize)> { + let mut tiles: Vec = mapped.iter().filter(|(_, e)| e.holes != 0xFFFF).map(|(&t, _)| t).collect(); + tiles.sort_unstable(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for t in tiles { + match runs.last_mut() { + Some(last) if last.1 == t => last.1 = t + TILE, + _ => runs.push((t, t + TILE)), + } + } + runs +} + +/// Drain any pending VEH lazy commits so `mapped_gen()` / `mapped_ranges()` include newly +/// CPU-committed tiles on the very first submit (zero-lock fast path when none are pending). +pub(super) fn drain_lazy_commits_if_pending() { + if HAS_LAZY_COMMITS.load(Ordering::Acquire) { + if let Some(s) = lock_state().as_mut() { + s.drain_lazy_commits(); + } + } +} + /// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write /// has to reach the GPU. pub fn mapped_ranges() -> Vec<(usize, usize)> { let mut g = lock_state(); let Some(s) = g.as_mut() else { return Vec::new() }; if s.runs.is_none() { - let mut tiles: Vec = s.mapped.keys().copied().collect(); - tiles.sort_unstable(); - let mut runs: Vec<(usize, usize)> = Vec::new(); - for t in tiles { - match runs.last_mut() { - Some(last) if last.1 == t => last.1 = t + TILE, - _ => runs.push((t, t + TILE)), - } - } - s.runs = Some(runs); + s.runs = Some(watchable_tile_runs(&s.mapped)); } s.runs.clone().unwrap_or_default() } @@ -3537,4 +3559,20 @@ mod tests { assert_eq!(mapped[&t0].holes, 0xFFFC); assert!(runs.is_some()); } + + #[test] + fn watchable_tile_runs_omits_vram_only_holes_until_unmasked() { + let mut mapped: FxHashMap = FxHashMap::default(); + let t0 = 0x1000_0000usize; + let t1 = t0 + TILE; + let t2 = t1 + TILE; + mapped.insert(t0, TileEntry::with_holes((0, 0), 0)); + mapped.insert(t1, TileEntry::with_holes((0, 1), 0xFFFF)); + mapped.insert(t2, TileEntry::with_holes((0, 2), 0x00FF)); + + assert_eq!(watchable_tile_runs(&mapped), vec![(t0, t0 + TILE), (t2, t2 + TILE)]); + + mapped.get_mut(&t1).unwrap().holes = 0; + assert_eq!(watchable_tile_runs(&mapped), vec![(t0, t2 + TILE)]); + } } diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d99fd7688..2e794c92fc 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -173,6 +173,14 @@ impl Table { false } + fn watchable_ranges(&self) -> Vec<(usize, usize)> { + self.by_res + .values() + .filter(|e| !e.gpu_written) + .map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)) + .collect() + } + /// Collect active textures that are pending or overlap any sorted dirty page in `dirty`, /// clearing `pending` on returned entries and returning `((res, was_pending) list, pending_cleared)`. fn dirty_and_pending(&mut self, dirty: &[usize], page: usize) -> (Vec<(usize, bool)>, usize) { @@ -631,6 +639,7 @@ pub fn note_gpu_write(res: usize) { }; if marked { STREAM_RECHECK.lock().unwrap().remove(&res); + TEXTURES_GEN.fetch_add(1, Ordering::Release); } } @@ -841,7 +850,7 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc> { // write-watched regions) only when the set of textures, tiles, or reservations changed. let mut regions = u.watch_regions(); regions.extend(crate::hle::kernelx::graphics_reservations()); - let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().by_res.values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); + let mut wanted = TEXTURES.lock().unwrap().watchable_ranges(); wanted.extend(super::sparse::mapped_ranges()); wanted.extend(super::sparse::gpu_view::sources()); // the sources of buffer mirrors: a draw copies only the pages written (`list_x::copy_written`) @@ -905,6 +914,7 @@ unsafe fn refresh_once(queue: *mut c_void) { recheck_gpu_view_sources(); let watch_t0 = std::time::Instant::now(); let mut page = 0x1000u32; + super::sparse::drain_lazy_commits_if_pending(); let ranges = cached_watch_ranges(u); let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); @@ -3650,4 +3660,40 @@ mod tests { assert_eq!(got.len(), 4096); assert_eq!((got[0], got[1], got[4095]), (0x11, 0x5A, 0xEE)); } + + #[test] + fn watchable_ranges_excludes_gpu_written_textures() { + let mut desc = [0u8; 0x38]; + desc[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + desc[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + desc[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + desc[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); // RGBA8 + desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + let tex = Arc::new(xg::Texture::new(&desc).unwrap()); + let span = (tex.size() as usize + 0xFFF) & !0xFFF; + + let mk = |va: usize, src: usize, gpu_written: bool| Entry { + device: 1, + va, + src, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written, + placed: false, + unmapped: false, + seq: 0, + }; + + let mut t = Table::new(); + t.insert(0x100, mk(0x1000_0000, 0x2000_0000, false)); + t.insert(0x200, mk(0x1010_0000, 0x2010_0000, true)); + assert_eq!(t.watchable_ranges(), vec![(0x2000_0000, 0x2000_0000 + span)]); + + assert!(t.mark_gpu_written(0x100)); + assert!(t.watchable_ranges().is_empty()); + } } From fe29b254aa2c157bb180f567709ff9e38b76926c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:50:52 +0100 Subject: [PATCH 208/258] tests: fill early_depth field in gpu_wave32_pixel_carry test --- crates/xcl/src/gpu/recomp/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 5bb42de654..914e2c69d1 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1835,7 +1835,7 @@ fn gpu_wave32_pixel_carry_preserves_adjacent_mask_at_triangle_edges() { ]; let code: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); let ps = super::PsInterface { inputs: vec![el("SV_Position", 0, 1, 3, 0, 15)], - outputs: vec![el("SV_Target", 0, 64, 3, 0, 15)], input_ena: 0x300, attrs: None }; + outputs: vec![el("SV_Target", 0, 64, 3, 0, 15)], input_ena: 0x300, attrs: None, early_depth: false }; let t = translate(&code, &Options { wave64: false, mode: Mode::Pixel(ps), ..Default::default() }).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); let ps = super::dxc::compile(&t.hlsl, "main", "ps_6_6", &[]).unwrap(); From 303f26d3b9a2a0b8914a1309002413b80eb55036 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 14:58:01 +0100 Subject: [PATCH 209/258] d3d12x: log DRED and stop promptly on sparse fence timeout or queue-drain device removal --- crates/xcl/src/hle/d3d12x/real.rs | 4 ++++ crates/xcl/src/hle/d3d12x/sparse.rs | 2 ++ 2 files changed, 6 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 9a27949855..85eb006bf4 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9333,6 +9333,7 @@ pub fn drain_gpu() { Err(e) => { crate::xlog_error!("D3D12 queue drain: {e}"); if matches!(e, FenceError::Removed(_)) { + log_device_removed(); return; } } @@ -9346,6 +9347,9 @@ pub fn drain_gpu() { Ok(value) => pending |= value < 1, Err(e) => { crate::xlog_error!("D3D12 queue drain: {e}"); + if matches!(e, FenceError::Removed(_)) { + log_device_removed(); + } return; } } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index f4412c58bb..0584cef8f6 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -865,6 +865,7 @@ impl State { windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); if self.fence.GetCompletedValue() < target { crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue()); + super::real::stop_if_device_removed(); } } @@ -1699,6 +1700,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { wait_target.1, wait_target.0.GetCompletedValue() ); + super::real::stop_if_device_removed(); job_idle = false; break; } From 253108c24e6b89a5c7fe5c9e84801512a07bed08 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:09:07 +0100 Subject: [PATCH 210/258] d3d12x/sparse: run GPU readbacks on dedicated rb_queue to eliminate title_qA->title_qB->sparse_q->title_qA circular deadlock --- crates/xcl/src/hle/d3d12x/sparse.rs | 144 ++++++++++++++++--- crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 5 + 2 files changed, 131 insertions(+), 18 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 0584cef8f6..fed215bf5b 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -219,9 +219,15 @@ struct State { value: u64, /// reusable auto-reset Win32 event for fence waits (no per-wait CreateEventW/CloseHandle) event: HANDLE, - /// fence signalled on title queues so `queue` waits before copying GPU writes back to CPU + /// dedicated readback queue (NEVER waited on by title queues, so waiting on title queues + /// here cannot form a circular GPU deadlock `title_qA -> title_qB -> sparse_q -> title_qA`) + rb_queue: ID3D12CommandQueue, + /// fence signalled on title queues so `rb_queue` waits before copying GPU writes back to CPU rb_fence: ID3D12Fence, rb_value: u64, + /// fence signalled on `rb_queue` for CPU-side readback completion waits + rb_done_fence: ID3D12Fence, + rb_done_value: u64, /// (window start, reserved buffer) of each sparse window windows: Vec<(usize, ID3D12Resource)>, /// video-memory pool heaps (None: given back, its index free for the next one) @@ -545,8 +551,10 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { } let made = (|| -> windows::core::Result { let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; let mut slots = Vec::with_capacity(UPLOAD_SLOTS); for _ in 0..UPLOAD_SLOTS { @@ -563,14 +571,18 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); let _ = queue.SetName(windows::core::w!("xcl sparse queue")); + let _ = rb_queue.SetName(windows::core::w!("xcl sparse readback queue")); Ok(State { dev: dev.clone(), queue, fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows, pools: Vec::new(), free: Vec::new(), @@ -869,6 +881,35 @@ impl State { } } + #[inline] + unsafe fn order_rb_after_uploads(&self) { + if self.value > 0 && self.fence.GetCompletedValue() < self.value { + let _ = self.rb_queue.Wait(&self.fence, self.value); + } + } + + #[inline] + unsafe fn signal_rb(&mut self) { + self.rb_done_value += 1; + let _ = self.rb_queue.Signal(&self.rb_done_fence, self.rb_done_value); + } + + #[inline] + unsafe fn wait_for_rb(&self, target: u64) { + if target == 0 || self.rb_done_fence.GetCompletedValue() >= target { + return; + } + let _ = self.rb_done_fence.SetEventOnCompletion(target, self.event); + windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); + if self.rb_done_fence.GetCompletedValue() < target { + crate::xlog_warn!( + "sparse: the readback queue has not reached fence value {target} after 5 s (at {})", + self.rb_done_fence.GetCompletedValue() + ); + super::real::stop_if_device_removed(); + } + } + #[inline] unsafe fn reclaim_ring(&mut self) { if self.inflight.is_empty() { @@ -1066,16 +1107,17 @@ impl State { let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize, Vec>)>, used: &mut usize, p: *mut u8| { if *open { *open = false; + s.order_rb_after_uploads(); if s.rb_list.Close().is_ok() { if let Ok(l) = s.rb_list.cast::() { super::title_textures::own_work(|| { - s.queue.ExecuteCommandLists(&[Some(l)]); + s.rb_queue.ExecuteCommandLists(&[Some(l)]); }); } } - s.signal(); - s.rb_last_fence = s.value; - s.wait_for(s.value); + s.signal_rb(); + s.rb_last_fence = s.rb_done_value; + s.wait_for_rb(s.rb_done_value); s.reclaim_ring(); } for (dst, off, len, snap) in pending.iter() { @@ -1145,7 +1187,7 @@ impl State { let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); if !open { - self.wait_for(self.rb_last_fence); + self.wait_for_rb(self.rb_last_fence); let _ = self.rb_alloc.Reset(); let _ = self.rb_list.Reset(&self.rb_alloc, None); open = true; @@ -1422,8 +1464,8 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz s.rb_value += 1; let v = s.rb_value; if queue.Signal(&s.rb_fence, v).is_ok() { - let _ = s.queue.Wait(&s.rb_fence, v); - super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); + let _ = s.rb_queue.Wait(&s.rb_fence, v); + super::list_x::note_internal_wait(s.rb_queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); } s.readback_ranges(&merged); } @@ -1675,21 +1717,23 @@ pub unsafe fn readback_now(va: usize, len: usize) { break; } let Ok(cmd_list) = job.list.cast::() else { break }; - // 2. Order `s.queue` behind active title queues via `rb_fence`, then submit & signal - // atomically under `STATE` (ordered after our uploads on `s.queue`) and release - // `STATE` BEFORE waiting on the GPU fence. + // 2. Order `s.rb_queue` behind pending sparse uploads and active title queues via + // `rb_fence`, then submit & signal atomically under `STATE` and release `STATE` BEFORE + // waiting on `rb_done_fence`. (`s.queue` never waits on title queues, preventing a + // `title_qA -> title_qB -> s.queue -> title_qA` circular GPU deadlock.) let wait_target = { let mut g = lock_state(); let Some(s) = g.as_mut() else { break }; + s.order_rb_after_uploads(); if !waited_title_queues { s.wait_title_queues_for_readback(); waited_title_queues = true; } super::title_textures::own_work(|| { - s.queue.ExecuteCommandLists(&[Some(cmd_list)]); + s.rb_queue.ExecuteCommandLists(&[Some(cmd_list)]); }); - s.signal(); - (s.fence.clone(), s.value) + s.signal_rb(); + (s.rb_done_fence.clone(), s.rb_done_value) }; if wait_target.1 > 0 && wait_target.0.GetCompletedValue() < wait_target.1 { let _ = wait_target.0.SetEventOnCompletion(wait_target.1, job.event); @@ -1909,10 +1953,11 @@ impl State { /// so a subsequent sparse readback sees all submitted GPU writes. unsafe fn wait_title_queues_for_readback(&mut self) { let self_q = self.queue.as_raw() as usize; + let rb_q = self.rb_queue.as_raw() as usize; let self_dev = self.dev.as_raw(); let mut seen: Vec = Vec::new(); for raw in super::present::known_queues() { - if raw == 0 || raw == self_q || seen.contains(&raw) { + if raw == 0 || raw == self_q || raw == rb_q || seen.contains(&raw) { continue; } let ptr = raw as *mut c_void; @@ -1927,8 +1972,8 @@ impl State { self.rb_value += 1; let v = self.rb_value; if q.Signal(&self.rb_fence, v).is_ok() { - let _ = self.queue.Wait(&self.rb_fence, v); - super::list_x::note_internal_wait(self_q, "sparse readback behind a title queue", &self.rb_fence, v); + let _ = self.rb_queue.Wait(&self.rb_fence, v); + super::list_x::note_internal_wait(rb_q, "sparse readback behind a title queue", &self.rb_fence, v); } } } @@ -1937,11 +1982,12 @@ impl State { // Pass 1 (before signaling): deduplicate live same-device title queues and prune stale // queue fences unconditionally so an early error cannot prune another live queue. let self_q = self.queue.as_raw() as usize; + let rb_q = self.rb_queue.as_raw() as usize; let mut active: Vec<(usize, &ID3D12CommandQueue)> = Vec::with_capacity(queues.len()); let mut live_keys: Vec = Vec::with_capacity(queues.len()); for &q in queues { let key = q.as_raw() as usize; - if key == 0 || key == self_q || live_keys.contains(&key) { + if key == 0 || key == self_q || key == rb_q || live_keys.contains(&key) { continue; } let mut qdev: Option = None; @@ -2452,8 +2498,10 @@ mod tests { } let dev = dev.expect("D3D12 device"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); @@ -2464,8 +2512,11 @@ mod tests { fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows: Vec::new(), pools: Vec::new(), free: Vec::new(), @@ -2663,8 +2714,10 @@ mod tests { .expect("CreateReservedResource"); let reserved = reserved.expect("reserved buffer"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); @@ -2676,8 +2729,11 @@ mod tests { fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), @@ -2764,8 +2820,10 @@ mod tests { .expect("CreateReservedResource"); let reserved = reserved.expect("reserved buffer"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); @@ -2777,8 +2835,11 @@ mod tests { fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), @@ -2895,8 +2956,10 @@ mod tests { .expect("CreateReservedResource"); let reserved = reserved.expect("reserved buffer"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("rb_alloc"); let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); @@ -2908,8 +2971,11 @@ mod tests { fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows: vec![(base, reserved)], pools: Vec::new(), free: Vec::new(), @@ -3577,4 +3643,46 @@ mod tests { mapped.get_mut(&t1).unwrap().holes = 0; assert_eq!(watchable_tile_runs(&mapped), vec![(t0, t2 + TILE)]); } + + /// Regression test for the circular GPU deadlock: + /// `title_qA -> title_qB -> sparse.queue -> title_qA`. + /// When `rb_queue` waits on a gated title queue `title_qA` (`rb_fence`), `sparse.queue` + /// (uploads + tile mappings) must remain unblocked so `title_qB` waiting on `sparse.queue` + /// can complete and release `title_qA`, unblocking the readback cleanly. + #[test] + fn readback_on_dedicated_queue_never_blocks_sparse_uploads_behind_gated_title_queue() { + unsafe { + let (base, mut s) = test_state_with_reserved(1); + let title_q_a: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title_q_a"); + let title_q_b: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title_q_b"); + let cross_fence: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("cross_fence"); + + // 1. title_q_a waits on title_q_b via cross_fence (not yet signalled by title_q_b). + title_q_a.Wait(&cross_fence, 1).expect("qA waits on qB"); + + // 2. A readback orders `rb_queue` behind title_q_a via `rb_fence` and signals `rb_done_fence`. + s.rb_value += 1; + let rb_v = s.rb_value; + title_q_a.Signal(&s.rb_fence, rb_v).expect("qA signals rb_fence"); + s.rb_queue.Wait(&s.rb_fence, rb_v).expect("rb_queue waits on qA"); + s.signal_rb(); + let rb_target = s.rb_done_value; + + // 3. Now title_q_b submits work that waits on `sparse.queue` (uploads), then signals cross_fence. + // With the old shared-queue design, `sparse.queue` was stuck behind qA, causing a 3-way deadlock! + s.signal(); + let upload_target = s.value; + title_q_b.Wait(&s.fence, upload_target).expect("qB waits on sparse.queue"); + title_q_b.Signal(&cross_fence, 1).expect("qB releases qA"); + + // Both `sparse.queue` AND `rb_queue` must complete well within 5 s (no deadlock!). + s.wait_for(upload_target); + assert!(s.fence.GetCompletedValue() >= upload_target, "sparse.queue must not be blocked by rb_queue"); + s.wait_for_rb(rb_target); + assert!(s.rb_done_fence.GetCompletedValue() >= rb_target, "rb_queue must complete once qB unblocks qA"); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0); + } + } } diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs index f5cf32d0ef..16f63e7096 100644 --- a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -595,8 +595,10 @@ mod tests { let mut reserved: Option = None; dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut reserved).expect("reserved buffer"); let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("queue"); + let rb_queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("rb_queue"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_fence"); + let rb_done_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("rb_done_fence"); let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None).expect("event"); let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("alloc"); let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("list"); @@ -614,8 +616,11 @@ mod tests { fence, value: 0, event, + rb_queue, rb_fence, rb_value: 0, + rb_done_fence, + rb_done_value: 0, windows: vec![(window, reserved.expect("reserved buffer"))], pools: Vec::new(), free: Vec::new(), From c32c91a30904fdf72071a8fa77db713cfea92b4c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:19:46 +0100 Subject: [PATCH 211/258] d3d12x/sparse: gate deferred tile unmaps, quarantine, and pool retirement on rb_done_fence --- crates/xcl/src/hle/d3d12x/sparse.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index fed215bf5b..f743fddd43 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -233,9 +233,9 @@ struct State { /// video-memory pool heaps (None: given back, its index free for the next one) pools: Vec>, free: Vec<(u32, u32)>, - /// pools all of whose tiles came free: released once the GPU is past `value` and a moment - /// went by (titles' queues may still read what was mapped there) - retired: Vec<(ID3D12Heap, u64, std::time::Instant)>, + /// pools all of whose tiles came free: released once the GPU is past `(value, rb_done_value)` + /// and a moment went by (titles' queues and `rb_queue` may still read what was mapped there) + retired: Vec<(ID3D12Heap, u64, u64, std::time::Instant)>, /// tile address → pool tile + uncommitted page hole mask + per-page sent chunk hashes mapped: FxHashMap, /// pool tiles also used by placed buffers (not freed while they are) @@ -656,7 +656,7 @@ impl State { // 64 MB heap is made: freeing and allocating a tile in turn made a new pool each time, // up to 18 GB of retired heaps in 2 s (#913). Its tiles are reused as freed tiles are // (zeroed), so this is no less safe than reusing a tile of a pool in use. - if let Some((heap, _, _)) = self.retired.pop() { + if let Some((heap, _, _, _)) = self.retired.pop() { let h = self.add_pool(heap); return Some(((h, 0), true)); } @@ -699,7 +699,8 @@ impl State { fn retire_free_pools(&mut self) { let now = std::time::Instant::now(); let done = unsafe { self.fence.GetCompletedValue() }; - self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); + let rb_done = unsafe { self.rb_done_fence.GetCompletedValue() }; + self.retired.retain(|(_, v, rb_v, at)| !(done >= *v && rb_done >= *rb_v && now.duration_since(*at).as_secs() >= 2)); if self.free.len() < POOL_TILES as usize { return; } @@ -714,7 +715,7 @@ impl State { self.free.retain(|&(h, _)| !gone.contains(&(h as usize))); for h in gone { if let Some(heap) = self.pools[h].take() { - self.retired.push((heap, self.value, now)); + self.retired.push((heap, self.value, self.rb_done_value, now)); } } } @@ -2057,9 +2058,13 @@ impl State { } self.signal(); if !tiles.is_empty() { + let mut marks = vec![(self.fence.clone(), self.value)]; + if self.rb_done_value > 0 { + marks.push((self.rb_done_fence.clone(), self.rb_done_value)); + } self.quarantined.push_back(RetiredTiles { tiles, - marks: Some(vec![(self.fence.clone(), self.value)]), + marks: Some(marks), }); } } @@ -2132,7 +2137,12 @@ impl State { return false; } let entries: Vec<(usize, (u32, u32))> = std::mem::take(&mut self.parked).into_iter().collect(); - let title_marks = self.signal_title_queues_for(queues); + let mut title_marks = self.signal_title_queues_for(queues); + if self.rb_done_value > 0 { + if let Some(marks) = title_marks.as_mut() { + marks.push((self.rb_done_fence.clone(), self.rb_done_value)); + } + } if title_marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)) { self.unmap_entries_and_quarantine(entries); } else { From 287a931b9b358860531ebc2a0f4e1f6d0735cc48 Mon Sep 17 00:00:00 2001 From: Jesse Date: Thu, 26 Nov 2026 13:59:55 +0200 Subject: [PATCH 212/258] Recompiler: each loop region of a program gets its own iteration budget A translated program caps its loops with one per-lane counter, 65,536 iterations shared by the whole program. A program whose own spin-wait gives up after 0x10000 tries uses all of it, and every loop after that spin then leaves at its first guard. A retail FSR pass (CS a8de35e47f36d28c) polls flags written by an earlier pass with a cap of exactly 0x10000 tries, inside an outer loop. When the spin ran out, its main loop never ran. A spilled SGPR then held a weight from an earlier load where the constant buffer's 0 should have been, and the flags it publishes read that weight with bit 0 set instead of 1. The pass waiting on those flags (5f29d7e51b2c6230) spun to its own cap every frame: about 260 ms of GPU time a frame on an RTX 5070 Ti. Measured with a local probe: the flags, cb[0xa8] = 0, and the weight dword the flags carry. The outermost ranges of loop_ranges are the program's loop regions. Control only moves forward between them: a jump back would make them one range. In a program with two or more regions, each region starts with two budgets. Two, so that a 0x10000 spin inside an outer loop fits, because the outer loop's head spends from the same count. All regions together have at most four budgets (xcl_btotal / VAR_BUDGET_TOTAL), so a program that really runs away stops within four budgets. Before, it stopped within one. This is done in all three emitters: the HLSL structured and pc forms (loop_guard), the direct DXIL plain form (kernel.rs) and the compact form. In the compact form, a loop head's class now includes its region. Programs with fewer than two regions keep their exact HLSL text and cached translations. Of the title's 2,682 compute programs, 1,916 have two or more regions, so those are translated and compiled again once. Assisted-by: Claude Code (Claude Opus 5.5) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/gpu/dxil/compact.rs | 33 ++++++++++-- crates/xcl/src/gpu/dxil/compact_tests.rs | 39 ++++++++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 23 ++++++-- crates/xcl/src/gpu/dxil/lower.rs | 9 +++- crates/xcl/src/gpu/recomp/mod.rs | 56 +++++++++++++++++-- crates/xcl/src/gpu/recomp/tests.rs | 69 ++++++++++++++++++++++++ 6 files changed, 216 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index 618e7b3004..e10140f4bb 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -1,7 +1,7 @@ //! The compact form: each distinct block of a program lowered once, in a loop over a table. use super::cfg::{Cfg, Term}; -use super::lower::{ext_encoding, LResult, Lw, VAR_BUDGET, VAR_SCC}; +use super::lower::{ext_encoding, LResult, Lw, LOOP_BUDGET, VAR_BUDGET, VAR_BUDGET_OWNER, VAR_BUDGET_TOTAL, VAR_SCC}; use super::lower_mem::VAR_TMP; use super::module::{Block, Pred, Value}; use std::collections::{BTreeSet, HashMap}; @@ -515,6 +515,8 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { vec![ALL_SGPRS_MASK | SCC_LIVE_BIT; mblocks.len()] }; + // a loop head's guard names its loop region: heads of two regions are two classes + let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); let build = |param_lit: bool, param_pc: bool| { let mut ids: HashMap<(Vec, &'static str), u32> = HashMap::new(); let (mut class, mut rep, mut next, mut blk_lit) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); @@ -522,7 +524,12 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { for (n, blk) in mblocks.iter().enumerate() { let p_lit = if param_lit { single_param_lit(cfg, blk) } else { None }; blk_lit.push(p_lit); - let mut key = vec![blk.is_header as u64, p_lit.is_some() as u64]; + let region = if blk.is_header { + crate::gpu::recomp::budget_region(®ions, cfg.blocks[order[n]].pc).unwrap_or(0) as u64 + } else { + 0 + }; + let mut key = vec![blk.is_header as u64 + region, p_lit.is_some() as u64]; for &i in &blk.insts { let d = &cfg.insts[i]; let mask_lit = p_lit.is_some() && d.literal.is_some(); @@ -797,6 +804,8 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let (at, to) = (lw.tmp_var(), lw.tmp_var()); let (at, to, budget) = (slot(lw, at), slot(lw, to), slot(lw, VAR_BUDGET)); + let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); + let owner = if regions.is_empty() { None } else { Some((slot(lw, VAR_BUDGET_OWNER), slot(lw, VAR_BUDGET_TOTAL))) }; lw.s.m.set_block(head); let b = lw.s.m.load(at, 4); let w = lw.c(width); @@ -908,8 +917,19 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block lw.ssa.begin_log(); let blk = &p.mblocks[r]; if blk.is_header { - // a loop head spends the loop budget - let left = lw.s.m.load(budget, 4); + // a loop head spends the loop budget (of its region: the recompiler's `loop_guard`) + let region = owner.zip(crate::gpu::recomp::budget_region(®ions, cfg.blocks[p.order[r]].pc)); + let mut left = lw.s.m.load(budget, 4); + if let Some(((own_at, total_at), reg)) = region { + let own = lw.s.m.load(own_at, 4); + let other = lw.cmpc(Pred::Ne, own, reg); + left = lw.selc(other, LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_PER_REGION, left); + let rv = lw.c(reg); + lw.s.m.store(own_at, rv, 4); + let total = lw.s.m.load(total_at, 4); + let spent = lw.cmpc(Pred::Eq, total, 0); + left = lw.selc(spent, 0, left); + } let none = lw.cmpc(Pred::Eq, left, 0); let (out, body) = (lw.block(Some(1)), lw.block(Some(1))); lw.cond_br(none, out, body); @@ -921,6 +941,11 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let one = lw.c(1); let l = lw.sub(left, one); lw.s.m.store(budget, l, 4); + if let Some(((_, total_at), _)) = region { + let total = lw.s.m.load(total_at, 4); + let t = lw.sub(total, one); + lw.s.m.store(total_at, t, 4); + } } lw.compact_blk_pc = blk_pc.map(|v| (v, blk.pc)); lw.compact_lit = if p.blk_lit[r].is_some() { blk_lit_val } else { None }; diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 6fbd19c699..06c198724d 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -106,6 +106,45 @@ fn gpu_compact_form_spends_the_loop_budget_as_the_plain_form() { assert_eq!(&c.sgpr[..2], &p.sgpr[..2]); } +/// The direct translator's forms give each loop region its own budget as the HLSL path does +/// (`recomp::tests::gpu_a_loop_after_a_spin_to_the_budget_still_runs`). +#[test] +fn gpu_a_loop_after_a_spin_to_the_budget_still_runs_in_both_forms() { + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + for (spin, n, nested) in [(0x10000, 3, false), (0xFFF0, 1000, false), (0x10000, 3, true)] { + let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}")); + // a spin of `spin` tries (in an outer loop that runs once when `nested`), a loop of `n`, + // then s2 = 7 (as `recomp::tests::spin_then_loop`) + let mut v = Vec::new(); + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None)); + if nested { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 129)], None)); + } + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 255)], Some(spin))); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None)); + if nested { + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 3), ("SSRC1", 129)], None)); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None)); + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)], None)); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 255)], Some(n))); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None)); + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 135)], None)); + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + for compact in [true, false] { + let k = translate_full_as(&v, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + let r = runner::run_with_statics(&k.dxil, &KernelState::default(), &[], &[], &[], &k.static_samplers).expect("GPU run"); + assert_eq!(&r.sgpr[..3], &[spin, n, 7], "spin {spin:#x}, loop {n}, nested {nested}, compact {compact}"); + } + } +} + fn early_outs(copies: usize) -> Vec { let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); let mut v = Vec::new(); diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 6c0f56a41d..6f3b278633 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -13,7 +13,7 @@ use std::collections::{BTreeSet, HashMap}; use super::cfg::{Cfg, Term}; use super::container::Stage; -use super::lower::{ComputeInit, Init, Lw, Partner, VAR_BUDGET, VAR_SCC, VAR_VGPR}; +use super::lower::{ComputeInit, Init, Lw, Partner, LOOP_BUDGET, VAR_BUDGET, VAR_BUDGET_OWNER, VAR_BUDGET_TOTAL, VAR_SCC, VAR_VGPR}; use super::module::{Block, Pred, Value}; use super::shader::{RawUav, Shader}; use super::ssa::Ssa; @@ -371,6 +371,7 @@ fn translate_on_this_thread( None => super::compact::emit(&mut lw, &cfg, p, h0, exit)?, } } + let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); for &b in cfg.rpo.iter().filter(|_| plan.is_none()) { let h = head(&mut lw, b); lw.s.m.set_block(h); @@ -386,8 +387,19 @@ fn translate_on_this_thread( } let end = if es_block { switch.unwrap() } else { exit }; if cfg.headers.contains(&b) { - // a lane's loop iterations are capped (the recompiler's LOOP_GUARD) - let left = lw.rd(VAR_BUDGET); + // a lane's loop iterations are capped (the recompiler's LOOP_GUARD / loop_guard) + let region = crate::gpu::recomp::budget_region(®ions, cfg.blocks[b].pc); + let mut left = lw.rd(VAR_BUDGET); + if let Some(r) = region { + let own = lw.rd(VAR_BUDGET_OWNER); + let other = lw.cmpc(Pred::Ne, own, r); + left = lw.selc(other, LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_PER_REGION, left); + let rv = lw.c(r); + lw.wr(VAR_BUDGET_OWNER, rv); + let total = lw.rd(VAR_BUDGET_TOTAL); + let spent = lw.cmpc(Pred::Eq, total, 0); + left = lw.selc(spent, 0, left); + } let none = lw.cmpc(Pred::Eq, left, 0); let cont = lw.block(Some(1)); lw.cond_br(none, end, cont); @@ -395,6 +407,11 @@ fn translate_on_this_thread( let one = lw.c(1); let l = lw.sub(left, one); lw.wr(VAR_BUDGET, l); + if region.is_some() { + let total = lw.rd(VAR_BUDGET_TOTAL); + let t = lw.sub(total, one); + lw.wr(VAR_BUDGET_TOTAL, t); + } } for &i in &cfg.blocks[b].insts { lw.reload = reloads.get(b, i); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 34a4eb021a..acf47db334 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -34,6 +34,10 @@ pub const VAR_XDEAD: u32 = VAR_BUDGET + 4; pub const VAR_IMG_WRITE: u32 = VAR_BUDGET + 8; /// loop iterations a lane may run (the recompiler's `xcl_budget`) pub const LOOP_BUDGET: u32 = 1 << 16; +/// the loop region whose budget [`VAR_BUDGET`] holds (the recompiler's `xcl_bown`, `budget_region`) +pub const VAR_BUDGET_OWNER: u32 = VAR_BUDGET + 7; +/// iterations left to all the regions together (the recompiler's `xcl_btotal`) +pub const VAR_BUDGET_TOTAL: u32 = VAR_BUDGET + 24; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Dst { @@ -117,10 +121,13 @@ impl Init { if var == VAR_BUDGET { return s.m.i32c(LOOP_BUDGET); } + if var == VAR_BUDGET_TOTAL { + return s.m.i32c(LOOP_BUDGET * crate::gpu::recomp::LOOP_BUDGETS_IN_ALL); + } if var == super::lower_round::VAR_F32_MODE { return s.m.i32c(super::lower_round::MODE_INIT); } - if var == VAR_FP16_RM || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) { + if var == VAR_FP16_RM || var == VAR_BUDGET_OWNER || var == VAR_WIN || var == VAR_XK || var == VAR_XDEAD || (VAR_IMG_WRITE..VAR_IMG_WRITE + 16).contains(&var) { return s.m.i32c(0); } if var >= super::lower_mem::VAR_TMP { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 589219b1e6..ec33fdd3b3 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -704,6 +704,8 @@ struct Ctx<'a> { starts: &'a BTreeSet, leaders: &'a [u64], loops: &'a [(u64, u64)], + /// [`budget_regions`] + regions: &'a [(u64, u64)], /// every branch: (address of the branch, target) edges: &'a [(u64, u64)], /// split wave64 geometry mode: the ES's s_setpc ends the ES phase and `gs_start` is the GS @@ -786,6 +788,46 @@ impl Conts { /// leaves at its next iteration and the program runs to its end. const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;"; +/// A program with two or more loop regions gives each this many budgets of iterations +/// ([`loop_guard`]): a title's own spin capped at one budget (0x10000 tries) must fit, also +/// when it sits in an outer loop whose head spends from the same count. +pub(crate) const LOOP_BUDGETS_PER_REGION: u32 = 2; +/// ... and all of its regions together at most this many. +pub(crate) const LOOP_BUDGETS_IN_ALL: u32 = 4; + +/// The outermost of [`loop_ranges`]: the program's loop regions, in order. Control only moves +/// forward from one to the next (a jump back into an earlier one would make them one range). +/// Empty for a program with fewer than two, whose guards stay [`LOOP_GUARD`]. +pub(crate) fn budget_regions(loops: &[(u64, u64)]) -> Vec<(u64, u64)> { + let outer: Vec<(u64, u64)> = loops.iter().copied().filter(|&(a, b)| !loops.iter().any(|&(c, d)| (c, d) != (a, b) && c <= a && b <= d)).collect(); + if outer.len() < 2 { + Vec::new() + } else { + outer + } +} + +/// The region ([`budget_regions`]) of the loop headed at `head`, numbered from 1. +pub(crate) fn budget_region(regions: &[(u64, u64)], head: u64) -> Option { + regions.iter().position(|&(a, b)| a <= head && head < b).map(|k| k as u32 + 1) +} + +/// The guard of the loop headed at `head`. In a program with loop regions, each region starts +/// with [`LOOP_BUDGETS_PER_REGION`] budgets, and `xcl_btotal` keeps all of them to +/// [`LOOP_BUDGETS_IN_ALL`]: a title's own spin that gives up after 0x10000 tries, the budget, +/// otherwise left every loop after it without an iteration (a retail FSR pass then published a +/// flag made from a register its main loop never set, and the pass waiting on that flag spun +/// 260 ms a frame). +fn loop_guard(regions: &[(u64, u64)], head: u64) -> String { + match budget_region(regions, head) { + Some(r) => format!( + "if (xcl_bown != {r}u) {{ xcl_bown = {r}u; xcl_budget = {}u; }} if (xcl_budget == 0u || xcl_btotal == 0u) break; xcl_budget--; xcl_btotal--;", + LOOP_BUDGETS_PER_REGION << 16 + ), + None => LOOP_GUARD.to_string(), + } +} + /// Structured code longer than this many bytes per byte of program falls back to the `pc` form. /// Each guard of the structured form lists every pending skip flag, so it grows with the /// square of the flags: one retail program made 455 B per byte (148 MB, 14 MB as `pc` blocks), @@ -795,7 +837,7 @@ const STRUCTURED_BYTES_PER_CODE_BYTE: usize = 128; /// The loops the translator emits: ranges spanned by backward jumps (far jumps included), /// partly overlapping ones merged until they nest, sorted. `x64_masks` uses them for the /// exits through `LOOP_GUARD`. -pub(super) fn loop_ranges(insts: &[Decoded]) -> Vec<(u64, u64)> { +pub(crate) fn loop_ranges(insts: &[Decoded]) -> Vec<(u64, u64)> { let mut loops: Vec<(u64, u64)> = Vec::new(); for d in insts { if let Some(t) = rdna2::branch_target(d) { @@ -1237,7 +1279,7 @@ fn emit_structured( } let raised: BTreeSet = match it { Item::Loop { a, b, latch, entry } => { - body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {LOOP_GUARD}\n")); + body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {}\n", loop_guard(c.regions, a))); let (lcont, lin) = if entry.is_none() { (cont.enter(Some(a)), &inner) } else { (cont.enter(None), &none) }; let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, &lcont, lin, d + 1, blocks, flags); for &t in &r { @@ -1358,7 +1400,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d let start = c.leaders[i]; let inner = c.loops.iter().filter(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)).max_by_key(|x| x.1).copied(); if let Some((a, b)) = inner { - body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {LOOP_GUARD}\n")); + body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {}\n", loop_guard(c.regions, a))); emit_range(c, em, body, a, b, depth + 1, blocks, flags); body.push_str(&format!("{pad}}}\n")); i = c.leaders.partition_point(|&l| l < b); @@ -1804,13 +1846,14 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // (optimising one big dispatcher loop took minutes on large retail programs). let leaders: Vec = leaders.into_iter().filter(|l| starts.contains(l)).collect(); let loops = loop_ranges(&insts); + let regions = budget_regions(&loops); let edges: Vec<(u64, u64)> = insts.iter().filter_map(|d| rdna2::branch_target(d).map(|t| (d.pc, t))).collect(); let phase_split = gs_jump.is_some_and(|t| t.is_some()) && opt.split_wave64 && opt.wave64; - let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, edges: &edges, phase_split, memo: Default::default() }; + let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, regions: ®ions, edges: &edges, phase_split, memo: Default::default() }; let mut flags = BTreeSet::new(); let mut code = String::new(); let nested = nested_loop_ranges(&insts); - let sctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &nested, edges: &edges, phase_split, memo: Default::default() }; + let sctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &nested, regions: ®ions, edges: &edges, phase_split, memo: Default::default() }; if gs_jump.is_none() && opt.structured && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none() && structurable(&sctx, 0, u64::MAX).is_some() { // structured control flow: plain if / loops, no block dispatch on `pc` (much // smaller for DXC and the driver on big programs) @@ -1826,6 +1869,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } emit_range(&ctx, &mut em, &mut code, 0, u64::MAX, 1, &mut blocks, &mut flags); } + if !regions.is_empty() { + body.push_str(&format!(" uint xcl_bown = 0u;\n uint xcl_btotal = {}u;\n", LOOP_BUDGETS_IN_ALL << 16)); + } for &t in &flags { body.push_str(&format!(" bool {} = false;\n", skip_flag(t))); } diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 914e2c69d1..eeba83a48c 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1426,6 +1426,75 @@ fn gpu_scalar_loop_and_scc() { assert_eq!((r.sgpr[41], r.sgpr[42], r.sgpr[43]), (48, 33, u32::MAX), "flbit_i64 high-then-low scan"); } +/// A spin of `spin` tries (a retail FSR pass polls a flag up to 0x10000 times, the loop budget), +/// inside an outer loop that runs once when `nested` (as in that pass), then a loop of `n` +/// iterations, then `s2 = 7`. +fn spin_then_loop(spin: u32, n: u32, nested: bool) -> Vec { + let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}")); + let mut v = i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None); // s0 = 0 + if nested { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 3), ("SSRC0", 3), ("SSRC1", 129)], None)); // outer: s3 += 1 + } + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); // spin: s0 += 1 + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 255)], Some(spin))); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None)); // → spin + if nested { + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 3), ("SSRC1", 129)], None)); // until s3 == 1 + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFF9)], None)); // → outer + } + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 128)], None)); // s1 = 0 + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); // loop: s1 += 1 + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 1), ("SSRC1", 255)], Some(n))); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFC)], None)); // → loop + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 135)], None)); // s2 = 7 + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + v +} + +/// A program's own spin that gives up at the loop budget, or just before it, must not leave the +/// loops after it short of iterations: the FSR pass then published a flag built from a register +/// its main loop never set, and the pass waiting on it spun for 260 ms a frame. Both HLSL forms. +#[test] +fn gpu_a_loop_after_a_spin_to_the_budget_still_runs() { + if !gpu_ready() { + return; + } + for (spin, n, nested) in [(0x10000, 3, false), (0xFFF0, 1000, false), (0x10000, 3, true)] { + let code = spin_then_loop(spin, n, nested); + for structured in [true, false] { + let opt = Options { structured, ..runner::options(Mode::Kernel) }; + let t = translate(&code, &opt).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + let what = format!("spin {spin:#x}, loop {n}, nested {nested}, structured {structured}"); + assert_eq!(r.sgpr[0], spin, "{what}: the spin ran to its own end"); + assert_eq!((r.sgpr[1], r.sgpr[2]), (n, 7), "{what}: the loop after it ran all its iterations"); + } + } +} + +/// Loops that never end still stop: four budgets in all, then every loop leaves. (The direct +/// translator ends the program where a budget runs out, so this is the HLSL path's.) +#[test] +fn gpu_endless_loops_in_many_regions_stop_after_four_budgets() { + if !gpu_ready() { + return; + } + // six regions, each `s0 += 1` until s0 == 0 (2^32 tries); s1 counts the regions reached + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + for _ in 0..6 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 129)], None)); + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + list.push(("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None)); + } + let t = translate(&prog(&list), &runner::options(Mode::Kernel)).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + assert_eq!(r.sgpr[1], 6, "every region was reached"); + assert_eq!(r.sgpr[0], super::LOOP_BUDGETS_IN_ALL << 16, "four budgets of iterations in all"); +} + #[test] fn gpu_divergence_through_exec() { if !gpu_ready() { From b6fd1f279a141f626b160efc45df866571a8ac12 Mon Sep 17 00:00:00 2001 From: 3L1A5-1 <276908492+3L1A5-1@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:35:57 +0100 Subject: [PATCH 213/258] D3D12.X: render targets on one physical page share its video memory A retail game maps one physical page under render targets at two addresses at once (aliasing targets that are never live together, as the console allows). kernelx keeps a page at one address (`map_pages` moves it), and `vram::Pages` keyed its video memory by title address, so each alias got pages of its own: in its first 40 s the game placed 422 targets (2.1 GB) whose pages it then mapped under 276 others (1.85 GB), and kept using both sets (barriers, views). The duplicate cost 1.85 GB of video memory, and what the GPU wrote through one alias never showed in the other. A GPU-owned texture's owned pages are now keyed by the physical page mapped at their address (`kernelx::physical_pages`, asked before `PAGES` is taken), else by the address as before. Sampled textures keep address keys. Measured on GTA VI, RTX 2060 SUPER 8 GB, 90 s at the menus, 3 runs each: target pages 3597 -> 1738 MB, local video memory 6652 -> 4796 MB. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 84 +++++++++++++++++++ crates/xcl/src/hle/d3d12x/vram.rs | 92 ++++++++++++++++----- crates/xcl/src/hle/kernelx.rs | 10 +++ 3 files changed, 164 insertions(+), 22 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 2e794c92fc..f842d021f2 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2880,6 +2880,90 @@ mod tests { assert_eq!(unmap_unaligned, vec![30, 31]); } + /// Real GPU: render targets at two addresses of one physical page (mapped at the second after + /// the first, as a retail game aliases its targets) share one page of video memory, as on the + /// console; a target on another physical page gets its own. + #[test] + fn render_targets_on_one_physical_page_share_its_video_memory() { + // (a test that panicked holding these locks does not fail this one too) + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use crate::hle::kernelx; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const NAME: &str = "render_targets_on_one_physical_page_share_its_video_memory"; + unsafe { + let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); + let Ok(adapter) = factory.EnumAdapters1(0) else { return println!("SKIPPED {NAME}: no adapter") }; + if adapter.GetDesc1().is_ok_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0) { + return println!("SKIPPED {NAME}: software adapter"); + } + let mut dev: Option = None; + let _ = D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { return println!("SKIPPED {NAME}: no D3D12 device") }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_2.0 + { + return println!("SKIPPED {NAME}: tiled tier < 2"); + } + // (`vram::place` keeps no render target on pages below resource heap tier 2) + if opts.ResourceHeapTier.0 < 2 { + return println!("SKIPPED {NAME}: resource heap tier < 2"); + } + if crate::gpu::uma::get().is_none() { + return println!("SKIPPED {NAME}: no UMA"); + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + // a 128x128 R8G8B8A8 render target: one 64 KiB page on the console and on the PC + let mut rt = console_desc(3, 128, 128, 1, 1, 28, 0x109); + rt[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); + let place = |va: usize| -> ID3D12Resource { + let mut p = std::ptr::null_mut(); + let hr = super::super::device_x::create_placed_resource_x(dev.as_raw(), va as u64, rt.as_ptr(), D3D12_RESOURCE_STATE_RENDER_TARGET.0 as u32, std::ptr::null(), riid, &mut p); + assert!(hr >= 0 && !p.is_null(), "CreatePlacedResourceX at {va:#x}: {hr:#x}"); + assert!(super::super::vram::is_placed_texture(p as usize), "expected a vram::Pages target at {va:#x}"); + ID3D12Resource::from_raw(p) + }; + let dev_pages = || super::super::vram::page_bytes_for(dev.as_raw() as usize).0; + let lost = || super::super::vram::tiles_unaccounted_for(dev.as_raw() as usize); + let space = VirtualAlloc(std::ptr::null(), 4 << 20, MEM_RESERVE, PAGE_READWRITE) as usize; + assert_ne!(space, 0); + let (a, b, c, d) = (space, space + (1 << 20), space + (2 << 20), space + (3 << 20)); + let (mut n, mut pages) = (3usize, [0usize; 3]); + assert_eq!(kernelx::AllocateTitlePhysicalPages(std::ptr::null_mut(), 0, &mut n, pages.as_mut_ptr()), 1); + let (before, lost_before) = (dev_pages(), lost()); + assert_eq!(kernelx::MapTitlePhysicalPages(a as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, a); + let first = place(a); + // the same page at a second address: the console's alias of `a` + assert_eq!(kernelx::MapTitlePhysicalPages(b as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, b); + let second = place(b); + let shared = dev_pages() - before; + // another physical page: video memory of its own + assert_eq!(kernelx::MapTitlePhysicalPages(c as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(1)) as usize, c); + let third = place(c); + let all = dev_pages() - before; + // a target at `d` with no page mapped (keyed by its address), then a page mapped there + // and a second target: its page is keyed by the physical page, which has none yet + let fourth = place(d); + assert_eq!(kernelx::MapTitlePhysicalPages(d as *mut c_void, 1, 0, 4, pages.as_mut_ptr().add(2)) as usize, d); + let fifth = place(d); + let lost_after = lost(); + drop((first, second, third, fourth, fifth)); + let mut none = [0usize; 1]; + kernelx::MapTitlePhysicalPages(b as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::MapTitlePhysicalPages(c as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::MapTitlePhysicalPages(d as *mut c_void, 1, 0, 4, none.as_mut_ptr()); + kernelx::FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()); + VirtualFree(space as *mut c_void, 0, MEM_RELEASE); + assert_eq!(shared, 0x1_0000, "two targets on one physical page: one page of video memory"); + assert_eq!(all, 0x2_0000, "a target on another physical page: a page of its own"); + assert_eq!(lost_after, lost_before, "every pool tile taken is a page's"); + } + } + /// Real GPU (#248): placed title textures share `vram::Pages` so streaming unreleased /// overlapping placements stays bounded in video memory, superseded textures never corrupt /// newer placements on shared tiles, 4 KiB-aligned neighbours never false-alias, and mip diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 24d8e2cc27..a070feb49f 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -411,6 +411,8 @@ struct Target { /// its levels get their pages one by one (`map_levels`); None: all of it has pages levels: Option, recycle: Option, + /// placed as GPU-owned: its pages are keyed by the physical page under them (`page_key`) + gpu_owned: bool, } /// An owned page of placed textures in a graphics reservation: mapped only while the title @@ -1562,10 +1564,12 @@ impl Pages { } } - /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. + /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue + /// (`phys[i]`: the title's physical page at owned page i, if any – see `page_key`). /// When `follow_key` is `Some`, a page in a graphics reservation the title has no memory at /// yet is left unmapped (tier 2: reads zero) and mapped when the title puts memory there /// (`apply_backing`); GPU-owned targets (`RT | DS | UAV`) pass `None` so every tile is backed. + #[allow(clippy::too_many_arguments)] unsafe fn bind_with_follow( &mut self, dev: &ID3D12Device, @@ -1574,13 +1578,14 @@ impl Pages { va: usize, console_bytes: Option, total: u32, + phys: &[Option], ) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { - self.bind_range(dev, res, follow_key, va, console_bytes, total, 0, 0..total as usize) + self.bind_range(dev, res, follow_key, va, console_bytes, total, 0, 0..total as usize, phys) } #[cfg(test)] unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, key: usize, va: usize, console_bytes: Option, total: u32) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { - self.bind_with_follow(dev, res, Some(key), va, console_bytes, total) + self.bind_with_follow(dev, res, Some(key), va, console_bytes, total, &[]) } /// `bind` for the tiles `range` of the resource's `total`, which start at subresource `sub`. @@ -1595,6 +1600,7 @@ impl Pages { total: u32, sub: u32, range: std::ops::Range, + phys: &[Option], ) -> Option<(Vec, Vec<(usize, usize)>, Vec)> { #[cfg(test)] if FAIL_LEVEL_BIND_FOR_TEST.with(|failure| { @@ -1614,7 +1620,7 @@ impl Pages { enum TilePlan { FollowSkip(usize), - Own { addr: usize, follow: bool }, + Own { addr: usize, key: usize, follow: bool }, Extra(usize, usize), } @@ -1630,6 +1636,7 @@ impl Pages { for i in range.clone() { if i < own { let a = first + i * PAGE; + let key = page_key(a, phys.get(i).copied().flatten()); let in_res = if check_res { if res_bounds.is_none_or(|(lo, hi)| a < lo || a >= hi) { res_bounds = crate::hle::kernelx::graphics_reservation_bounds(a); @@ -1639,19 +1646,19 @@ impl Pages { false }; if in_res { - let shared = self.pages.get(&a).is_some_and(|p| p.users > 0); + let shared = self.pages.get(&key).is_some_and(|p| p.users > 0); let already_mapped = self.follow.get(&a).is_some_and(|f| f.mapped); if !(already_mapped || shared || title_backed_in(a, &mut backed_run)) { plan.push(TilePlan::FollowSkip(a)); continue; } } - match self.pages.get(&a).map(|p| p.tile.0) { + match self.pages.get(&key).map(|p| p.tile.0) { Some(h) if preferred.is_none() => preferred = Some(h), Some(_) => {} None => missing += 1, } - plan.push(TilePlan::Own { addr: a, follow: in_res }); + plan.push(TilePlan::Own { addr: a, key, follow: in_res }); } else { match self.extra_pages.get(&(va, i)).map(|p| p.tile.0) { Some(h) if preferred.is_none() => preferred = Some(h), @@ -1686,16 +1693,16 @@ impl Pages { } tiles.push(None); } - TilePlan::Own { addr: a, follow } => { + TilePlan::Own { addr: a, key, follow } => { if follow { follows.push(a); - if let Some(key) = follow_key { + if let Some(fkey) = follow_key { let f = self.follow.entry(a).or_insert(Follow { users: Vec::new(), mapped: false }); - f.users.push((key, i as u32)); + f.users.push((fkey, i as u32)); f.mapped = true; } } - let t = match self.pages.get_mut(&a) { + let t = match self.pages.get_mut(&key) { Some(p) => { p.users += 1; p.idle_since = None; @@ -1703,11 +1710,11 @@ impl Pages { } None => { let t = fresh_iter.next().unwrap(); - self.pages.insert(a, Page { tile: t, users: 1, idle_since: None }); + self.pages.insert(key, Page { tile: t, users: 1, idle_since: None }); t } }; - used.push(a); + used.push(key); tiles.push(Some(t)); } TilePlan::Extra(va, idx) => { @@ -1963,6 +1970,30 @@ fn canonical_va(va: usize) -> usize { if mapped { va } else { src } } +/// Keys of `Pages::pages` for the title's physical pages (title addresses never have bit 63). +const PHYS_KEY: usize = 1 << 63; + +/// The key of the page of video memory for title page address `a`: the physical page mapped +/// there (`phys`), else the address. A retail game maps one physical page under render targets +/// at two addresses (aliasing, as on the console): keyed by address, each got video memory of +/// its own (1.85 GB more in its first 40 s) and what the GPU wrote through one never showed in +/// the other. +fn page_key(a: usize, phys: Option) -> usize { + phys.map_or(a, |p| PHYS_KEY | p) +} + +/// The physical pages under a GPU-owned texture's owned pages (`require_aligned`), asked before +/// `PAGES` is taken; empty for others (keyed by address) and without the console size. +fn physical_pages_under(va: usize, console_bytes: Option, require_aligned: bool) -> Vec> { + if !require_aligned { + return Vec::new(); + } + match console_bytes.and_then(|b| owned_pages(va, Some(b), usize::MAX)) { + Some((first, n)) if n > 0 => crate::hle::kernelx::physical_pages(first, n), + _ => Vec::new(), + } +} + /// A texture at `va` as a reserved resource on the title's shared 64 KiB pages /// (`console_bytes`: its size on the console; tiles past the owned page boundaries are shared by /// `(va, tile_index)` so repeated placements at the same address do not leak). None: it cannot be. @@ -1989,6 +2020,7 @@ unsafe fn place_on_pages( if (require_aligned || console_bytes.is_none()) && va % PAGE != 0 { return None; } + let phys = physical_pages_under(va, console_bytes, require_aligned); // reserved textures have the PC's 64 KiB tiles let tiled = D3D12_RESOURCE_DESC { Layout: D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE, ..*desc }; static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); @@ -2106,10 +2138,10 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used: Vec::new(), used_extra: Vec::new(), follows: Vec::new(), follow_backing, levels, recycle: recycle_key }); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used: Vec::new(), used_extra: Vec::new(), follows: Vec::new(), follow_backing, levels, recycle: recycle_key, gpu_owned: require_aligned }); true - } else if let Some((used, used_extra, follows)) = pages.bind_with_follow(dev, res, follow_backing.then_some(raw as usize), va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used, used_extra, follows, follow_backing, levels: None, recycle: recycle_key }); + } else if let Some((used, used_extra, follows)) = pages.bind_with_follow(dev, res, follow_backing.then_some(raw as usize), va, console_bytes, total, &phys) { + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, mapping_gen: 0, used, used_extra, follows, follow_backing, levels: None, recycle: recycle_key, gpu_owned: require_aligned }); true } else { false @@ -2185,21 +2217,29 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { } let Some(dev) = dev else { return false }; let key = res.as_raw() as usize; - let mut g = PAGES.lock().unwrap(); - let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; - let Some((va, console_bytes, total, mapped, follow_backing)) = pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped, t.follow_backing)) else { - return false; + let target = |g: &mut std::sync::MutexGuard<'_, std::collections::BTreeMap>>| { + let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return None }; + pages.targets.get(&key).map(|t| (t.va, t.console_bytes, t.total, t.mapped, t.follow_backing, t.gpu_owned)) }; + // (the physical pages are asked without `PAGES` held) + let Some((va, console_bytes, _, mapped, _, gpu_owned)) = target(&mut PAGES.lock().unwrap()) else { return false }; + if mapped { + return true; + } + let phys = physical_pages_under(va, console_bytes, gpu_owned); + let mut g = PAGES.lock().unwrap(); + let Some((va, console_bytes, total, mapped, follow_backing, _)) = target(&mut g) else { return false }; if mapped { return true; } + let Some(Some(pages)) = g.get_mut(&(dev.as_raw() as usize)) else { return false }; // (lazy levels: they get their pages again with their next texels) if let Some(t) = pages.targets.get_mut(&key).filter(|t| t.levels.is_some()) { t.mapped = true; t.mapping_gen = t.mapping_gen.wrapping_add(1); return true; } - let Some((used, used_extra, follows)) = pages.bind_with_follow(&dev, res, follow_backing.then_some(key), va, console_bytes, total) else { + let Some((used, used_extra, follows)) = pages.bind_with_follow(&dev, res, follow_backing.then_some(key), va, console_bytes, total, &phys) else { return false; }; if let Some(t) = pages.targets.get_mut(&key) { @@ -2622,6 +2662,14 @@ pub(super) fn tile_mappings_for(device: usize, resource: usize) -> Option<(Vec<( (used.len() + extra.len() == target.total as usize).then_some((used, extra)) } +/// Pool tiles of `device` that are neither free, cooling, nor any page's (taken and lost). +#[cfg(test)] +pub(super) fn tiles_unaccounted_for(device: usize) -> usize { + let g = PAGES.lock().unwrap(); + let Some(Some(p)) = g.get(&device) else { return 0 }; + (p.pools.len() * POOL_PAGES as usize).saturating_sub(p.pool.free_total + p.pool.cooling.len() + p.pages.len() + p.extra_pages.len()) +} + /// (bytes of pages in use by tiled textures, bytes of pool heaps) – `XCL_ACTIVITY` pub fn page_bytes() -> (usize, usize) { let (su, sp) = super::vram_small::bytes(); @@ -2722,7 +2770,7 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return false }; let mut complete = true; for (k, sub, first, n) in todo { - let Some((used, used_extra, _)) = pages.bind_range(dev, res, None, va, console_bytes, total, sub, first as usize..(first + n) as usize) else { + let Some((used, used_extra, _)) = pages.bind_range(dev, res, None, va, console_bytes, total, sub, first as usize..(first + n) as usize, &[]) else { complete = false; continue; }; diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 8353160490..d34b4d22e6 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -1202,6 +1202,16 @@ pub fn physical_page_at(va: usize) -> bool { AWAY.lock().unwrap().as_ref().is_some_and(|a| a.at.contains_key(&(va & !(PHYS_PAGE - 1)))) } +/// The physical page mapped away from home at each of the `n` 64 KiB pages from `va` (None: none +/// there, or a page at its home). The console maps one page at several addresses at once; here it +/// is at one (`map_pages` moves it), so `d3d12x::vram` asks which page an address had to let +/// textures at two addresses of one page share its video memory. +pub fn physical_pages(va: usize, n: usize) -> Vec> { + let g = AWAY.lock().unwrap(); + let Some(a) = g.as_ref() else { return vec![None; n] }; + (0..n).map(|i| va.checked_add(i * PHYS_PAGE).and_then(|at| a.at.get(&at).copied())).collect() +} + /// Counts the calls that map or unmap physical pages in a GPU view (`mirrors`): what /// `physical_page_at` says there may have changed. static GPU_VIEW_MAP_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); From f35b75ebc8721993ad64df93314f591b558f8fd2 Mon Sep 17 00:00:00 2001 From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 13:47:57 +0500 Subject: [PATCH 214/258] Recompiler: share translated DXIL across repeated pipeline builds (#2609) console_to_dxil_in clones the cached Compiled on every call, so a RAM hit still copied the whole DXIL blob and sampler list for each pipeline build of one shader. Compiled.dxil (and TwoPass.cs, Chain.whole_code, the two-pass PS slots) are now Arc'd: the hit clone bumps a refcount and carries the cached bytes, and a dispatch chain keeps that allocation instead of copying it again in build(). The deep-copy assertion in shader_cache_skips_repeated_translation_and_disk_lookups became a sharing assertion; a new test pins the property on the cached_shader hit path. Assisted-by: Devin (SWE-2 High) --- crates/xcl/src/gpu/recomp/pso.rs | 78 ++++++++++++------- crates/xcl/src/hle/d3d12x/real.rs | 20 ++--- .../xcl/src/hle/d3d12x/real/dispatch_chain.rs | 6 +- crates/xcl/src/shaders.rs | 4 +- 4 files changed, 64 insertions(+), 44 deletions(-) diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 2eff3853b9..ca917482de 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -124,10 +124,11 @@ pub fn heap_flat() -> bool { pub type StaticSampler = ([u32; 4], bool); /// A console shader as PC DXIL and the static samplers it needs in its root signature. +/// `dxil` is shared: a RAM-hit clone hands out the same bytes, not a copy (#2609). #[derive(Clone)] pub struct Compiled { pub dispatch_chain: Option>, - pub dxil: Vec, + pub dxil: std::sync::Arc>, pub samplers: Vec, } @@ -343,7 +344,7 @@ mod translated { if !rest.is_empty() { return None; } Some(std::sync::Arc::new(crate::gpu::dxil::kernel::DispatchChain { dwords_per_group, pieces })) }; - Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain }) + Some(Compiled { dxil: whole.to_vec().into(), samplers, dispatch_chain }) } pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) { @@ -662,7 +663,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; - Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }, false)) + Ok((Compiled { dispatch_chain: None, dxil: dxil.into(), samplers: t.static_samplers }, false)) } /// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. @@ -997,7 +998,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo Ok(k) => { crate::gpu::dxil::coverage::record_translated("CS per-lane"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil.into(), samplers: k.static_samplers }); } Err(e) => { let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); @@ -1007,7 +1008,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } let k = crate::gpu::dxil::kernel::translate_compute_rodata(code, o, &cs, &rodata)?; dump_direct(blob, &k.dxil); - Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil.into(), samplers: k.static_samplers }) } /// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's @@ -1043,7 +1044,7 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - }; let k = crate::gpu::dxil::kernel::translate_entry_rodata(code, o, entry, &f.rodata(p))?; dump_direct(blob, &k.dxil); - Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil: k.dxil.into(), samplers: k.static_samplers }) } pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(super::Translation, &'static str), String> { @@ -1094,7 +1095,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, /// then a pass-through mesh shader rasterises the records with the pixel shader. pub struct TwoPass { /// compute pass (cs_6_6 DXIL) - pub cs: Vec, + pub cs: std::sync::Arc>, /// pass-through mesh shader (ms_6_6 DXIL) pub ms: Vec, pub record: super::MsInterface, @@ -1118,7 +1119,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option return Err(format!("incomplete translation, missing: {missing:?}")); } let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers }, record, ps) + finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs.into(), samplers: t.static_samplers }, record, ps) } fn compile_console_mesh( @@ -1145,7 +1146,7 @@ fn compile_console_mesh( Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil.into(), samplers: k.static_samplers }); } Err(e) => direct_fallback("MS", &e), } @@ -1156,7 +1157,7 @@ fn compile_console_mesh( return Err(format!("incomplete translation, missing: {missing:?}")); } let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil: dxil.into(), samplers: t.static_samplers }) } fn console_mesh_with( @@ -1264,7 +1265,7 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b let ps_inputs = ps.map(|p| crate::gpu::dxbc::signatures(p).0); let msb = dxc::compile_cached(&super::emit::mesh_passthrough_for(&record, ps_inputs.as_deref()), "main", "ms_6_6")?.0; let mesh_groups_per_record = super::emit::passthrough_split(&record, super::emit::passthrough_elements(&record, ps_inputs.as_deref())); - return Ok(TwoPass { cs: k.dxil, ms: msb, record, mesh_groups_per_record, samplers: k.static_samplers }); + return Ok(TwoPass { cs: k.dxil.into(), ms: msb, record, mesh_groups_per_record, samplers: k.static_samplers }); } Err(e) => direct_fallback("GS", &e), } @@ -1771,7 +1772,7 @@ mod shader_cache_tests { fn translations_on_disk_need_the_same_bytes_and_identity() { let dir = std::env::temp_dir().join(format!("xcl-translated-{}", std::process::id())); let path = dir.join("t.bin"); - let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; + let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5).into(), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; translated::store_in(&path, 42, b"console", &c); let back = translated::load_in(&path, 42, b"console").expect("stored"); assert_eq!((back.dxil, back.samplers), (c.dxil.clone(), c.samplers.clone())); @@ -1802,7 +1803,7 @@ mod shader_cache_tests { }) .unwrap(); assert_eq!(calls, 1); - assert_eq!(first.dxil, synthetic_dxil(7)); + assert_eq!(*first.dxil, synthetic_dxil(7)); assert!(unnamespaced.exists()); assert!(translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false).exists()); @@ -2007,7 +2008,7 @@ mod shader_cache_tests { // Store a valid entry first, then corrupt only the DXIL payload while keeping the // XCLTRAN2 header and payload length intact (e.g. zeroed blocks after a hard reset). - let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)] }; + let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1).into(), samplers: vec![([1, 2, 3, 4], false)] }; translated::store_in(&path, ident, blob, &valid); let mut raw = std::fs::read(&path).unwrap(); let dxil_start = raw.len() - valid.dxil.len(); @@ -2016,7 +2017,7 @@ mod shader_cache_tests { assert!(translated::load_in(&path, ident, blob).is_none(), "zeroed DXIL payload must not load as a cache hit"); // Also corrupt only the inner DXIL magic inside an otherwise valid-looking DXBC chunk. - let mut bad_inner = valid.dxil.clone(); + let mut bad_inner = (*valid.dxil).clone(); bad_inner[52..56].fill(0); raw[dxil_start..].copy_from_slice(&bad_inner); std::fs::write(&path, &raw).unwrap(); @@ -2026,17 +2027,17 @@ mod shader_cache_tests { let mut calls = 0usize; let rebuilt = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { calls += 1; - Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)] }) + Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9).into(), samplers: vec![([5, 6, 7, 8], true)] }) }) .unwrap(); assert_eq!(calls, 1); - assert_eq!(rebuilt.dxil, synthetic_dxil(9)); + assert_eq!(*rebuilt.dxil, synthetic_dxil(9)); let cached = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { panic!("rebuilt translated cache entry was not reused") }) .unwrap(); - assert_eq!(cached.dxil, synthetic_dxil(9)); + assert_eq!(*cached.dxil, synthetic_dxil(9)); assert_eq!(cached.samplers, vec![([5, 6, 7, 8], true)]); let _ = std::fs::remove_dir_all(&dir); } @@ -2050,35 +2051,35 @@ mod shader_cache_tests { let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false); let err = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec().into(), samplers: Vec::new() }) }) .err() .expect("invalid fresh DXIL must be rejected"); assert!(err.contains("invalid DXIL container"), "{err}"); assert!(!path.exists(), "invalid fresh DXIL must not be written to disk"); - translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }); + translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec().into(), samplers: Vec::new() }); assert!(!path.exists(), "store_in must not write an invalid DXIL container"); // A real container emitted by the direct DXIL backend must be accepted and cached. let real_direct = crate::gpu::dxil::shader::Shader::new(crate::gpu::dxil::container::Stage::Compute, (6, 6)).finish([1, 1, 1], None); let stored = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone().into(), samplers: Vec::new() }) }) .unwrap(); - assert_eq!(stored.dxil, real_direct); + assert_eq!(*stored.dxil, real_direct); let hit = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { panic!("valid direct DXIL entry was not reused") }) .unwrap(); - assert_eq!(hit.dxil, real_direct); + assert_eq!(*hit.dxil, real_direct); let _ = std::fs::remove_dir_all(&dir); } fn compiled(marker: u8) -> Compiled { Compiled { dispatch_chain: None, - dxil: synthetic_dxil(marker), + dxil: synthetic_dxil(marker).into(), samplers: vec![([marker as u32; 4], false)], } } @@ -2103,12 +2104,31 @@ mod shader_cache_tests { } assert_eq!(calls, 1); let mut owned = first.as_ref().clone(); - owned.dxil[67] = 99; owned.samplers.clear(); + // the clone shares the translated bytes instead of copying them: callers only read + assert!(Arc::ptr_eq(&first.dxil, &owned.dxil)); assert_eq!(first.dxil[67], 7); assert_eq!(first.samplers.len(), 1); } + /// The clone `console_to_dxil_in` hands a caller on a RAM hit carries the cached entry's + /// own bytes: repeated pipeline builds of one shader do not allocate and copy its whole + /// DXIL again (#2609). `as_ptr` compares the byte storage, not the `Arc`s. + #[test] + fn a_ram_hit_clone_shares_the_translated_bytes() { + let cache = Mutex::new(ShaderCache::new(1 << 20)); + let first = cached_shader(&cache, key(1), b"a", || Ok(compiled(7))).unwrap(); + for _ in 0..8 { + let next = cached_shader(&cache, key(1), b"a", || panic!("repeated shader reached the compiler path")) + .unwrap() + .as_ref() + .clone(); + assert!(std::ptr::eq(first.dxil.as_ptr(), next.dxil.as_ptr()), "the RAM hit copied the whole DXIL"); + assert_eq!(*next.dxil, *first.dxil); + assert_eq!(next.samplers, first.samplers); + } + } + #[test] fn shader_cache_checks_context_and_blob_bytes() { let cache = Mutex::new(ShaderCache::new(1 << 20)); @@ -2154,7 +2174,7 @@ mod shader_cache_tests { let dxil = dxc::compile_cached_in(&dir, "probe", "main", "cs_6_6")?.0; Ok(Compiled { dispatch_chain: None, - dxil, + dxil: dxil.into(), samplers: Vec::new(), }) }) @@ -2188,7 +2208,7 @@ mod shader_cache_tests { b"d", Arc::new(Compiled { dispatch_chain: None, - dxil: vec![0; limit + 1], + dxil: vec![0; limit + 1].into(), samplers: Vec::new(), }), ); @@ -2363,7 +2383,7 @@ mod shader_cache_tests { dxc::compile_cached_in(&dir, "pending probe", "main", "cs_6_6")?.0; Ok(Compiled { dispatch_chain: None, - dxil, + dxil: dxil.into(), samplers: Vec::new(), }) }) @@ -2453,7 +2473,7 @@ mod shader_cache_tests { let (res, missed) = dxc::cached_only(|| { translated::cached_in(&dir, ident_v1, deferred_blob, Stage::Compute, 0, 1, false, || { let dxil = dxc::compile_cached_in(&dir, "deferred probe", "main", "cs_6_6")?.0; - Ok(Compiled { dxil, samplers: Vec::new(), dispatch_chain: None }) + Ok(Compiled { dxil: dxil.into(), samplers: Vec::new(), dispatch_chain: None }) }) }); assert!(res.is_err() && missed); diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 85eb006bf4..5581c5f064 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5605,7 +5605,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const } let record = crate::gpu::shader::fnv64(cs); if let Some(plan) = compiled.dispatch_chain { - if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, &dxil, &compiled.samplers, plan) { + if let Some(rs) = dispatch_chain::build(this, f, d, riid, ppv, record, dxil.clone(), &compiled.samplers, plan) { LAST_COMPUTE_RS.with(|c| c.set(rs)); note_pso_rs(*ppv, rs as *mut c_void); super::dred::label_text(*ppv as usize, || format!("cs {record:016x} piece 0")); @@ -6671,7 +6671,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const return None; } }, - Some(p) => Some(p.to_vec()), + Some(p) => Some(p.to_vec().into()), None => None, }; // Large translated graphics pipelines (>= huge_pso_bytes) defer off the title thread when @@ -6685,7 +6685,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let mut copy: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop>>(rs); copy.VS = bytecode(&vs_dxil); - copy.PS = ps_dxil.as_deref().map(bytecode).unwrap_or_default(); + copy.PS = ps_dxil.as_deref().map(|v| bytecode(v)).unwrap_or_default(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); // a rect list pipeline: the fourth corner of each rect comes from a generated GS; without // it each rect is drawn as the triangle of its three vertices @@ -6724,8 +6724,8 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } - let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); - let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); + let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, |v| v.len()) + rect_gs.as_ref().map_or(0, Vec::len); + let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref().map(Vec::as_slice), rect_gs.as_deref(), &samplers); let mut cached = graphics_blob(gkey); let disk = driver_cache::graphics_path(gkey.0, gkey.1); let from_disk = cached.is_none(); @@ -7559,11 +7559,11 @@ mod two_pass_identity; /// The console PS of a two-pass pipeline (a PC PS passes as it is). /// The PS of a two-pass pipeline (DXIL, static samplers – a PC PS passes as it is). -fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option>, Vec), String> { +fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option>>, Vec), String> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; match ps { Some(p) if is_console(p) => console_to_dxil_for(p, Stage::Pixel, 0, split_wave64).map(|c| (Some(c.dxil), c.samplers)).map_err(|e| format!("PS: {e}")), - Some(p) => Ok((Some(p.to_vec()), Vec::new())), + Some(p) => Ok((Some(p.to_vec().into()), Vec::new())), None => Ok((None, Vec::new())), } } @@ -7901,7 +7901,7 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri } let Some(rs) = abi_rs_for(this, &ps_samplers) else { return Some(E_INVALIDARG) }; // the title's state (blend, rasteriser, depth, formats …) with XCL's RS and shaders - let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref()); + let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref().map(Vec::as_slice)); // Extract PC-mapped render target formats upfront so BLEND (type 8) can be sanitized for // integer RTVs regardless of subobject order in the stream. let mut rt_count = 0u32; @@ -8001,7 +8001,7 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE } }; let Some(rs) = abi_rs_for(this, &ps_samplers) else { return E_INVALIDARG }; - let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref()); + let mut out = two_pass_mesh_stream(rs, &tp.ms, ps.as_deref().map(Vec::as_slice)); let mut rt = D3D12_RT_FORMAT_ARRAY { NumRenderTargets: d.NumRenderTargets, RTFormats: d.RTVFormats }; for f in rt.RTFormats.iter_mut() { *f = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_target_format(f.0 as u32) as i32); @@ -10595,7 +10595,7 @@ mod mesh_stream_tests { let _cleanup = Cleanup { ext: ext_vtbl, key }; let make_tp = || crate::gpu::recomp::pso::TwoPass { - cs: vec![0; 16], + cs: vec![0; 16].into(), ms: vec![0; 16], record: crate::gpu::recomp::MsInterface { outputs: Vec::new(), threads: 32, max_vertices: 3, max_primitives: 1, params: None }, mesh_groups_per_record: 1, diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 7d31906474..56959d52ce 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -104,7 +104,7 @@ struct Chain { builder: Arc, tail: Vec, words: u32, - whole_code: Vec, + whole_code: Arc>, whole: OnceLock>, whole_started: AtomicBool, /// after a whole build that ran out of memory: when it may be tried, once more @@ -286,7 +286,7 @@ unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler]) -> } pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, - iid: *const GUID, result: *mut *mut c_void, record: u64, whole: &[u8], samplers: &[pso::StaticSampler], + iid: *const GUID, result: *mut *mut c_void, record: u64, whole: Arc>, samplers: &[pso::StaticSampler], plan: Arc) -> Option { if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; } let dev = ID3D12Device::from_raw_borrowed(&this)?; @@ -313,7 +313,7 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), + whole_code: whole, whole: OnceLock::new(), whole_started: AtomicBool::new(false), retry_at: Mutex::new(None), diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index b92fbe9fc0..7fcdc87ed4 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1312,7 +1312,7 @@ mod pipeline_cap_tests { pipelines.max_dxil = dxil.len() - 1; let start = Instant::now(); - pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); + pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone().into(), samplers: vec![] }, Some(path.clone())); let elapsed = start.elapsed(); let capped = pipelines.capped.load(Ordering::Relaxed); let made = pipelines.made.load(Ordering::Relaxed); @@ -1391,7 +1391,7 @@ mod pipeline_cap_tests { pieces: vec![piece0.clone(), piece1.clone()], dwords_per_group: 4, })), - dxil: whole.clone(), + dxil: whole.clone().into(), samplers: vec![], }; From c45c45ed8dc72a8d4c7d57edce689f9e0e6a3ae6 Mon Sep 17 00:00:00 2001 From: Bloxive Date: Mon, 23 Nov 2026 21:15:50 -0400 Subject: [PATCH 215/258] GameInput: retain recent gamepad readings between polls Return the next and previous readings of the virtual gamepad from a bounded stream. Use the same retained objects for current and callback reads and keep guest callbacks off the sampler thread. --- README.md | 1 + crates/xcl/src/hle/gameinput.rs | 480 +++++++++++++++++++++++++++----- 2 files changed, 408 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index 8413f755c0..6b81edf11d 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,7 @@ A **gamepad is recommended**: console games are made for one, and their menus an - **Gamepad:** any controller Windows sees through XInput (Xbox controllers, wired or wireless) is the game's gamepad – buttons, sticks, triggers and rumble. It can be plugged in or out while the game runs. + GameInput keeps half a second of recent state changes so titles can read inputs between frames. - **PlayStation controllers** (DualShock 4 wired or over Bluetooth, DualSense wired) are the gamepad when no XInput controller is connected – buttons, sticks and triggers, no rumble or light bar. `XCL_PLAYSTATION_PAD=0` turns this off. diff --git a/crates/xcl/src/hle/gameinput.rs b/crates/xcl/src/hle/gameinput.rs index e7983a8929..58aeb5c106 100644 --- a/crates/xcl/src/hle/gameinput.rs +++ b/crates/xcl/src/hle/gameinput.rs @@ -2,20 +2,21 @@ //! //! The title gets the console's GameInput interfaces (the public GameInput.h of the GDK, v0: //! IGameInput, IGameInputDevice, IGameInputReading as COM objects with the methods in that -//! header's order) with one device: a gamepad that is always connected. A reading is the -//! state at the moment it is asked for – the PC's first XInput controller (else a PlayStation -//! controller, `playstation`), and the keyboard -//! while a window of this process has the focus (Enter / Space A, Escape / Backspace B, +//! header's order) with one device: a gamepad that is always connected. Readings sample +//! the PC's first XInput controller (or a PlayStation controller when XInput is absent) and +//! the keyboard while a window of this process has the focus (Enter / Space A, Escape / Backspace B, //! arrows the D-pad, Tab View, P Menu). Windows' own GameInput.dll is not used: its //! interfaces are not the console's and it reads only for a foreground app of its own. //! Device callbacks report the gamepad (at once for a blocking enumeration, from another -//! thread for an asynchronous one); reading callbacks get a reading when the state changes -//! (polled at 250 Hz). Methods not listed log their slot once and fail. +//! thread for an asynchronous one). One poller samples the gamepad about every 4 ms. +//! State changes enter a half-second history and reach the reading callbacks. +//! Methods not listed log their slot once and fail. //! //! `XCL_PRESS_A_AT=s1,s2…`: press A for 200 ms at those seconds after start (tests). #![allow(non_snake_case)] +use std::collections::VecDeque; use std::ffi::c_void; use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock}; @@ -28,6 +29,7 @@ use crate::util::{E_NOINTERFACE, E_NOTIMPL, E_POINTER, HRESULT, S_OK}; const GAMEINPUT_E_DEVICE_NOT_FOUND: HRESULT = 0x838A_0002_u32 as i32; const GAMEINPUT_E_READING_NOT_FOUND: HRESULT = 0x838A_0003_u32 as i32; +const GAMEINPUT_E_REFERENCE_READING_TOO_OLD: HRESULT = 0x838A_0004_u32 as i32; // Verified GameInput v0 interface GUIDs (Windows SDK / GDK `GameInput.h`). const IID_IUNKNOWN: GUID = GUID::from_u128(0x00000000_0000_0000_c000_000000000046); @@ -454,8 +456,8 @@ fn input() -> *mut Object { (2, release as usize), (3, get_current_timestamp as usize), (4, get_current_reading as usize), - (5, other_reading as usize), - (6, other_reading as usize), + (5, other_reading:: as usize), + (6, other_reading:: as usize), (7, get_temporal_reading as usize), (8, register_reading_callback as usize), (9, register_device_callback as usize), @@ -513,10 +515,113 @@ fn reading_vtable() -> *const usize { }) as *const usize } -static SEQUENCE: AtomicU64 = AtomicU64::new(0); +/// One owned COM reference, held by the history or a callback dispatch. +struct OwnedReading(*mut Reading); -fn new_reading(state: GamepadState) -> *mut Reading { - Box::into_raw(Box::new(Reading { vtable: reading_vtable(), refs: AtomicU32::new(1), state, sequence: SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1, timestamp: now_us() })) +// SAFETY: a reading is immutable except for its atomic reference count. Its +// vtable has process lifetime, and this owner keeps the allocation alive. +unsafe impl Send for OwnedReading {} + +impl OwnedReading { + fn new(state: GamepadState, sequence: u64, timestamp: u64) -> Self { + Self(Box::into_raw(Box::new(Reading { + vtable: reading_vtable(), + refs: AtomicU32::new(1), + state, + sequence, + timestamp, + }))) + } + + fn reading(&self) -> &Reading { + // SAFETY: this owner holds a reference for at least the lifetime of the borrow. + unsafe { &*self.0 } + } + + fn into_raw(self) -> *mut Reading { + let ptr = self.0; + std::mem::forget(self); + ptr + } +} + +impl Clone for OwnedReading { + fn clone(&self) -> Self { + // SAFETY: self owns a reference. + unsafe { reading_add_ref(self.0) }; + Self(self.0) + } +} + +impl Drop for OwnedReading { + fn drop(&mut self) { + // SAFETY: release the reference owned by self. + unsafe { reading_release(self.0) }; + } +} + +const POLL_INTERVAL_MS: u64 = 4; +const HISTORY_US: u64 = 500_000; +const HISTORY_CAPACITY: usize = (HISTORY_US / (POLL_INTERVAL_MS * 1000)) as usize + 1; + +struct ReadingHistory { + readings: VecDeque, + /// A title can still use the reading preceding the retained window to + /// advance to its immediate successor after a long period of no input. + predecessor: Option, +} + +static HISTORY: Mutex = Mutex::new(ReadingHistory::new()); +static READING_READY: Condvar = Condvar::new(); + +impl ReadingHistory { + const fn new() -> Self { + Self { readings: VecDeque::new(), predecessor: None } + } + + fn prune(&mut self, now: u64) { + while self.readings.len() > 1 + && (self.readings.len() > HISTORY_CAPACITY + || self.readings.front().is_some_and(|r| now.saturating_sub(r.reading().timestamp) > HISTORY_US)) + { + self.predecessor = self.readings.pop_front(); + } + } + + fn sequence(&self) -> u64 { + self.readings.back().map_or(0, |r| r.reading().sequence) + } + + fn record(&mut self, state: GamepadState, now: u64) -> bool { + let changed = self.readings.back().is_none_or(|r| r.reading().state != state); + if changed { + let reading = OwnedReading::new(state, self.sequence() + 1, now); + self.readings.push_back(reading); + } + self.prune(now); + changed + } + + fn next_after(&self, sequence: u64) -> Option { + self.readings.iter().find(|r| r.reading().sequence > sequence).cloned() + } + + fn adjacent(&mut self, reference: *mut Reading, now: u64) -> Result { + self.prune(now); + let Some(index) = self.readings.iter().position(|r| r.0 == reference) else { + if NEXT && self.predecessor.as_ref().is_some_and(|r| r.0 == reference) { + return self + .readings + .front() + .filter(|r| now.saturating_sub(r.reading().timestamp) <= HISTORY_US) + .cloned() + .ok_or(GAMEINPUT_E_REFERENCE_READING_TOO_OLD); + } + return Err(GAMEINPUT_E_REFERENCE_READING_TOO_OLD); + }; + let neighbor = if NEXT { index.checked_add(1) } else { index.checked_sub(1) }; + neighbor.and_then(|i| self.readings.get(i)).cloned().ok_or(GAMEINPUT_E_READING_NOT_FOUND) + } } // ---- shared methods ---- @@ -622,6 +727,23 @@ fn note_query(what: &str, kind: u32) { unsafe extern "system" fn get_current_reading(_this: *mut Object, kind: u32, dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { note_query("GetCurrentReading", kind); + current_reading(kind, dev, out, || { + let started = start_poller(); + let mut history = HISTORY.lock().unwrap_or_else(|e| e.into_inner()); + // If the worker cannot start, current reads still sample the gamepad. + if !started && history.record(poll(), now_us()) { + READING_READY.notify_one(); + } + history.readings.back().cloned() + }) +} + +unsafe fn current_reading( + kind: u32, + dev: *mut c_void, + out: *mut *mut Reading, + latest: impl FnOnce() -> Option, +) -> HRESULT { if out.is_null() { return E_POINTER; } @@ -629,17 +751,50 @@ unsafe extern "system" fn get_current_reading(_this: *mut Object, kind: u32, dev if kind & KINDS == 0 || !ours(dev) { return GAMEINPUT_E_READING_NOT_FOUND; } - *out = new_reading(poll()); + let Some(reading) = latest() else { + return GAMEINPUT_E_READING_NOT_FOUND; + }; + *out = reading.into_raw(); S_OK } -/// the readings before and after one are not kept -unsafe extern "system" fn other_reading(_this: *mut Object, _reference: *mut c_void, kind: u32, _dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { +unsafe extern "system" fn other_reading( + _this: *mut Object, + reference: *mut Reading, + kind: u32, + dev: *mut c_void, + out: *mut *mut Reading, +) -> HRESULT { note_query("GetNext/PreviousReading", kind); - if !out.is_null() { - *out = std::ptr::null_mut(); + adjacent_reading::(&HISTORY, reference, kind, dev, out, now_us()) +} + +unsafe fn adjacent_reading( + history: &Mutex, + reference: *mut Reading, + kind: u32, + dev: *mut c_void, + out: *mut *mut Reading, + now: u64, +) -> HRESULT { + if out.is_null() { + return E_POINTER; + } + *out = std::ptr::null_mut(); + if reference.is_null() { + return E_POINTER; + } + if kind & KINDS == 0 || !ours(dev) { + return GAMEINPUT_E_READING_NOT_FOUND; + } + let mut history = history.lock().unwrap_or_else(|e| e.into_inner()); + match history.adjacent::(reference, now) { + Ok(reading) => { + *out = reading.into_raw(); + S_OK + } + Err(hr) => hr, } - GAMEINPUT_E_READING_NOT_FOUND } unsafe extern "system" fn get_temporal_reading(this: *mut Object, _timestamp: u64, dev: *mut c_void, out: *mut *mut Reading) -> HRESULT { @@ -652,7 +807,7 @@ type ReadingCallback = unsafe extern "system" fn(u64, *mut c_void, *mut Reading, type DeviceCallback = unsafe extern "system" fn(u64, *mut c_void, *mut Object, u64, u32, u32); enum CallbackKind { - Reading { ctx: usize, cb: ReadingCallback }, + Reading { ctx: usize, cb: ReadingCallback, after_sequence: u64 }, Device, } @@ -762,14 +917,22 @@ unsafe extern "system" fn register_reading_callback(_this: *mut Object, dev: *mu *token = t; } if let Some(cb) = cb.filter(|_| kind & KINDS != 0 && ours(dev)) { - let entry = Arc::new(CallbackEntry::new(t, CallbackKind::Reading { ctx: context as usize, cb })); - CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).push(entry); start_poller(); + let history = HISTORY.lock().unwrap_or_else(|e| e.into_inner()); + let after_sequence = history.sequence(); + track_reading_callback(t, context, cb, after_sequence); + start_reading_dispatcher(after_sequence); } S_OK } -fn dispatch_reading_callbacks(s: GamepadState) { +fn track_reading_callback(token: u64, context: *mut c_void, cb: ReadingCallback, after_sequence: u64) { + let entry = Arc::new(CallbackEntry::new(token, CallbackKind::Reading { ctx: context as usize, cb, after_sequence })); + CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()).push(entry); +} + +fn dispatch_reading_callbacks(reading: &OwnedReading, previous: u64) { + let sequence = reading.reading().sequence; let cbs: Vec> = CALLBACKS .lock() .unwrap_or_else(|e| e.into_inner()) @@ -778,38 +941,75 @@ fn dispatch_reading_callbacks(s: GamepadState) { .cloned() .collect(); for entry in cbs { - let CallbackKind::Reading { ctx, cb } = entry.kind else { continue }; + let CallbackKind::Reading { ctx, cb, after_sequence } = entry.kind else { continue }; + if sequence <= after_sequence { + continue; + } let Some(_guard) = entry.try_enter() else { continue }; - let r = new_reading(s); + let overrun = sequence - previous.max(after_sequence) > 1; // SAFETY: `cb` and `ctx` were registered by the caller; `_guard` keeps - // `UnregisterCallback` blocked until `cb` returns so `ctx` stays valid. - unsafe { - cb(entry.token, ctx as *mut c_void, r, false); - reading_release(r); - } + // `UnregisterCallback` blocked until `cb` returns, and reading is borrowed + // from a live owner throughout the call. + unsafe { cb(entry.token, ctx as *mut c_void, reading.0, overrun) }; } } -/// A thread that calls the reading callbacks when the gamepad's state changes. -fn start_poller() { +/// Deliver callbacks in order on a different thread so guest code cannot +/// stall sampling. If the worker falls behind, resume at the oldest retained +/// reading and report the skipped readings through the v0 overrun flag. +fn start_reading_dispatcher(after_sequence: u64) { static STARTED: OnceLock<()> = OnceLock::new(); STARTED.get_or_init(|| { - let _ = std::thread::Builder::new().name("xcl-gameinput".into()).spawn(|| { + let worker = std::thread::Builder::new().name("xcl-gameinput-callback".into()).spawn(move || { crate::eh::arm_current_thread(); - let mut last = GamepadState::default(); + let mut previous = after_sequence; loop { - std::thread::sleep(Duration::from_millis(4)); - let s = poll(); - if s == last { - continue; + let reading = { + let history = HISTORY.lock().unwrap_or_else(|e| e.into_inner()); + let mut history = READING_READY + .wait_while(history, |history| history.sequence() <= previous) + .unwrap_or_else(|e| e.into_inner()); + history.prune(now_us()); + history.next_after(previous) + }; + if let Some(reading) = reading { + dispatch_reading_callbacks(&reading, previous); + previous = reading.reading().sequence; } - last = s; - dispatch_reading_callbacks(s); } }); + if let Err(e) = worker { + crate::xlog_warn!("GameInput: could not start reading callback worker: {e}"); + } }); } +/// One sampler for current, historical and callback reads. In particular, +/// sampling consumes mouse deltas, so the query and worker must not both poll. +fn start_poller() -> bool { + static STARTED: OnceLock = OnceLock::new(); + *STARTED.get_or_init(|| { + // Seed before starting the worker or returning the first current reading. + let initial = poll(); + HISTORY.lock().unwrap_or_else(|e| e.into_inner()).record(initial, now_us()); + let worker = std::thread::Builder::new().name("xcl-gameinput".into()).spawn(|| { + crate::eh::arm_current_thread(); + loop { + std::thread::sleep(Duration::from_millis(POLL_INTERVAL_MS)); + let state = poll(); + if HISTORY.lock().unwrap_or_else(|e| e.into_inner()).record(state, now_us()) { + READING_READY.notify_one(); + } + } + }); + if let Err(e) = worker { + crate::xlog_warn!("GameInput: could not start reading poller: {e}"); + return false; + } + true + }) +} + /// RegisterDeviceCallback(device, kind, status filter, enumeration kind, context, callback, /// &token): the gamepad, connected – at once for a blocking enumeration, from another /// thread for an asynchronous one, not at all without enumeration (it never comes or goes) @@ -1014,18 +1214,133 @@ mod tests { #[test] fn readings_come_and_go() { unsafe { - let g = input(); + let reading = OwnedReading::new(GamepadState { buttons: A, ..Default::default() }, 1, 1); let mut r = std::ptr::null_mut(); - assert_eq!(get_current_reading(g, KIND_GAMEPAD, std::ptr::null_mut(), &mut r), S_OK); - let mut s = GamepadState { buttons: 99, ..Default::default() }; + assert_eq!(current_reading(KIND_GAMEPAD, std::ptr::null_mut(), &mut r, || Some(reading.clone())), S_OK); + assert_eq!(r, reading.0); + let mut s = GamepadState::default(); assert!(reading_gamepad(r, &mut s)); - assert_ne!(s.buttons, 99); + assert_eq!(s.buttons, A); let mut d = std::ptr::null_mut(); reading_device(r, &mut d); assert_eq!(d, device()); - assert_eq!(reading_release(r), 0); - assert_eq!(get_current_reading(g, 0x10, std::ptr::null_mut(), &mut r), GAMEINPUT_E_READING_NOT_FOUND, "keyboard kind"); + assert_eq!(reading_release(r), 1); + assert_eq!( + current_reading(0x10, std::ptr::null_mut(), &mut r, || panic!("keyboard kind")), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert!(r.is_null()); + } + } + + fn record_test_reading(history: &mut ReadingHistory, buttons: u32, now: u64) -> OwnedReading { + assert!(history.record(GamepadState { buttons, ..Default::default() }, now)); + history.readings.back().unwrap().clone() + } + + #[test] + fn adjacent_readings_preserve_a_tap_after_idle() { + let pressed_at = HISTORY_US + 2; + let now = pressed_at + 3; + let history = Mutex::new(ReadingHistory::new()); + let (neutral, pressed, released) = { + let mut stream = history.lock().unwrap(); + let neutral = record_test_reading(&mut stream, 0, 1); + let pressed = record_test_reading(&mut stream, A, pressed_at); + assert!(!stream.record(pressed.reading().state, pressed_at + 1)); + let released = record_test_reading(&mut stream, 0, pressed_at + 2); + assert_eq!(stream.readings.back().unwrap().0, released.0); + (neutral, pressed, released) + }; + // Use the same out-pointer and filtering path as the IGameInput vtable. + let mut out = std::ptr::null_mut(); + unsafe { + let any_device = std::ptr::null_mut(); + assert_eq!(adjacent_reading::(&history, neutral.0, KIND_GAMEPAD, any_device, &mut out, now), S_OK); + assert_eq!(out, pressed.0); + let mut state = GamepadState::default(); + assert!(reading_gamepad(out, &mut state)); + assert_eq!(state.buttons, A); + assert_eq!(reading_timestamp(out), pressed_at); + assert!(reading_sequence(out, KIND_GAMEPAD) > reading_sequence(neutral.0, KIND_GAMEPAD)); + reading_release(out); + + assert_eq!(adjacent_reading::(&history, pressed.0, KIND_GAMEPAD, any_device, &mut out, now), S_OK); + assert_eq!(out, released.0); + assert!(reading_gamepad(out, &mut state)); + assert_eq!(state.buttons, 0); + reading_release(out); + + let gamepad = device().cast(); + assert_eq!(adjacent_reading::(&history, released.0, KIND_GAMEPAD, gamepad, &mut out, now), S_OK); + assert_eq!(out, pressed.0); + reading_release(out); + + assert_eq!( + adjacent_reading::(&history, released.0, KIND_GAMEPAD, gamepad, &mut out, now), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert!(out.is_null()); + } + } + + #[test] + fn adjacent_readings_check_inputs_and_keep_caller_references_alive() { + use std::ptr::{dangling_mut, null_mut}; + let history = Mutex::new(ReadingHistory::new()); + let (old, latest) = { + let mut stream = history.lock().unwrap(); + let old = record_test_reading(&mut stream, A, 1); + let latest = record_test_reading(&mut stream, 0, HISTORY_US + 1); + (old, latest) + }; + let valid = KIND_GAMEPAD; + let mut out = dangling_mut(); + unsafe { + assert_eq!(adjacent_reading::(&history, old.0, valid, null_mut(), null_mut(), 1), E_POINTER); + assert_eq!(adjacent_reading::(&history, null_mut(), valid, null_mut(), &mut out, 1), E_POINTER); + assert!(out.is_null()); + assert_eq!( + adjacent_reading::(&history, old.0, 0x10, null_mut(), &mut out, 1), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert_eq!( + adjacent_reading::(&history, old.0, valid, dangling_mut::().cast(), &mut out, 1), + GAMEINPUT_E_READING_NOT_FOUND + ); + + // At the retention boundary the old reading is still available. + assert_eq!(adjacent_reading::(&history, latest.0, valid, null_mut(), &mut out, HISTORY_US + 1), S_OK); + assert_eq!(out, old.0); + let caller_ref = out; + drop(old); + assert_eq!( + adjacent_reading::(&history, latest.0, valid, null_mut(), &mut out, HISTORY_US + 2), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert!(out.is_null()); + // The predecessor cannot advance when its successor is also expired, + // even though that successor remains available as the current reading. + assert_eq!( + adjacent_reading::(&history, caller_ref, valid, null_mut(), &mut out, 2 * HISTORY_US + 2), + GAMEINPUT_E_REFERENCE_READING_TOO_OLD + ); + assert!(out.is_null()); + assert_eq!(reading_timestamp(caller_ref), 1); + let mut state = GamepadState::default(); + assert!(reading_gamepad(caller_ref, &mut state)); + assert_eq!(state.buttons, A); + reading_release(caller_ref); + + assert_eq!( + adjacent_reading::(&history, latest.0, valid, null_mut(), &mut out, 3 * HISTORY_US), + GAMEINPUT_E_READING_NOT_FOUND + ); + assert!(out.is_null()); } + let stream = history.lock().unwrap(); + assert_eq!(stream.readings.len(), 1); + assert_eq!(stream.readings.back().unwrap().0, latest.0); } #[test] @@ -1131,7 +1446,7 @@ mod tests { assert_eq!(call_qi(d, &IID_IGAMEINPUT_DEVICE, std::ptr::null_mut()), E_POINTER); // IGameInputReading (refcounted) - let r = new_reading(GamepadState::default()); + let r = OwnedReading::new(GamepadState::default(), 1, now_us()).into_raw(); let rp = r as *mut c_void; out = sentinel; assert_eq!(call_qi(rp, &IID_IUNKNOWN, &mut out), S_OK); @@ -1219,21 +1534,54 @@ mod tests { static READING_CB_TEST_LOCK: Mutex<()> = Mutex::new(()); + // These tests drive dispatch explicitly so no host input changes can + // invoke their callbacks or hold up their synchronization handshake. + fn track_test_reading_callback(context: *mut c_void, cb: ReadingCallback) -> u64 { + let token = TOKENS.fetch_add(1, Ordering::Relaxed) + 1; + track_reading_callback(token, context, cb, 0); + token + } + + fn dispatch_test_reading(buttons: u32) { + let reading = OwnedReading::new(GamepadState { buttons, ..Default::default() }, 1, now_us()); + dispatch_reading_callbacks(&reading, 0); + } + + #[test] + fn callback_history_filters_old_readings_and_reports_overrun() { + let _serial = READING_CB_TEST_LOCK.lock().unwrap(); + unsafe extern "system" fn record_delivery(_token: u64, ctx: *mut c_void, _r: *mut Reading, overrun: bool) { + // SAFETY: the test keeps this counter alive until unregistering. + unsafe { &*ctx.cast::() }.store(if overrun { 2 } else { 1 }, Ordering::Relaxed); + } + let mut history = ReadingHistory::new(); + let initial = record_test_reading(&mut history, 0, 1); + let sequence = history.sequence(); + let delivered = AtomicU32::new(0); + let token = TOKENS.fetch_add(1, Ordering::Relaxed) + 1; + track_reading_callback(token, (&raw const delivered).cast_mut().cast(), record_delivery, sequence); + dispatch_reading_callbacks(&initial, 0); + let delivered_before = delivered.load(Ordering::Relaxed); + + history.record(GamepadState { buttons: A, ..Default::default() }, 2); + let latest = record_test_reading(&mut history, 0, HISTORY_US + 3); + let recovered = history.next_after(sequence).unwrap(); + dispatch_reading_callbacks(&recovered, sequence); + assert!(unsafe { unregister_callback(input(), token, 0) }); + assert_eq!(delivered_before, 0, "pre-registration readings aren't dispatched"); + assert_eq!(recovered.0, latest.0); + assert_eq!(delivered.load(Ordering::Relaxed), 2, "expired unread readings set overrun"); + } + #[test] fn unregister_reading_callback_waits_for_in_flight_and_prevents_uaf() { let _serial = READING_CB_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let gate = Arc::new(CallbackGate::new()); let g = input(); - let mut token = 0u64; - unsafe { - assert_eq!( - register_reading_callback(g, std::ptr::null_mut(), KIND_GAMEPAD, 0.0, Arc::as_ptr(&gate) as *mut c_void, Some(gated_reading_cb), &mut token), - S_OK - ); - } + let token = track_test_reading_callback(Arc::as_ptr(&gate) as *mut c_void, gated_reading_cb); let dispatch_thread = std::thread::spawn(|| { - dispatch_reading_callbacks(GamepadState { buttons: A, ..Default::default() }); + dispatch_test_reading(A); }); gate.wait_entered(); @@ -1259,7 +1607,7 @@ mod tests { // Subsequent dispatches must never invoke the unregistered callback again. let calls_before = gate.calls.load(Ordering::Acquire); - dispatch_reading_callbacks(GamepadState { buttons: B, ..Default::default() }); + dispatch_test_reading(B); assert_eq!(gate.calls.load(Ordering::Acquire), calls_before); } @@ -1268,16 +1616,10 @@ mod tests { let _serial = READING_CB_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let gate = Arc::new(CallbackGate::new()); let g = input(); - let mut token = 0u64; - unsafe { - assert_eq!( - register_reading_callback(g, std::ptr::null_mut(), KIND_GAMEPAD, 0.0, Arc::as_ptr(&gate) as *mut c_void, Some(gated_reading_cb), &mut token), - S_OK - ); - } + let token = track_test_reading_callback(Arc::as_ptr(&gate) as *mut c_void, gated_reading_cb); let dispatch_thread = std::thread::spawn(|| { - dispatch_reading_callbacks(GamepadState { buttons: X, ..Default::default() }); + dispatch_test_reading(X); }); gate.wait_entered(); @@ -1316,21 +1658,13 @@ mod tests { calls: AtomicU32::new(0), unreg_ok: std::sync::atomic::AtomicBool::new(false), }); - let g = input(); - let mut token = 0u64; - unsafe { - assert_eq!( - register_reading_callback(g, std::ptr::null_mut(), KIND_GAMEPAD, 0.0, &*ctx as *const SelfCtx as *mut c_void, Some(self_unreg_cb), &mut token), - S_OK - ); - } - - dispatch_reading_callbacks(GamepadState { buttons: Y, ..Default::default() }); + track_test_reading_callback(&*ctx as *const SelfCtx as *mut c_void, self_unreg_cb); + dispatch_test_reading(Y); assert_eq!(ctx.calls.load(Ordering::Acquire), 1); assert!(ctx.unreg_ok.load(Ordering::Acquire)); // Must not fire again after self-unregister. - dispatch_reading_callbacks(GamepadState { buttons: MENU, ..Default::default() }); + dispatch_test_reading(MENU); assert_eq!(ctx.calls.load(Ordering::Acquire), 1); } From 7d9be015bcb7d4a12581a99da37fbe700919b931 Mon Sep 17 00:00:00 2001 From: Bloxive Date: Wed, 25 Nov 2026 15:18:33 -0400 Subject: [PATCH 216/258] D3D12.X: canonicalize inactive two-pass stream descriptors Zero-count stream output, input layouts, and view instancing can carry inert pointer values and padding. Treat them and empty optional shader bytecode as omitted so the stream remains eligible for a stable two-pass cache key. Preserve rejection of unsupported active state. Assisted-by: Codex (GPT-6) --- .../src/hle/d3d12x/real/two_pass_identity.rs | 66 ++++++++++++++++++- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index 6ca0572281..c1e7efddc3 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -200,12 +200,31 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp for (ty, payload) in subs { match ty { 0 | 19 => {} // RS replaced by ABI RS via ps_samplers; CACHED_PSO is the lookup input - 7 | 12 | 22 => { - if payload.iter().any(|&b| b != 0) { + // These descriptors can carry inert pointers and padding in a title stream. + // Their counts and flags determine whether any state needs to be hashed. + 7 => { + let state = read_state::(payload)?; + if state.NumEntries != 0 || state.NumStrides != 0 || state.RasterizedStream != 0 { + return None; + } + } + 12 => { + let state = read_state::(payload)?; + if state.NumElements != 0 { + return None; + } + } + 22 => { + let state = read_state::(payload)?; + if state.ViewInstanceCount != 0 || state.Flags.0 != 0 { return None; } } 1..=6 | 24 | 25 => { + let state = read_state::(payload)?; + if state.BytecodeLength == 0 && ty != 25 { + continue; + } let code = payload_shader(payload)?; shader_bytes = shader_bytes.checked_add(code.len())?; h.u32(ty); @@ -333,6 +352,49 @@ mod tests { } } + #[test] + fn empty_stream_descriptors_do_not_change_the_key() { + let ms = [1u8, 2, 3, 4]; + let mut base = StreamOut::default(); + base.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, &ms); + let mut with_empty = StreamOut(base.0.clone(), base.1); + with_empty.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT, &D3D12_STREAM_OUTPUT_DESC { + pSODeclaration: 0x2000 as *const _, + pBufferStrides: 0x3000 as *const _, + ..Default::default() + }); + let mut input = [0u8; std::mem::size_of::()]; + input[..8].copy_from_slice(&0x4000u64.to_le_bytes()); + let padding = std::mem::offset_of!(D3D12_INPUT_LAYOUT_DESC, NumElements) + std::mem::size_of::(); + input[padding..].fill(0xaa); + with_empty.raw(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT.0 as u32, &input, true); + with_empty.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING, &D3D12_VIEW_INSTANCING_DESC { + pViewInstanceLocations: 0x5000 as *const _, + ..Default::default() + }); + let empty_shader = D3D12_SHADER_BYTECODE { pShaderBytecode: 0x6000 as *const _, BytecodeLength: 0 }; + for stage in [ + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_HS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS, + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS, + ] { + with_empty.put(stage, &empty_shader); + } + + unsafe { + let key = two_pass_stream_key(&base.0, &[], 1, 4).expect("base mesh key"); + assert_eq!(two_pass_stream_key(&with_empty.0, &[], 1, 4), Some(key)); + + let mut empty_ms = StreamOut::default(); + empty_ms.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS, &empty_shader); + assert_eq!(two_pass_stream_key(&empty_ms.0, &[], 1, 4), None); + } + } + #[test] fn two_pass_keys_cover_mem_windows_invalid_counts_and_duplicates() { let mut s = StreamOut::default(); From 7aec897568617cf3aaf5e1127c12c6bec4768fa5 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:13:05 +0100 Subject: [PATCH 217/258] d3d12x: fix Arc> and phys slice call sites after #2767 and #1182 merges --- crates/xcl/src/hle/d3d12x/real.rs | 8 ++++---- crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs | 11 ++++++----- crates/xcl/src/hle/d3d12x/vram.rs | 2 +- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 5581c5f064..e75ec08178 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -6677,7 +6677,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const // Large translated graphics pipelines (>= huge_pso_bytes) defer off the title thread when // `dxc::defer()` is active, matching `translated_compute_pso_once` so cold >= 256 KiB graphics // PSOs never stall title threads even when `XCL_LAZY_PSO=0`. - let big = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) >= huge_pso_bytes(); + let big = vs_dxil.len() + ps_dxil.as_ref().map_or(0, |v| v.len()) >= huge_pso_bytes(); if big && crate::gpu::recomp::dxc::defer() { return None; } @@ -6700,7 +6700,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const pc_topology_type(&mut copy); let ps_hash = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); let debug_override = debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash) || debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash); - let lib_key = (!debug_override).then(|| pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers)); + let lib_key = (!debug_override).then(|| pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref().map(Vec::as_slice), rect_gs.as_deref(), &samplers)); if let Some(key) = lib_key.as_deref() { if pso_lib::try_load_graphics(this, key, ©, riid, ppv) { let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); @@ -6776,7 +6776,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); if let Some(key) = lib_key { let final_key = if rect_gs.is_some() && copy.GS.pShaderBytecode.is_null() { - pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref(), None, &samplers) + pso_lib::graphics_key(©, &vs_dxil, ps_dxil.as_deref().map(Vec::as_slice), None, &samplers) } else { key }; @@ -7895,7 +7895,7 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri return Some(E_INVALIDARG); } }; - let big = tp.ms.len() + tp.cs.len() + ps.as_ref().map_or(0, Vec::len) >= huge_pso_bytes(); + let big = tp.ms.len() + tp.cs.len() + ps.as_ref().map_or(0, |v| v.len()) >= huge_pso_bytes(); if big && crate::gpu::recomp::dxc::defer() { return None; } diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 56959d52ce..a91822290f 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -1117,9 +1117,10 @@ mod tests { let plan_a = Arc::new(super::DispatchChain { pieces: vec![shared.clone(), tail_a.clone()], dwords_per_group: 4 }); let plan_b = Arc::new(super::DispatchChain { pieces: vec![shared.clone(), tail_b.clone()], dwords_per_group: 4 }); + let whole = Arc::new(whole); unsafe { let mut raw_a: *mut c_void = std::ptr::null_mut(); - let rs_a = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_a, 1, &whole, &[], plan_a.clone()).expect("build Program A"); + let rs_a = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_a, 1, whole.clone(), &[], plan_a.clone()).expect("build Program A"); cleanup.psos.push(ID3D12PipelineState::from_raw(raw_a)); cleanup.blob_keys.push(super::super::compute_blob_key(&shared, rs_a, 0)); cleanup.blob_keys.push(super::super::compute_blob_key(&tail_a, rs_a, 0)); @@ -1137,7 +1138,7 @@ mod tests { let plib_hits_before_b = super::PLIB_HITS.load(Ordering::Relaxed); let mut raw_b: *mut c_void = std::ptr::null_mut(); - let rs_b = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_b, 2, &whole, &[], plan_b).expect("build Program B"); + let rs_b = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_b, 2, whole.clone(), &[], plan_b).expect("build Program B"); cleanup.psos.push(ID3D12PipelineState::from_raw(raw_b)); cleanup.blob_keys.push(super::super::compute_blob_key(&tail_b, rs_b, 0)); let b_calls = std::mem::take(&mut *SPY_CALLS.lock().unwrap()); @@ -1158,7 +1159,7 @@ mod tests { drop(pso_a); let plib_hits_before_a2 = super::PLIB_HITS.load(Ordering::Relaxed); let mut raw_a2: *mut c_void = std::ptr::null_mut(); - let rs_a2 = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_a2, 3, &whole, &[], plan_a).expect("rebuild Program A"); + let rs_a2 = super::build(dev.as_raw(), spy_create, &base_desc, iid, &mut raw_a2, 3, whole.clone(), &[], plan_a).expect("rebuild Program A"); cleanup.psos.push(ID3D12PipelineState::from_raw(raw_a2)); let a2_calls = std::mem::take(&mut *SPY_CALLS.lock().unwrap()); assert_eq!(rs_a2, rs_a); @@ -1205,7 +1206,7 @@ mod tests { builder, tail: Vec::new(), words: 4, - whole_code: vec![0; 16], + whole_code: Arc::new(vec![0; 16]), whole: OnceLock::new(), whole_started: AtomicBool::new(false), retry_at: Mutex::new(None), @@ -1249,7 +1250,7 @@ mod tests { builder, tail: Vec::new(), words: 4, - whole_code: vec![0; 16], + whole_code: Arc::new(vec![0; 16]), whole: OnceLock::new(), whole_started: AtomicBool::new(false), retry_at: Mutex::new(None), diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index a070feb49f..262592ecb2 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -3937,7 +3937,7 @@ mod tests { assert!(total >= 1 && (total as usize) * PAGE <= span); let (used, extra, follows) = pages - .bind_with_follow(&dev, &res, None, va, Some(total as u64 * PAGE as u64), total) + .bind_with_follow(&dev, &res, None, va, Some(total as u64 * PAGE as u64), total, &[]) .expect("GPU-owned bind must map every tile even when title VA is uncommitted"); assert_eq!(used.len() + extra.len(), total as usize); assert!(follows.is_empty(), "GPU-owned target must not register FollowSkip entries"); From b44bb81921b2bb6492b44b16c207555e326d5656 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:21:03 +0100 Subject: [PATCH 218/258] d3d12x: AVX2 zero-skip + persistent ScanPool for sparse/texture scans and XCL_COHERENT_CAP_MB --- crates/xcl/src/gpu/uma.rs | 17 +- crates/xcl/src/hle/d3d12x/sparse.rs | 462 ++++++++++++++++++-- crates/xcl/src/hle/d3d12x/title_textures.rs | 72 ++- 3 files changed, 511 insertions(+), 40 deletions(-) diff --git a/crates/xcl/src/gpu/uma.rs b/crates/xcl/src/gpu/uma.rs index 73b08b4644..973d2669b9 100644 --- a/crates/xcl/src/gpu/uma.rs +++ b/crates/xcl/src/gpu/uma.rs @@ -802,11 +802,22 @@ fn coherent_file() -> std::path::PathBuf { crate::state::data_dir().join("cache").join("uma_coherent.txt") } +/// Optional upper cap on the coherent window(s) in bytes (`XCL_COHERENT_CAP_MB`), keeping +/// `uma_coherent.txt` auto-growth bounded so large general-purpose title heaps stay out of +/// GPU-writable Window 3 when desired. +fn coherent_cap_bytes(max_cap: usize) -> usize { + std::env::var("XCL_COHERENT_CAP_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map(|mb| (mb << 20).clamp(GRAIN, max_cap)) + .unwrap_or(max_cap) +} + /// Bytes the coherent window(s) are made with for a runtime layout of `windows` windows. pub fn coherent_hint_for(windows: usize) -> usize { - let cap = max_coherent_bytes(windows); + let cap = coherent_cap_bytes(max_coherent_bytes(windows)); if let Some(mb) = std::env::var("XCL_COHERENT_MB").ok().and_then(|v| v.parse::().ok()) { - return (mb << 20).clamp(GRAIN, cap); + return (mb << 20).clamp(GRAIN, max_coherent_bytes(windows)); } let title = std::fs::read_to_string(coherent_file()).ok().and_then(|s| s.trim().parse::().ok()).unwrap_or(0); // only with the commit for all of it: the title's ~13 GB, video memory for its render targets @@ -819,7 +830,7 @@ pub fn coherent_hint_for(windows: usize) -> usize { free_commit() >> 20, NEEDS_FOR_COHERENT_HEAPS >> 20 ); - return RUNTIME_COMMITTED_CAP; + return RUNTIME_COMMITTED_CAP.min(cap); } (title + RUNTIME_COMMITTED_CAP).min(cap) } diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index f743fddd43..45589341b3 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -19,8 +19,8 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Mutex; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::{CloseHandle, HANDLE}; @@ -352,11 +352,82 @@ fn push_run(out: &mut Vec<(usize, usize)>, addr: usize, len: usize) { } } -/// Scan a 4 KiB page at `pg`, appending any changed 64-byte chunk runs directly to `out` -/// (zero per-page heap allocation; skips allocating `slot` completely when a fresh zero page -/// is still all zeros). #[inline] -fn scan_page(page: &[u8], pg: usize, slot: &mut Option>, out: &mut Vec<(usize, usize)>) { +fn has_avx2() -> bool { + #[cfg(target_arch = "x86_64")] + { + static AVX2: OnceLock = OnceLock::new(); + *AVX2.get_or_init(|| std::arch::is_x86_feature_detected!("avx2")) + } + #[cfg(not(target_arch = "x86_64"))] + { + false + } +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +#[inline] +unsafe fn is_chunk_zero_avx2(c: &[u8]) -> bool { + use std::arch::x86_64::{_mm256_loadu_si256, _mm256_or_si256, _mm256_testz_si256, __m256i}; + debug_assert_eq!(c.len(), CHUNK); + let p = c.as_ptr() as *const __m256i; + let v0 = _mm256_loadu_si256(p); + let v1 = _mm256_loadu_si256(p.add(1)); + let any = _mm256_or_si256(v0, v1); + _mm256_testz_si256(any, any) != 0 +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn scan_page_avx2(page: &[u8], pg: usize, slot: &mut Option>, out: &mut Vec<(usize, usize)>) { + use std::arch::x86_64::{_mm256_loadu_si256, _mm256_or_si256, _mm256_testz_si256, __m256i}; + if let Some(sent) = slot.as_deref_mut() { + for (k, c) in page.chunks_exact(CHUNK).enumerate() { + if sent[k] == ZERO_HASH && is_chunk_zero_avx2(c) { + continue; + } + let h = chunk_hash(c); + if h == sent[k] { + continue; + } + sent[k] = h; + push_run(out, pg + k * CHUNK, CHUNK); + } + return; + } + // Fresh all-zero page fast path: scan 128 bytes (2 chunks) per iteration with AVX2. + let ptr = page.as_ptr() as *const __m256i; + let pairs = page.len() / (CHUNK * 2); + let mut first_nz_chunk = None; + for pair in 0..pairs { + let base = ptr.add(pair * 4); + let a = _mm256_or_si256(_mm256_loadu_si256(base), _mm256_loadu_si256(base.add(1))); + let b = _mm256_or_si256(_mm256_loadu_si256(base.add(2)), _mm256_loadu_si256(base.add(3))); + let any = _mm256_or_si256(a, b); + if _mm256_testz_si256(any, any) == 0 { + let k0 = pair * 2; + first_nz_chunk = Some(if _mm256_testz_si256(a, a) == 0 { k0 } else { k0 + 1 }); + break; + } + } + let Some(start_k) = first_nz_chunk else { return }; + for (k, c) in page.chunks_exact(CHUNK).enumerate().skip(start_k) { + if is_chunk_zero_avx2(c) { + continue; + } + let h = chunk_hash(c); + if h == ZERO_HASH { + continue; + } + let sent = slot.get_or_insert_with(|| Box::new(ZERO_HASHES)); + sent[k] = h; + push_run(out, pg + k * CHUNK, CHUNK); + } +} + +#[inline] +fn scan_page_scalar(page: &[u8], pg: usize, slot: &mut Option>, out: &mut Vec<(usize, usize)>) { if let Some(sent) = slot.as_deref_mut() { for (k, c) in page.chunks_exact(CHUNK).enumerate() { let h = chunk_hash(c); @@ -395,6 +466,254 @@ fn scan_page(page: &[u8], pg: usize, slot: &mut Option>, out: } } +/// Scan a 4 KiB page at `pg`, appending any changed 64-byte chunk runs directly to `out` +/// (zero per-page heap allocation; skips allocating `slot` completely when a fresh zero page +/// is still all zeros; uses AVX2 zero-skipping when available). +#[inline] +fn scan_page(page: &[u8], pg: usize, slot: &mut Option>, out: &mut Vec<(usize, usize)>) { + #[cfg(target_arch = "x86_64")] + if has_avx2() && page.len() == PAGE { + unsafe { + scan_page_avx2(page, pg, slot, out); + } + return; + } + scan_page_scalar(page, pg, slot, out); +} + +/// Minimum dirty pages in one `before_execute` before fanning out `scan_page` across `ScanPool`. +const PARALLEL_SCAN_PAGES: usize = 64; +const MAX_SCAN_THREADS: usize = 6; + +fn scan_threads() -> usize { + static N: OnceLock = OnceLock::new(); + *N.get_or_init(|| { + if let Some(n) = std::env::var("XCL_SPARSE_SCAN_THREADS").ok().and_then(|v| v.trim().parse::().ok()) { + return n.clamp(1, 16); + } + std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, MAX_SCAN_THREADS) + }) +} + +struct ScanPoolState { + gen: u64, + active_helpers: usize, + pending_helpers: usize, + func: Option, + ctx: usize, +} + +/// Persistent worker pool for parallel dirty-page chunk scanning in `before_execute` (avoids +/// per-submit thread creation overhead while keeping tile hash state lock-free per page). +struct ScanPool { + run_lock: Mutex<()>, + state: Arc<(Mutex, Condvar, Condvar)>, + helpers: usize, +} + +impl ScanPool { + fn new(max_threads: usize) -> Self { + let helpers = max_threads.saturating_sub(1); + let state = Arc::new(( + Mutex::new(ScanPoolState { gen: 0, active_helpers: 0, pending_helpers: 0, func: None, ctx: 0 }), + Condvar::new(), + Condvar::new(), + )); + let mut spawned = 0usize; + for _ in 0..helpers { + let id = spawned; + let shared = Arc::clone(&state); + if std::thread::Builder::new() + .name(format!("xcl-sparse-scan-{id}")) + .spawn(move || { + let mut seen = 0u64; + loop { + let job = { + let mut g = shared.0.lock().unwrap(); + while g.gen == seen { + g = shared.1.wait(g).unwrap(); + } + seen = g.gen; + if id < g.active_helpers { g.func.map(|f| (f, g.ctx)) } else { None } + }; + if let Some((func, ctx)) = job { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { func(ctx as *const c_void) })); + let mut g = shared.0.lock().unwrap(); + g.pending_helpers -= 1; + if g.pending_helpers == 0 { + shared.2.notify_one(); + } + } + } + }) + .is_ok() + { + spawned += 1; + } + } + ScanPool { run_lock: Mutex::new(()), state, helpers: spawned } + } + + fn run(&self, total_threads: usize, f: &F) { + let helpers = total_threads.saturating_sub(1).min(self.helpers); + if helpers == 0 { + f(); + return; + } + unsafe fn trampoline(ctx: *const c_void) { + (*(ctx as *const F))(); + } + let _serial = self.run_lock.lock().unwrap(); + { + let mut g = self.state.0.lock().unwrap(); + g.func = Some(trampoline::); + g.ctx = (f as *const F) as usize; + g.active_helpers = helpers; + g.pending_helpers = helpers; + g.gen = g.gen.wrapping_add(1); + self.state.1.notify_all(); + } + let caller_res = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); + { + let mut g = self.state.0.lock().unwrap(); + while g.pending_helpers > 0 { + g = self.state.2.wait(g).unwrap(); + } + g.func = None; + g.ctx = 0; + g.active_helpers = 0; + } + if let Err(payload) = caller_res { + std::panic::resume_unwind(payload); + } + } +} + +fn scan_pool() -> &'static ScanPool { + static POOL: OnceLock = OnceLock::new(); + POOL.get_or_init(|| ScanPool::new(scan_threads())) +} + +/// Disjoint page work item for parallel `scan_page` execution. +#[derive(Clone, Copy)] +struct ScanItem { + pg: usize, + slot: *mut Option>, +} + +// SAFETY: `scan_dirty_pages_into` deduplicates sorted `pg` values before constructing `ScanItem`s, +// so every item owns a unique `(tile, idx)` hash slot and reads immutable title memory at `pg`. +unsafe impl Sync for ScanItem {} +unsafe impl Send for ScanItem {} + +/// Scan all write-watched `dirty` pages (sorted ascending, `page` bytes each) overlapping `mapped`, +/// appending coalesced changed 64-byte runs into `out` in ascending address order. Uses the +/// persistent `ScanPool` when at least `PARALLEL_SCAN_PAGES` mapped pages are dirty. +unsafe fn scan_dirty_pages_into( + mapped: &mut FxHashMap, + dirty: &[usize], + page: usize, + max_threads: usize, + out: &mut Vec<(usize, usize)>, +) { + if dirty.is_empty() { + return; + } + // Small dirty sets scan directly with zero intermediate allocation. + if dirty.len() < PARALLEL_SCAN_PAGES || max_threads <= 1 { + let mut i = 0; + while i < dirty.len() { + let a = dirty[i]; + let mut n = page; + i += 1; + while i < dirty.len() && dirty[i] == a + n { + n += page; + i += 1; + } + let mut x = a; + while x < a + n { + let t = x & !(TILE - 1); + let end = (t + TILE).min(a + n); + if let Some(entry) = mapped.get_mut(&t) { + let mut pg = x & !(PAGE - 1); + while pg < end { + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); + scan_page(bytes, pg, &mut entry.sent[idx], out); + } + pg += PAGE; + } + } + x = end; + } + } + return; + } + + // Collect deduplicated, ascending `(pg, &mut entry.sent[idx])` pairs once under `&mut mapped`. + let mut items: Vec = Vec::with_capacity(dirty.len()); + let mut last_pg = usize::MAX; + let mut i = 0; + while i < dirty.len() { + let a = dirty[i]; + let mut n = page; + i += 1; + while i < dirty.len() && dirty[i] == a + n { + n += page; + i += 1; + } + let mut x = a; + while x < a + n { + let t = x & !(TILE - 1); + let end = (t + TILE).min(a + n); + if let Some(entry) = mapped.get_mut(&t) { + let mut pg = x & !(PAGE - 1); + while pg < end { + if pg != last_pg { + last_pg = pg; + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + items.push(ScanItem { pg, slot: &mut entry.sent[idx] as *mut _ }); + } + } + pg += PAGE; + } + } + x = end; + } + } + + if items.len() < PARALLEL_SCAN_PAGES { + for item in items { + let bytes = std::slice::from_raw_parts(item.pg as *const u8, PAGE); + scan_page(bytes, item.pg, &mut *item.slot, out); + } + return; + } + + let threads = max_threads.min(items.len() / 16).max(1); + let chunk_len = items.len().div_ceil(threads); + let chunks: Vec<&[ScanItem]> = items.chunks(chunk_len).collect(); + let buckets: Vec>> = (0..chunks.len()).map(|_| Mutex::new(Vec::new())).collect(); + let next = AtomicUsize::new(0); + scan_pool().run(chunks.len(), &|| loop { + let b = next.fetch_add(1, Ordering::Relaxed); + let Some(&slice) = chunks.get(b) else { break }; + let mut local = Vec::new(); + for &item in slice { + let bytes = std::slice::from_raw_parts(item.pg as *const u8, PAGE); + scan_page(bytes, item.pg, &mut *item.slot, &mut local); + } + *buckets[b].lock().unwrap() = local; + }); + for b in buckets { + for (addr, len) in b.into_inner().unwrap() { + push_run(out, addr, len); + } + } +} + /// The byte ranges (offset, length) of `page` whose 64-byte chunks differ from `sent` /// (updated to the page's chunks). pub fn changed_chunks(page: &[u8], sent: &mut [u64; CHUNKS]) -> Vec<(usize, usize)> { @@ -2239,34 +2558,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } let mut dirty_runs = std::mem::take(&mut s.scratch_runs); dirty_runs.clear(); - let mut i = 0; - while i < dirty.len() { - let a = dirty[i]; - let mut n = page; - i += 1; - while i < dirty.len() && dirty[i] == a + n { - n += page; - i += 1; - } - // only what has video memory (committed tiles of a sparse window) - let mut x = a; - while x < a + n { - let t = x & !(TILE - 1); - let end = (t + TILE).min(a + n); - if let Some(entry) = s.mapped.get_mut(&t) { - let mut pg = x & !(PAGE - 1); - while pg < end { - let idx = (pg - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - scan_page(bytes, pg, &mut entry.sent[idx], &mut dirty_runs); - } - pg += PAGE; - } - } - x = end; - } - } + scan_dirty_pages_into(&mut s.mapped, dirty, page, scan_threads(), &mut dirty_runs); let t_scanned = std::time::Instant::now(); PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); @@ -2632,6 +2924,108 @@ mod tests { assert_eq!(out, vec![(0x1_0FC0, 128)]); } + #[test] + fn scan_page_avx2_matches_scalar_bit_for_bit() { + let mut page = vec![0u8; PAGE]; + let mut slot_a: Option> = None; + let mut slot_b: Option> = None; + let (mut out_a, mut out_b) = (Vec::new(), Vec::new()); + + // Step 1: all-zero fresh page (neither allocates) + scan_page(&page, 0x2_0000, &mut slot_a, &mut out_a); + scan_page_scalar(&page, 0x2_0000, &mut slot_b, &mut out_b); + assert_eq!(out_a, out_b); + assert!(slot_a.is_none() && slot_b.is_none()); + + // Step 2: sparse non-zero writes across odd/even 64B chunks (including last byte) + for &off in &[0usize, 63, 64, 191, 512, 2048, PAGE - 1] { + page[off] = (off as u8).wrapping_mul(37).wrapping_add(1); + } + scan_page(&page, 0x2_0000, &mut slot_a, &mut out_a); + scan_page_scalar(&page, 0x2_0000, &mut slot_b, &mut out_b); + assert_eq!(out_a, out_b); + assert_eq!(slot_a.as_deref(), slot_b.as_deref()); + + // Step 3: re-scan unchanged page (no runs) + out_a.clear(); + out_b.clear(); + scan_page(&page, 0x2_0000, &mut slot_a, &mut out_a); + scan_page_scalar(&page, 0x2_0000, &mut slot_b, &mut out_b); + assert_eq!(out_a, out_b); + assert!(out_a.is_empty()); + + // Step 4: zero out some previously non-zero chunks and mutate another + page[64] = 0; + page[512] = 0; + page[1024] = 0x5A; + scan_page(&page, 0x2_0000, &mut slot_a, &mut out_a); + scan_page_scalar(&page, 0x2_0000, &mut slot_b, &mut out_b); + assert_eq!(out_a, out_b); + assert_eq!(slot_a.as_deref(), slot_b.as_deref()); + } + + #[test] + fn parallel_scan_dirty_pages_matches_serial_bit_for_bit() { + // Allocate a 64 KiB-aligned backing buffer of 16 tiles (256 pages = 1 MiB) via VirtualAlloc + // so `t = x & !(TILE - 1)` aligns cleanly with `MappedTile` boundaries. + const NUM_TILES: usize = 16; + const TOTAL_BYTES: usize = NUM_TILES * TILE; + unsafe { + let base = VirtualAlloc(std::ptr::null(), TOTAL_BYTES, MEM_COMMIT | 0x2000, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + assert_eq!(base % TILE, 0); + let mem = std::slice::from_raw_parts_mut(base as *mut u8, TOTAL_BYTES); + // Seed deterministic pattern across every other page + boundary-spanning chunks. + for p in 0..(NUM_TILES * PAGES_PER_TILE) { + if p % 3 == 0 { + mem[p * PAGE] = (p as u8).wrapping_add(1); + mem[p * PAGE + PAGE - 1] = (p as u8).wrapping_mul(13).wrapping_add(7); + } else if p % 3 == 1 { + // Adjacent start chunk to force boundary coalescing across worker slices + mem[p * PAGE] = 0xEE; + } + } + let make_map = || -> FxHashMap { + let mut m = FxHashMap::default(); + for ti in 0..NUM_TILES { + // Mark page 5 as a hole on odd tiles + let holes = if ti % 2 == 1 { 1u16 << 5 } else { 0 }; + m.insert(base + ti * TILE, TileEntry::with_holes((0, ti as u32), holes)); + } + m + }; + let mut dirty: Vec = (0..(NUM_TILES * PAGES_PER_TILE)).map(|p| base + p * PAGE).collect(); + // Inject a duplicate entry to verify deduplication safety. + dirty.insert(40, dirty[40]); + + let mut serial_map = make_map(); + let mut parallel_map = make_map(); + let (mut out_serial, mut out_parallel) = (Vec::new(), Vec::new()); + + scan_dirty_pages_into(&mut serial_map, &dirty, PAGE, 1, &mut out_serial); + scan_dirty_pages_into(&mut parallel_map, &dirty, PAGE, 6, &mut out_parallel); + assert_eq!(out_parallel, out_serial, "parallel scan must match serial scan bit-for-bit"); + assert!(!out_parallel.is_empty()); + + // Second pass with no changes must emit zero runs on both. + out_serial.clear(); + out_parallel.clear(); + scan_dirty_pages_into(&mut serial_map, &dirty, PAGE, 1, &mut out_serial); + scan_dirty_pages_into(&mut parallel_map, &dirty, PAGE, 6, &mut out_parallel); + assert!(out_serial.is_empty() && out_parallel.is_empty()); + + // Mutate one byte on every 4th page and re-verify parity. + for p in (0..(NUM_TILES * PAGES_PER_TILE)).step_by(4) { + mem[p * PAGE + 128] ^= 0xFF; + } + scan_dirty_pages_into(&mut serial_map, &dirty, PAGE, 1, &mut out_serial); + scan_dirty_pages_into(&mut parallel_map, &dirty, PAGE, 6, &mut out_parallel); + assert_eq!(out_parallel, out_serial, "second mutation pass must match serial bit-for-bit"); + + VirtualFree(base as *mut c_void, 0, 0x8000); + } + } + /// Ring-buffer planner keeps every chunk contiguous, 64-byte aligned, <= cap/2, and splits /// cleanly across the end of the ring buffer without wrapping mid-copy. #[test] diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index f842d021f2..aa3226656d 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1156,9 +1156,48 @@ unsafe fn changed_pages_since_last_upload(res: usize, src: usize, size: usize, d changed_pages_with(res, src, size, dirty_pages, page_size, |at, len| title_bytes(at, len)) } -/// A 64-bit hash of `b` for "the same bytes as before" (four lanes of multiply-rotate over -/// 8-byte words: gigabytes a second; not for anything adversarial). -fn content_hash(b: &[u8]) -> u64 { +#[inline] +fn has_avx2() -> bool { + #[cfg(target_arch = "x86_64")] + { + static AVX2: std::sync::OnceLock = std::sync::OnceLock::new(); + *AVX2.get_or_init(|| std::arch::is_x86_feature_detected!("avx2")) + } + #[cfg(not(target_arch = "x86_64"))] + { + false + } +} + +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "avx2")] +unsafe fn is_zero_avx2(b: &[u8]) -> bool { + use std::arch::x86_64::{_mm256_loadu_si256, _mm256_or_si256, _mm256_testz_si256, __m256i}; + let mut ptr = b.as_ptr(); + let mut rem = b.len(); + while rem >= 128 { + let p = ptr as *const __m256i; + let a = _mm256_or_si256(_mm256_loadu_si256(p), _mm256_loadu_si256(p.add(1))); + let c = _mm256_or_si256(_mm256_loadu_si256(p.add(2)), _mm256_loadu_si256(p.add(3))); + let any = _mm256_or_si256(a, c); + if _mm256_testz_si256(any, any) == 0 { + return false; + } + ptr = ptr.add(128); + rem -= 128; + } + while rem >= 32 { + let v = _mm256_loadu_si256(ptr as *const __m256i); + if _mm256_testz_si256(v, v) == 0 { + return false; + } + ptr = ptr.add(32); + rem -= 32; + } + std::slice::from_raw_parts(ptr, rem).iter().all(|&x| x == 0) +} + +fn content_hash_scalar(b: &[u8]) -> u64 { const K: u64 = 0x9E37_79B9_7F4A_7C15; let mut h = [K, K.rotate_left(17), K.rotate_left(31), K.rotate_left(47)]; let mut chunks = b.chunks_exact(32); @@ -1175,6 +1214,21 @@ fn content_hash(b: &[u8]) -> u64 { h.iter().fold(tail, |a, &l| (a ^ l).wrapping_mul(K).rotate_left(27)) } +fn zero_page_hash_4k() -> u64 { + static H: std::sync::OnceLock = std::sync::OnceLock::new(); + *H.get_or_init(|| content_hash_scalar(&[0u8; 4096])) +} + +/// A 64-bit hash of `b` for "the same bytes as before" (four lanes of multiply-rotate over +/// 8-byte words: gigabytes a second; AVX2 fast-zero shortcut on 4 KiB pages). +fn content_hash(b: &[u8]) -> u64 { + #[cfg(target_arch = "x86_64")] + if b.len() == 4096 && has_avx2() && unsafe { is_zero_avx2(b) } { + return zero_page_hash_4k(); + } + content_hash_scalar(b) +} + /// Frame milestones (relative to last upload or detected content change) at which unwatched /// textures (e.g. physical-page / `MEM_MAPPED` views that `GetWriteWatch` cannot track) are /// re-fingerprinted to catch late streaming writes that land after an initial zeroed upload. @@ -2070,6 +2124,18 @@ unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec { mod tests { use super::*; + #[test] + fn content_hash_avx2_zero_fast_path_matches_scalar() { + let mut page = vec![0u8; 4096]; + assert_eq!(content_hash(&page), content_hash_scalar(&page)); + for &off in &[0usize, 31, 32, 127, 128, 2047, 4095] { + page[off] = 1; + assert_eq!(content_hash(&page), content_hash_scalar(&page), "mismatch at offset {off}"); + page[off] = 0; + } + assert_eq!(content_hash(&page), content_hash_scalar(&page)); + } + /// A texture is left out only when its memory hashes as at its own last upload, and a /// texture that was forgotten (released, or its address registered again) is uploaded again. #[test] From 06405c415f1f4e032a13c2db7fd1e13803cd629f Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:43:05 -0500 Subject: [PATCH 219/258] xcl run: prepare supported shader records before starting the title Count completed records in the offline shader path and display progress while the launcher waits for the worker. Warm both pieces and the whole compute fallback for split records. A cancelled or unsuccessful pass leaves the host unstarted. --- README.md | 9 ++ crates/xcl/Cargo.toml | 1 + crates/xcl/src/launcher.rs | 16 ++ crates/xcl/src/launcher/shader_window.rs | 196 +++++++++++++++++++++++ crates/xcl/src/main.rs | 2 +- crates/xcl/src/shaders.rs | 166 +++++++++++++++---- crates/xcl/tests/launcher_e2e.rs | 15 ++ 7 files changed, 372 insertions(+), 33 deletions(-) create mode 100644 crates/xcl/src/launcher/shader_window.rs diff --git a/README.md b/README.md index 6b81edf11d..00501c7821 100644 --- a/README.md +++ b/README.md @@ -233,6 +233,15 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder
Switches, caches, logs and the files XCL writes +- When a game folder contains a `shaders.rpf` shader pack or loose `.dxbc` files under + `shaders/`, XCL opens a preparation window before starting the title. The percentage counts + processed records. The timer counts seconds since one finished (or preparation started); + five seconds without progress counts as a stall, and the window shows when the last one ended. + XCL prepares supported shader stages and compute pipelines, including + split pieces and their whole fallback. Graphics pipelines that need state supplied by the + title are created during play. Later launches reuse matching cache entries. + Closing the window cancels the launch. A compiler or driver failure stops it and reports + the cause. Null-renderer runs skip shader preparation. - **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved blob is left to the runtime instead of being compiled in the pass — those compiles take tens of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index c3b23a1b8b..08bd049d19 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -44,6 +44,7 @@ features = [ version = "0.61" features = [ "Win32_Foundation", + "Win32_Graphics_Gdi", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Diagnostics_Debug", diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index 00a9cb1f87..02ed8e0852 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -6,6 +6,8 @@ use std::path::{Path, PathBuf}; use crate::config::{Boot, Config}; use crate::util::wide; +mod shader_window; + /// Data root: `%XCL_DATA_ROOT%` or `%LOCALAPPDATA%\XCL`. pub fn data_root() -> PathBuf { if let Ok(p) = std::env::var("XCL_DATA_ROOT") { @@ -286,6 +288,14 @@ fn quote(a: &str) -> String { } pub fn run(target: &Path, args: &[String]) -> i32 { + run_with_ui(target, args, false) +} + +pub fn run_from_menu(target: &Path) -> i32 { + run_with_ui(target, &[], true) +} + +fn run_with_ui(target: &Path, args: &[String], menu: bool) -> i32 { let (root, explicit_exe, title) = match resolve_location(target) { Ok(x) => x, Err(e) => { @@ -383,6 +393,12 @@ pub fn run(target: &Path, args: &[String]) -> i32 { } } + if !boot.config.graphics.eq_ignore_ascii_case("null") { + if let Err(e) = shader_window::prepare(&root, &boot.config.d3d12_adapter, menu) { + eprintln!("xcl: {e}"); + return 2; + } + } let mut cmdline = quote(&exe.to_string_lossy()); for a in args { cmdline.push(' '); diff --git a/crates/xcl/src/launcher/shader_window.rs b/crates/xcl/src/launcher/shader_window.rs new file mode 100644 index 0000000000..68e3e4b1be --- /dev/null +++ b/crates/xcl/src/launcher/shader_window.rs @@ -0,0 +1,196 @@ +use std::path::Path; +use std::ptr::{null, null_mut}; +use std::sync::atomic::Ordering; +use std::time::{Duration, Instant}; + +use windows_sys::Win32::Foundation::{ERROR_CLASS_ALREADY_EXISTS, GetLastError, HWND}; +use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW; +use windows_sys::Win32::UI::Controls::*; +use windows_sys::Win32::UI::WindowsAndMessaging::*; + +use crate::shaders::{LaunchPreparation, prepare_for_launch}; +use crate::util::wide; + +struct Window { hwnd: HWND, label: HWND, timer: HWND, bar: HWND } + +impl Drop for Window { + fn drop(&mut self) { unsafe { if IsWindow(self.hwnd) != 0 { DestroyWindow(self.hwnd); } } } +} + +impl Window { + fn open() -> Result { + unsafe { + let instance = GetModuleHandleW(null()); + let class = wide("XCLShaderPreparation"); + let wc = WNDCLASSW { + hInstance: instance, lpfnWndProc: Some(DefWindowProcW), + hCursor: LoadCursorW(null_mut(), IDC_ARROW), + hbrBackground: (windows_sys::Win32::Graphics::Gdi::COLOR_WINDOW + 1) as _, + lpszClassName: class.as_ptr(), ..std::mem::zeroed() + }; + if RegisterClassW(&wc) == 0 && GetLastError() != ERROR_CLASS_ALREADY_EXISTS { + return Err(std::io::Error::last_os_error().to_string()); + } + let init = INITCOMMONCONTROLSEX { dwSize: std::mem::size_of::() as u32, dwICC: ICC_PROGRESS_CLASS }; + if InitCommonControlsEx(&init) == 0 { return Err("Could not initialize the progress bar".into()); } + let hwnd = CreateWindowExW(0, class.as_ptr(), wide("XCL – Preparing shaders").as_ptr(), + WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 510, 155, + null_mut(), null_mut(), instance, null()); + if hwnd.is_null() { return Err(std::io::Error::last_os_error().to_string()); } + let label = CreateWindowExW(0, wide("STATIC").as_ptr(), wide("Reading shader records…").as_ptr(), + WS_CHILD | WS_VISIBLE, 16, 16, 420, 25, hwnd, null_mut(), instance, null()); + let timer = CreateWindowExW(0, wide("STATIC").as_ptr(), null(), + WS_CHILD | WS_VISIBLE, 16, 47, 465, 23, hwnd, null_mut(), instance, null()); + let bar = CreateWindowExW(0, PROGRESS_CLASSW, null(), WS_CHILD | WS_VISIBLE, + 16, 79, 465, 18, hwnd, null_mut(), instance, null()); + let window = Self { hwnd, label, timer, bar }; + if label.is_null() || timer.is_null() || bar.is_null() { return Err(std::io::Error::last_os_error().to_string()); } + ShowWindow(hwnd, SW_SHOWNORMAL); + Ok(window) + } + } + + fn pump(&self) -> bool { + unsafe { + let mut msg = std::mem::zeroed(); + while PeekMessageW(&mut msg, null_mut(), 0, 0, PM_REMOVE) != 0 { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + IsWindow(self.hwnd) != 0 + } + } + + fn update(&self, done: usize, total: usize, ready: bool) { + let percent = percent(done, total, ready); + unsafe { + SetWindowTextW(self.label, wide(&format!("Preparing shaders: {percent}% ({done}/{total} records)")).as_ptr()); + SendMessageW(self.bar, PBM_SETPOS, percent, 0); + } + } +} + +#[derive(Default)] +struct StallClock { + done: usize, + advanced_at: Duration, + last_stall_ended: Option, +} + +impl StallClock { + fn sample(&mut self, done: usize, now: Duration) -> (u64, Option) { + if done != self.done { + if now - self.advanced_at >= Duration::from_secs(5) { + self.last_stall_ended = Some(now); + } + self.done = done; + self.advanced_at = now; + } + ((now - self.advanced_at).as_secs(), self.last_stall_ended.map(|end| (now - end).as_secs())) + } +} + +fn percent(done: usize, total: usize, ready: bool) -> usize { + if ready { 100 } else { done.saturating_mul(100).checked_div(total).unwrap_or(0).min(99) } +} + +pub(super) fn prepare(root: &Path, adapter: &str, menu: bool) -> Result<(), String> { + let pack = root.join("shaders.rpf"); + let loose = root.join("shaders"); + if !pack.try_exists().map_err(|e| e.to_string())? && !loose.is_dir() { return Ok(()); } + let window = Window::open()?; + let progress = LaunchPreparation { adapter, done: 0.into(), total: 0.into(), cancel: false.into() }; + let start = Instant::now(); + let mut clock = StallClock::default(); + let mut last_times = None; + let mut last = None; + let result = wait_for_worker(&progress, || prepare_for_launch(root, &progress), || { + if !window.pump() { return false; } + let total = progress.total.load(Ordering::Relaxed); + let done = progress.done.load(Ordering::Relaxed); + let times = clock.sample(done, start.elapsed()); + if last_times != Some(times) { + let mut text = format!("No shader progress for {} s", times.0); + if let Some(ago) = times.1 { text.push_str(&format!(" | Last stall ended {ago} s ago")); } + unsafe { SetWindowTextW(window.timer, wide(&text).as_ptr()); } + last_times = Some(times); + } + if total > 0 && last != Some(done) { + window.update(done, total, false); + last = Some(done); + } + true + }); + match &result { + Ok(()) => { + let total = progress.total.load(Ordering::Relaxed); + window.update(total, total, true); + unsafe { + windows_sys::Win32::Graphics::Gdi::UpdateWindow(window.label); + windows_sys::Win32::Graphics::Gdi::UpdateWindow(window.bar); + } + } + Err(message) if !progress.cancel.load(Ordering::Relaxed) && menu => unsafe { + MessageBoxW(window.hwnd, wide(message).as_ptr(), wide("XCL – Shader preparation failed").as_ptr(), MB_OK | MB_ICONERROR); + }, + _ => {} + } + result +} + +fn wait_for_worker(progress: &LaunchPreparation, work: impl FnOnce() -> Result<(), String> + Send, + mut pump: impl FnMut() -> bool) -> Result<(), String> { + std::thread::scope(|scope| { + let worker = scope.spawn(work); + while !worker.is_finished() { + if !pump() { progress.cancel.store(true, Ordering::Relaxed); } + std::thread::sleep(Duration::from_millis(80)); + } + let result = worker.join().map_err(|_| "Shader preparation worker stopped unexpectedly")?; + if !pump() { progress.cancel.store(true, Ordering::Relaxed); } + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + result + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn launch_waits_for_success_and_propagates_failure_or_close() { + let progress = LaunchPreparation { adapter: "auto", done: 0.into(), total: 0.into(), cancel: false.into() }; + let called = std::sync::atomic::AtomicBool::new(false); + wait_for_worker(&progress, || { + while !called.load(Ordering::Acquire) { std::thread::yield_now(); } + Ok(()) + }, || { called.store(true, Ordering::Release); true }).unwrap(); + assert_eq!(wait_for_worker(&progress, || Err("bad shader".into()), || true).unwrap_err(), "bad shader"); + let cancelled = wait_for_worker(&progress, || { + while !progress.cancel.load(Ordering::Relaxed) { std::thread::yield_now(); } + Ok(()) + }, || false); + assert_eq!(cancelled.unwrap_err(), "Shader preparation cancelled"); + } + + #[test] + fn clock_advances_during_a_stall_and_remembers_recovery() { + let mut clock = StallClock::default(); + let s = Duration::from_secs; + assert_eq!(clock.sample(0, s(1)), (1, None)); + assert_eq!(clock.sample(0, s(5)), (5, None)); + assert_eq!(clock.sample(2, s(6)), (0, Some(0))); + assert_eq!(clock.sample(2, s(8)), (2, Some(2))); + assert_eq!(clock.sample(3, s(9)), (0, Some(3))); + assert_eq!(clock.sample(3, s(15)), (6, Some(9))); + assert_eq!(clock.sample(4, s(16)), (0, Some(0))); + } + + #[test] + fn only_a_successful_join_releases_the_last_percent() { + assert_eq!(percent(0, 0, false), 0); + assert_eq!(percent(1, 4, false), 25); + assert_eq!(percent(4, 4, false), 99); + assert_eq!(percent(4, 4, true), 100); + } +} diff --git a/crates/xcl/src/main.rs b/crates/xcl/src/main.rs index 4c45685711..45ce7573b5 100644 --- a/crates/xcl/src/main.rs +++ b/crates/xcl/src/main.rs @@ -121,7 +121,7 @@ fn run_picked_game() -> i32 { let _ = std::fs::create_dir_all(xcl::launcher::data_root()); let _ = std::fs::write(&last_file, target.to_string_lossy().as_bytes()); println!("xcl run \"{}\"", target.display()); - let code = xcl::launcher::run(&target, &[]); + let code = xcl::launcher::run_from_menu(&target); if code != 0 { println!("\nXCL ended with code {code}. Press Enter to close."); let _ = std::io::stdin().read_line(&mut String::new()); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 7fcdc87ed4..7b4338c231 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -986,7 +986,10 @@ pub fn run(path: &Path, args: &[String]) -> i32 { let used = opts.used_only.then(crate::hle::d3d12x::pso_async::earlier_used_keys); // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) let windows = runtime_windows(); - return precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0); + return match precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0, None) { + Ok(()) => 0, + Err(e) => { eprintln!("xcl shaders: {e}"); 2 } + }; } if opts.direct { return direct_sweep(&input, &opts, t0); @@ -1450,11 +1453,14 @@ mod pipeline_cap_tests { unsafe impl Sync for Pipelines {} impl Pipelines { - fn new() -> Result { + fn new() -> Result { Self::for_adapter("auto") } + + fn for_adapter(adapter: &str) -> Result { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0; use windows::Win32::Graphics::Dxgi::*; unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; +<<<<<<< HEAD let sel = crate::gpu::adapter::Selector::from_env_or("auto"); let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; crate::hle::d3d12x::real::driver_cache::note_vendor(desc.VendorId); @@ -1465,6 +1471,16 @@ impl Pipelines { let library = (!cfg!(test)) .then(|| crate::hle::d3d12x::pso_library::MmapPipelineLibrary::open_or_create(&dev, &adapter_name)) .flatten(); +======= + let sel = crate::gpu::adapter::Selector::from_env_or(adapter); + let dev = if sel == crate::gpu::adapter::Selector::Warp { + let warp: IDXGIAdapter = factory.EnumWarpAdapter().map_err(|e| e.to_string())?; + crate::gpu::agility::create_device(&warp, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())? + } else { + let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())? + }; +>>>>>>> 7d9e8111 (xcl run: prepare supported shader records before starting the title) let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); Ok(Pipelines { @@ -1698,15 +1714,65 @@ fn used_compute(blob: &[u8], used: &std::collections::HashSet) -> bool { used.contains(&crate::hle::d3d12x::real::shaders_key(&[blob.to_vec()])) } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant) -> i32 { +pub(crate) struct LaunchPreparation<'a> { + pub adapter: &'a str, + pub done: AtomicUsize, + pub total: AtomicUsize, + pub cancel: std::sync::atomic::AtomicBool, +} + +/// Unpacked shader containers in the title's shaders directory. Do not follow directory +/// junctions into another tree or back into the shader directory. +fn loose_inputs(dir: &Path, files: &mut Vec) -> std::io::Result<()> { + use std::os::windows::fs::MetadataExt; + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let metadata = entry.metadata()?; + if metadata.file_attributes() & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT != 0 { continue; } + let path = entry.path(); + if metadata.is_dir() { + loose_inputs(&path, files)?; + } else if path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("dxbc")) { + files.push(path); + } + } + Ok(()) +} + +pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> Result<(), String> { + let mut inputs = Vec::new(); + let pack = root.join("shaders.rpf"); + if pack.try_exists().map_err(|e| e.to_string())? { + let data = std::fs::read(&pack).map_err(|e| format!("Reading {}: {e}", pack.display()))?; + if !data.starts_with(pack::RPF9_MAGIC) { return Err(format!("Unrecognized shader pack: {}", pack.display())); } + let records = pack::scan(&data, 0x40); + if records.is_empty() { return Err(format!("No readable shader records in {}", pack.display())); } + inputs.push(Input::Pack { data, records }); + } + let loose = root.join("shaders"); + if loose.is_dir() { + let mut files = Vec::new(); + loose_inputs(&loose, &mut files).map_err(|e| format!("Reading {}: {e}", loose.display()))?; + if !files.is_empty() { inputs.push(Input::Files(files)); } + } + progress.total.store(inputs.iter().map(Input::len).sum(), Ordering::Relaxed); + let mut windows = crate::gpu::uma::configured_runtime_windows() as u32; + if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } + for input in inputs { + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + precompile(&input, usize::MAX, windows, None, None, true, None, std::time::Instant::now(), Some(progress))?; + } + Ok(()) +} + +fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { let pipelines = if pipelines { - match Pipelines::new() { - Ok(p) => Some(p), - Err(e) => { - eprintln!("xcl shaders --pipelines: no GPU device: {e}"); - return 2; - } + let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter)) + .map_err(|e| format!("No pipeline device: {e}"))?; + if startup.is_some() && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { + p.max_dxil = 0; } + Some(p) } else { None }; @@ -1726,8 +1792,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on recomp::dxc::set_memory_reserve(2); // VS / PS: the 32-lane form wherever the GPU can run 32-lane waves (`pso::graphics_wave32`); // `--split` sets both - let graphics_split = split.unwrap_or_else(recomp::runner::graphics_wave32); - let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w)); + let startup_device = pipelines.filter(|_| startup.is_some()); + let graphics_split = split.unwrap_or_else(|| startup_device.map_or_else(recomp::runner::graphics_wave32, |p| recomp::pso::graphics_wave32_for_device(&p.dev))); + let split = split.unwrap_or_else(|| startup_device.map_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w), |p| recomp::pso::wave32_only_for_device(&p.dev))); println!( "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), @@ -1741,15 +1808,29 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on std::thread::scope(|s| { for _ in 0..threads { s.spawn(|| loop { + if startup.is_some_and(|p| p.cancel.load(Ordering::Relaxed)) { break; } let i = next.fetch_add(1, Ordering::Relaxed); if i >= n { break; } + let record_done = || { + let d = done.fetch_add(1, Ordering::Relaxed) + 1; + if let Some(p) = startup { p.done.fetch_add(1, Ordering::Relaxed); } + if d % 200 == 0 { eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); } + }; let (name, blob) = input.get(i); - let Some(blob) = blob else { continue }; - let Some(sh) = xbox::parse(&blob) else { continue }; + let Some(blob) = blob else { + if startup.is_some() { failed.fetch_add(1, Ordering::Relaxed); } + record_done(); + continue; + }; + let Some(sh) = xbox::parse(&blob) else { + if startup.is_some() { failed.fetch_add(1, Ordering::Relaxed); } + record_done(); + continue; + }; if only.is_some_and(|o| !sh.stage.eq_ignore_ascii_case(o)) { - done.fetch_add(1, Ordering::Relaxed); + record_done(); continue; } // a compute program as a title's pipeline translates it (`pso::console_to_dxil_in`): @@ -1757,7 +1838,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on if sh.fssm.iter().any(|f| matches!(recomp::interface(&blob, &sh, f), Some(recomp::Mode::Compute(_)))) { if used.is_some_and(|u| !used_compute(&blob, u)) { unused.fetch_add(1, Ordering::Relaxed); - done.fetch_add(1, Ordering::Relaxed); + record_done(); continue; } if crate::hle::d3d12x::real::rt_gated_compute_held(&blob) { @@ -1770,6 +1851,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on Ok(c) => { if let Some(p) = pipelines { p.make_record(&c, record); + if startup.is_some() && c.dispatch_chain.as_ref().is_some_and(|plan| plan.pieces.len() >= 2) { + p.make_one(&c.dxil, &c.samplers, true, None, record); + } } compiled.fetch_add(1, Ordering::Relaxed) } @@ -1781,10 +1865,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on failed.fetch_add(1, Ordering::Relaxed) } }; - let d = done.fetch_add(1, Ordering::Relaxed) + 1; - if d % 200 == 0 { - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); - } + record_done(); continue; } for f in &sh.fssm { @@ -1805,10 +1886,21 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // `translate_mesh`) let split = if matches!(mode, recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_)) { graphics_split } else { split }; let opt = recomp::Options { mode: mode.clone(), wave64: recomp::fssm_wave64(f, code), split_wave64: split, mem_windows: windows, rodata: f.rodata(p), ..Default::default() }; - let Ok(t) = recomp::translate(code, &opt) else { continue }; - if !t.complete() { - continue; - } + let t = match recomp::translate(code, &opt) { + Ok(t) if t.complete() => t, + Ok(_) => { + if startup.is_some() { skipped.fetch_add(1, Ordering::Relaxed); } + continue; + } + Err(e) => { + if startup.is_some() { + failed.fetch_add(1, Ordering::Relaxed); + let mut logs = errors.lock().unwrap(); + if logs.len() < 10 { logs.push(format!("{name}: {e}")); } + } + continue; + } + }; for (profile, src) in &jobs { match recomp::dxc::compile_cached(src.as_deref().unwrap_or(&t.hlsl), "main", profile) { Ok((_, true)) => cached.fetch_add(1, Ordering::Relaxed), @@ -1824,18 +1916,17 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on } } } - let d = done.fetch_add(1, Ordering::Relaxed) + 1; - if d % 200 == 0 { - eprintln!(" {d}/{n} ({:.0} s)", t0.elapsed().as_secs_f64()); - } + record_done(); }); } }); + let failed = failed.into_inner(); + let skipped_reason = if startup.is_some() { "runtime pairing or unsupported translation" } else { "GS – paired at pipeline creation" }; println!( - "compiled {}, already cached {}, errors {}, skipped (GS – paired at pipeline creation) {}, time {:.1} s", + "compiled {}, already cached {}, errors {}, skipped ({skipped_reason}) {}, time {:.1} s", compiled.into_inner(), cached.into_inner(), - failed.into_inner(), + failed, skipped.into_inner(), t0.elapsed().as_secs_f64() ); @@ -1869,10 +1960,21 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on println!("pipelines over the {} MiB DXIL cap, left to the runtime: {} ({} MiB of DXIL; XCL_PIPELINE_MAX_KB)", p.max_dxil >> 20, capped, p.capped_bytes.load(Ordering::Relaxed) >> 20); } } - for e in errors.into_inner().unwrap() { - println!(" {e}"); + let errors = errors.into_inner().unwrap(); + for e in &errors { println!(" {e}"); } + if let Some(progress) = startup { + if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } + let p = pipelines.expect("startup requested pipelines"); + let refused = p.refused.load(Ordering::Relaxed); + let capped = p.capped.load(Ordering::Relaxed); + if failed + refused + capped > 0 { + let cause = errors.first().map(String::as_str).unwrap_or( + if capped > 0 { "Raise XCL_PIPELINE_MAX_KB or set it to 0 to prepare larger pipelines." } + else { "Check the shader pack and driver diagnostics." }); + return Err(format!("Shader preparation stopped: {failed} record failures, {refused} refused pipelines, {capped} over the size cap. {cause}")); + } } - 0 + Ok(()) } /// Compile the kept HLSL samples with DXC on all cores: (ok, failures with the first error line). diff --git a/crates/xcl/tests/launcher_e2e.rs b/crates/xcl/tests/launcher_e2e.rs index 4100fad051..733d14a866 100644 --- a/crates/xcl/tests/launcher_e2e.rs +++ b/crates/xcl/tests/launcher_e2e.rs @@ -22,6 +22,21 @@ impl Drop for TempDir { } } +#[test] +fn unreadable_shader_pack_stops_launch_before_host_start() { + let game = TempDir::new("xcl-preparation-failed"); + std::fs::write(game.0.join("title.exe"), b"must never be loaded").unwrap(); + std::fs::write(game.0.join("shaders.rpf"), b"9FPR").unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_xcl")) + .args(["run"]).arg(&game.0) + .env("XCL_DATA_ROOT", game.0.join("user")) + .env("XCL_SKIP_CPU_CHECK", "1") + .output().unwrap(); + assert_eq!(output.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&output.stderr).contains("No readable shader records")); + assert!(!String::from_utf8_lossy(&output.stdout).contains("Log:")); +} + #[test] fn launcher_missing_target_argument_exits_code_two() { let output = Command::new(env!("CARGO_BIN_EXE_xcl")) From 20a99185d3136af46cc7a5c8375f89010c6fcd17 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:56:26 -0500 Subject: [PATCH 220/258] D3D12.X: show shader preparation in the presentation window Keep the guest behind the preparation gate in the host. The presenter owns its window throughout warm-up and swap-chain creation. Let its message thread draw progress and handle cancellation until the guest is ready. Leave the runtime clock and input timing anchored to title startup. --- README.md | 5 +- crates/xcl/src/hle/d3d12x/present.rs | 8 +- .../xcl/src/hle/d3d12x/present/preparation.rs | 230 ++++++++++++++++++ crates/xcl/src/host.rs | 5 + crates/xcl/src/launcher.rs | 24 +- crates/xcl/src/launcher/shader_window.rs | 196 --------------- crates/xcl/src/shaders.rs | 13 +- crates/xcl/tests/e2e.rs | 7 + 8 files changed, 273 insertions(+), 215 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/present/preparation.rs delete mode 100644 crates/xcl/src/launcher/shader_window.rs diff --git a/README.md b/README.md index 00501c7821..efc611d8c0 100644 --- a/README.md +++ b/README.md @@ -234,14 +234,15 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder Switches, caches, logs and the files XCL writes - When a game folder contains a `shaders.rpf` shader pack or loose `.dxbc` files under - `shaders/`, XCL opens a preparation window before starting the title. The percentage counts + `shaders/`, XCL shows shader preparation in the game window before executing title code. + The same window then presents the game. The percentage counts processed records. The timer counts seconds since one finished (or preparation started); five seconds without progress counts as a stall, and the window shows when the last one ended. XCL prepares supported shader stages and compute pipelines, including split pieces and their whole fallback. Graphics pipelines that need state supplied by the title are created during play. Later launches reuse matching cache entries. Closing the window cancels the launch. A compiler or driver failure stops it and reports - the cause. Null-renderer runs skip shader preparation. + the cause. Null-renderer runs skip shader preparation. With presentation disabled, the gate runs without a window. - **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved blob is left to the runtime instead of being compiled in the pass — those compiles take tens of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 38e204fafc..7a44ccb4c6 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -375,7 +375,10 @@ pub fn on_queue_console_method(_info: &StubInfo, _caller: usize) { // window // --------------------------------------------------------------------------------------- +pub(crate) mod preparation; + unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT { + if let Some(result) = preparation::on_message(hwnd, msg, wp) { return result; } // keyboard and mouse as the gamepad: raw mouse input, the cursor held in the window if crate::hle::kbm::on_message(hwnd.0, msg, wp.0, lp.0) { return LRESULT(0); @@ -518,10 +521,10 @@ fn window_thread() { crate::xlog_error!("could not create the XCL window"); return; }; - HWND_RAW.store(hwnd.0 as isize, Ordering::Release); crate::xlog_info!("XCL window created ({}x{})", cfg.window_width, cfg.window_height); - crate::hle::kbm::attach(hwnd.0); + if !preparation::active() { crate::hle::kbm::attach(hwnd.0); } SetTimer(Some(hwnd), COMPILE_TIMER, 500, None); + HWND_RAW.store(hwnd.0 as isize, Ordering::Release); let mut msg = MSG::default(); while GetMessageW(&mut msg, None, 0, 0).as_bool() { let _ = TranslateMessage(&msg); @@ -1036,6 +1039,7 @@ unsafe fn ensure_swapchain(p: &mut Presenter, hwnd: HWND, w: u32, h: u32, fmt: D p.h = h; p.fmt = fmt; crate::xlog_info!("present: swap chain {w}x{h} {:?} – the game image will appear in the XCL window", fmt); + crate::xlog_info!("present: swap chain window {:#x}", hwnd.0 as usize); p.sc.is_some() } Err(e) => { diff --git a/crates/xcl/src/hle/d3d12x/present/preparation.rs b/crates/xcl/src/hle/d3d12x/present/preparation.rs new file mode 100644 index 0000000000..1d4e614b8f --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/present/preparation.rs @@ -0,0 +1,230 @@ +//! Pre-entry shader preparation in the same HWND that later owns the DXGI swap chain. +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; +use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; +use windows::Win32::Foundation::{HWND, LRESULT, WPARAM}; +use windows_sys::Win32::Foundation::{RECT, WAIT_OBJECT_0}; +use windows_sys::Win32::Graphics::Gdi::*; +use windows_sys::Win32::System::Threading::WaitForSingleObject; +use windows_sys::Win32::UI::WindowsAndMessaging::*; +use crate::config::Boot; +use crate::shaders::{LaunchPreparation, prepare_for_launch}; +use crate::util::wide; + +static ACTIVE: AtomicBool = AtomicBool::new(false); +static SCREEN: Mutex> = Mutex::new(None); +const READY: u32 = WM_APP + 0x40; + +struct Screen { + progress: Arc, + start: Instant, + clock: StallClock, + ready: bool, +} + +impl Screen { + fn release(&mut self) -> bool { + self.ready = !self.progress.cancel.load(Ordering::Relaxed); + self.ready + } +} + +pub(super) fn active() -> bool { ACTIVE.load(Ordering::Acquire) } + +pub(crate) fn before_guest(boot: &Boot) -> Result<(), String> { + // This handle was opened by the launcher on itself, then inherited by this host. + let parent = std::env::var("XCL_PREPARATION_PARENT").ok() + .and_then(|s| s.parse::().ok()).filter(|&h| h != 0) + .map(|h| unsafe { OwnedHandle::from_raw_handle(h as _) }); + let menu = std::env::var_os("XCL_PREPARATION_MENU").is_some(); + std::env::remove_var("XCL_PREPARATION_PARENT"); + std::env::remove_var("XCL_PREPARATION_MENU"); + let root = &boot.game_root; + if boot.config.graphics.eq_ignore_ascii_case("null") || + (!root.join("shaders.rpf").try_exists().map_err(|e| e.to_string())? && !root.join("shaders").is_dir()) { + return Ok(()); + } + let progress = Arc::new(LaunchPreparation { adapter: boot.config.d3d12_adapter.clone(), ..Default::default() }); + let hwnd = if super::enabled() { + *SCREEN.lock().unwrap() = Some(Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }); + ACTIVE.store(true, Ordering::Release); + let hwnd = super::ensure_window().ok_or("Could not create the presentation window for shader preparation")?; + crate::xlog_info!("Shader preparation window {:#x}", hwnd.0 as usize); + Some(hwnd) + } else { None }; + let result = std::thread::scope(|scope| { + let worker = scope.spawn(|| prepare_for_launch(root, &progress)); + while !worker.is_finished() { + if let Some(parent) = &parent { + if unsafe { WaitForSingleObject(parent.as_raw_handle(), 80) } == WAIT_OBJECT_0 { + // The launcher was stopped during preparation. Do not leave an orphan compile or start the title. + std::process::exit(2); + } + } else { std::thread::sleep(Duration::from_millis(80)); } + } + worker.join().map_err(|_| "Shader preparation worker stopped unexpectedly")? + }); + let mut result = if progress.cancel.load(Ordering::Relaxed) { Err("Shader preparation cancelled".into()) } else { result }; + if let Some(hwnd) = hwnd { + if result.is_ok() { + // Complete painting on the window's owner thread before the guest can draw. + if unsafe { SendMessageW(hwnd.0, READY, 0, 0) } == 0 { + result = Err("Shader preparation cancelled".into()); + } + } else if let Err(e) = &result { + if menu && !progress.cancel.load(Ordering::Relaxed) { + unsafe { MessageBoxW(hwnd.0, wide(e).as_ptr(), wide("XCL – Shader preparation failed").as_ptr(), MB_OK | MB_ICONERROR); } + } + } + ACTIVE.store(false, Ordering::Release); + *SCREEN.lock().unwrap() = None; + } + result +} + +pub(super) unsafe fn on_message(hwnd: HWND, msg: u32, wp: WPARAM) -> Option { + if !active() { return None; } + match msg { + WM_PAINT => { + let mut guard = SCREEN.lock().unwrap(); + if let Some(s) = guard.as_mut() { paint(hwnd, s); } + } + WM_ERASEBKGND => return Some(LRESULT(1)), + WM_TIMER if wp.0 == super::COMPILE_TIMER => { InvalidateRect(hwnd.0, std::ptr::null(), 0); } + WM_CLOSE => { + if let Some(s) = SCREEN.lock().unwrap().as_ref() { s.progress.cancel.store(true, Ordering::Relaxed); } + InvalidateRect(hwnd.0, std::ptr::null(), 0); + } + READY => { + { + let mut view = SCREEN.lock().unwrap(); + let s = view.as_mut()?; + if !s.release() { return Some(LRESULT(0)); } + } + RedrawWindow(hwnd.0, std::ptr::null(), std::ptr::null_mut(), RDW_INVALIDATE | RDW_UPDATENOW); + crate::hle::kbm::attach(hwnd.0); + ACTIVE.store(false, Ordering::Release); + return Some(LRESULT(1)); + } + _ => return None, + } + Some(LRESULT(0)) +} + +unsafe fn fill(dc: HDC, rect: RECT, color: u32) { + let brush = CreateSolidBrush(color); + FillRect(dc, &rect, brush); + DeleteObject(brush); +} + +unsafe fn text(dc: HDC, rect: RECT, value: &str, size: i32, weight: i32, color: u32, align: u32) { + let font = CreateFontW(-size, 0, 0, 0, weight, 0, 0, 0, DEFAULT_CHARSET as _, 0, 0, CLEARTYPE_QUALITY as _, 0, wide("Segoe UI").as_ptr()); + let old = SelectObject(dc, font); + SetTextColor(dc, color); + let utf = wide(value); + let mut rect = rect; + DrawTextW(dc, utf.as_ptr(), (utf.len()-1) as i32, &mut rect, DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS | align); + SelectObject(dc, old); + DeleteObject(font); +} + +unsafe fn paint(hwnd: HWND, s: &mut Screen) { + let mut ps: PAINTSTRUCT = std::mem::zeroed(); + let dest = BeginPaint(hwnd.0, &mut ps); + let mut rc = RECT::default(); + GetClientRect(hwnd.0, &mut rc); + if rc.right > 0 && rc.bottom > 0 { + let dc = CreateCompatibleDC(dest); + let bitmap = CreateCompatibleBitmap(dest, rc.right, rc.bottom); + let old = SelectObject(dc, bitmap); + SetBkMode(dc, TRANSPARENT as i32); + fill(dc, rc, 0x201815); + let scale = |px: i32| (px * GetDeviceCaps(dc, LOGPIXELSY as i32).max(96)) / 96; + let width = scale(560).min((rc.right - scale(40)).max(1)); + let x = (rc.right - width) / 2; + let y = ((rc.bottom - scale(150)) / 2).max(0); + let row = |top, bottom| RECT { left: x, right: x+width, top: y+scale(top), bottom: y+scale(bottom) }; + let done = s.progress.done.load(Ordering::Relaxed); + let total = s.progress.total.load(Ordering::Relaxed); + let pct = percent(done, total, s.ready); + let (quiet, last) = s.clock.sample(done, s.start.elapsed()); + let heading = if s.progress.cancel.load(Ordering::Relaxed) { "Cancelling preparation" } else { "Preparing shaders" }; + let mut title = row(0,48); + title.right -= scale(84); + text(dc, title, heading, scale(31), 600, 0xf7f5f1, DT_LEFT); + text(dc, row(0,48), &format!("{pct}%"), scale(27), 600, 0xdfd09a, DT_RIGHT); + let bar = row(65,72); + fill(dc, bar, 0x4b4038); + fill(dc, RECT {right: x+(width as i64 * pct as i64/100) as i32, ..bar}, 0xbdb458); + let count = if total == 0 { "Reading shader records…".into() } else { format!("{done} of {total} records processed") }; + text(dc, row(87,112), &count, scale(17), 400, 0xe1dcd7, DT_LEFT); + let mut times = format!("No shader progress for {quiet} s"); + if let Some(ago) = last { times.push_str(&format!(" · Last stall ended {ago} s ago")); } + text(dc, row(117,145), ×, scale(14), 400, 0xb4aaa4, DT_LEFT); + BitBlt(dest, 0, 0, rc.right, rc.bottom, dc, 0, 0, SRCCOPY); + SelectObject(dc, old); + DeleteObject(bitmap); + DeleteDC(dc); + } + EndPaint(hwnd.0, &ps); +} + +#[derive(Default)] +struct StallClock { + done: usize, + advanced_at: Duration, + last_stall_ended: Option, +} + +impl StallClock { + fn sample(&mut self, done: usize, now: Duration) -> (u64, Option) { + if done != self.done { + if now - self.advanced_at >= Duration::from_secs(5) { + self.last_stall_ended = Some(now); + } + self.done = done; + self.advanced_at = now; + } + ((now - self.advanced_at).as_secs(), self.last_stall_ended.map(|end| (now - end).as_secs())) + } +} + +fn percent(done: usize, total: usize, ready: bool) -> usize { + if ready { 100 } else { done.saturating_mul(100).checked_div(total).unwrap_or(0).min(99) } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clock_advances_during_a_stall_and_remembers_recovery() { + let mut clock = StallClock::default(); + let s = Duration::from_secs; + assert_eq!(clock.sample(0, s(1)), (1, None)); + assert_eq!(clock.sample(0, s(5)), (5, None)); + assert_eq!(clock.sample(2, s(6)), (0, Some(0))); + assert_eq!(clock.sample(2, s(8)), (2, Some(2))); + assert_eq!(clock.sample(3, s(9)), (0, Some(3))); + assert_eq!(clock.sample(3, s(15)), (6, Some(9))); + assert_eq!(clock.sample(4, s(16)), (0, Some(0))); + } + + #[test] + fn close_before_the_ready_message_cancels_the_handoff() { + let progress = Arc::new(LaunchPreparation::default()); + let mut screen = Screen { progress: progress.clone(), start: Instant::now(), clock: StallClock::default(), ready: false }; + progress.cancel.store(true, Ordering::Relaxed); + assert!(!screen.release()); + assert!(!screen.ready); + } + + #[test] + fn only_a_successful_join_releases_the_last_percent() { + assert_eq!(percent(0, 0, false), 0); + assert_eq!(percent(1, 4, false), 25); + assert_eq!(percent(4, 4, false), 99); + assert_eq!(percent(4, 4, true), 100); + } +} diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 10a95991b9..a330edf9d8 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -36,6 +36,11 @@ pub fn host_main(boot_path: &Path) -> i32 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); } crate::state::set_boot(boot.clone()); + if let Err(e) = crate::hle::d3d12x::present::preparation::before_guest(&boot) { + crate::xlog_error!("Shader preparation: {e}"); + eprintln!("xcl: {e}"); + return 2; + } let _ = std::thread::Builder::new().name("xcl-split-counts".into()).spawn(|| loop { std::thread::sleep(std::time::Duration::from_secs(10)); crate::hle::d3d12x::real::log_dispatch_chain_counts(); diff --git a/crates/xcl/src/launcher.rs b/crates/xcl/src/launcher.rs index 02ed8e0852..c328c22750 100644 --- a/crates/xcl/src/launcher.rs +++ b/crates/xcl/src/launcher.rs @@ -6,7 +6,6 @@ use std::path::{Path, PathBuf}; use crate::config::{Boot, Config}; use crate::util::wide; -mod shader_window; /// Data root: `%XCL_DATA_ROOT%` or `%LOCALAPPDATA%\XCL`. pub fn data_root() -> PathBuf { @@ -393,18 +392,12 @@ fn run_with_ui(target: &Path, args: &[String], menu: bool) -> i32 { } } - if !boot.config.graphics.eq_ignore_ascii_case("null") { - if let Err(e) = shader_window::prepare(&root, &boot.config.d3d12_adapter, menu) { - eprintln!("xcl: {e}"); - return 2; - } - } let mut cmdline = quote(&exe.to_string_lossy()); for a in args { cmdline.push(' '); cmdline.push_str("e(a)); } - let code = match spawn_host(&cmdline, &root, &boot_path) { + let code = match spawn_host(&cmdline, &root, &boot_path, menu) { Ok(c) => c, Err(e) => { eprintln!("xcl: failed to start the game process: {e}"); @@ -464,12 +457,20 @@ pub fn missing_console_cpu_features() -> Vec<&'static str> { }) } -fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result { +fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path, menu: bool) -> Result { use windows_sys::Win32::Foundation::{CloseHandle, GetLastError}; use windows_sys::Win32::System::Threading::{ CreateProcessW, GetExitCodeProcess, WaitForSingleObject, INFINITE, PROCESS_INFORMATION, STARTUPINFOW, }; + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; + use windows_sys::Win32::System::Threading::{GetCurrentProcessId, OpenProcess, PROCESS_SYNCHRONIZE}; let me = std::env::current_exe().map_err(|e| e.to_string())?; + // An inheritable, synchronize-only handle identifies this exact launcher even after PID reuse. + let handle = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 1, GetCurrentProcessId()) }; + if handle.is_null() { return Err(std::io::Error::last_os_error().to_string()); } + let parent = unsafe { OwnedHandle::from_raw_handle(handle) }; + std::env::set_var("XCL_PREPARATION_PARENT", (parent.as_raw_handle() as usize).to_string()); + if menu { std::env::set_var("XCL_PREPARATION_MENU", "1"); } std::env::set_var("XCL_HOST", boot_path); let app = wide(&me.to_string_lossy()); let mut cmd = wide(cmdline); @@ -490,9 +491,12 @@ fn spawn_host(cmdline: &str, cwd: &Path, boot_path: &Path) -> Result Result { - unsafe { - let instance = GetModuleHandleW(null()); - let class = wide("XCLShaderPreparation"); - let wc = WNDCLASSW { - hInstance: instance, lpfnWndProc: Some(DefWindowProcW), - hCursor: LoadCursorW(null_mut(), IDC_ARROW), - hbrBackground: (windows_sys::Win32::Graphics::Gdi::COLOR_WINDOW + 1) as _, - lpszClassName: class.as_ptr(), ..std::mem::zeroed() - }; - if RegisterClassW(&wc) == 0 && GetLastError() != ERROR_CLASS_ALREADY_EXISTS { - return Err(std::io::Error::last_os_error().to_string()); - } - let init = INITCOMMONCONTROLSEX { dwSize: std::mem::size_of::() as u32, dwICC: ICC_PROGRESS_CLASS }; - if InitCommonControlsEx(&init) == 0 { return Err("Could not initialize the progress bar".into()); } - let hwnd = CreateWindowExW(0, class.as_ptr(), wide("XCL – Preparing shaders").as_ptr(), - WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 510, 155, - null_mut(), null_mut(), instance, null()); - if hwnd.is_null() { return Err(std::io::Error::last_os_error().to_string()); } - let label = CreateWindowExW(0, wide("STATIC").as_ptr(), wide("Reading shader records…").as_ptr(), - WS_CHILD | WS_VISIBLE, 16, 16, 420, 25, hwnd, null_mut(), instance, null()); - let timer = CreateWindowExW(0, wide("STATIC").as_ptr(), null(), - WS_CHILD | WS_VISIBLE, 16, 47, 465, 23, hwnd, null_mut(), instance, null()); - let bar = CreateWindowExW(0, PROGRESS_CLASSW, null(), WS_CHILD | WS_VISIBLE, - 16, 79, 465, 18, hwnd, null_mut(), instance, null()); - let window = Self { hwnd, label, timer, bar }; - if label.is_null() || timer.is_null() || bar.is_null() { return Err(std::io::Error::last_os_error().to_string()); } - ShowWindow(hwnd, SW_SHOWNORMAL); - Ok(window) - } - } - - fn pump(&self) -> bool { - unsafe { - let mut msg = std::mem::zeroed(); - while PeekMessageW(&mut msg, null_mut(), 0, 0, PM_REMOVE) != 0 { - TranslateMessage(&msg); - DispatchMessageW(&msg); - } - IsWindow(self.hwnd) != 0 - } - } - - fn update(&self, done: usize, total: usize, ready: bool) { - let percent = percent(done, total, ready); - unsafe { - SetWindowTextW(self.label, wide(&format!("Preparing shaders: {percent}% ({done}/{total} records)")).as_ptr()); - SendMessageW(self.bar, PBM_SETPOS, percent, 0); - } - } -} - -#[derive(Default)] -struct StallClock { - done: usize, - advanced_at: Duration, - last_stall_ended: Option, -} - -impl StallClock { - fn sample(&mut self, done: usize, now: Duration) -> (u64, Option) { - if done != self.done { - if now - self.advanced_at >= Duration::from_secs(5) { - self.last_stall_ended = Some(now); - } - self.done = done; - self.advanced_at = now; - } - ((now - self.advanced_at).as_secs(), self.last_stall_ended.map(|end| (now - end).as_secs())) - } -} - -fn percent(done: usize, total: usize, ready: bool) -> usize { - if ready { 100 } else { done.saturating_mul(100).checked_div(total).unwrap_or(0).min(99) } -} - -pub(super) fn prepare(root: &Path, adapter: &str, menu: bool) -> Result<(), String> { - let pack = root.join("shaders.rpf"); - let loose = root.join("shaders"); - if !pack.try_exists().map_err(|e| e.to_string())? && !loose.is_dir() { return Ok(()); } - let window = Window::open()?; - let progress = LaunchPreparation { adapter, done: 0.into(), total: 0.into(), cancel: false.into() }; - let start = Instant::now(); - let mut clock = StallClock::default(); - let mut last_times = None; - let mut last = None; - let result = wait_for_worker(&progress, || prepare_for_launch(root, &progress), || { - if !window.pump() { return false; } - let total = progress.total.load(Ordering::Relaxed); - let done = progress.done.load(Ordering::Relaxed); - let times = clock.sample(done, start.elapsed()); - if last_times != Some(times) { - let mut text = format!("No shader progress for {} s", times.0); - if let Some(ago) = times.1 { text.push_str(&format!(" | Last stall ended {ago} s ago")); } - unsafe { SetWindowTextW(window.timer, wide(&text).as_ptr()); } - last_times = Some(times); - } - if total > 0 && last != Some(done) { - window.update(done, total, false); - last = Some(done); - } - true - }); - match &result { - Ok(()) => { - let total = progress.total.load(Ordering::Relaxed); - window.update(total, total, true); - unsafe { - windows_sys::Win32::Graphics::Gdi::UpdateWindow(window.label); - windows_sys::Win32::Graphics::Gdi::UpdateWindow(window.bar); - } - } - Err(message) if !progress.cancel.load(Ordering::Relaxed) && menu => unsafe { - MessageBoxW(window.hwnd, wide(message).as_ptr(), wide("XCL – Shader preparation failed").as_ptr(), MB_OK | MB_ICONERROR); - }, - _ => {} - } - result -} - -fn wait_for_worker(progress: &LaunchPreparation, work: impl FnOnce() -> Result<(), String> + Send, - mut pump: impl FnMut() -> bool) -> Result<(), String> { - std::thread::scope(|scope| { - let worker = scope.spawn(work); - while !worker.is_finished() { - if !pump() { progress.cancel.store(true, Ordering::Relaxed); } - std::thread::sleep(Duration::from_millis(80)); - } - let result = worker.join().map_err(|_| "Shader preparation worker stopped unexpectedly")?; - if !pump() { progress.cancel.store(true, Ordering::Relaxed); } - if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } - result - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn launch_waits_for_success_and_propagates_failure_or_close() { - let progress = LaunchPreparation { adapter: "auto", done: 0.into(), total: 0.into(), cancel: false.into() }; - let called = std::sync::atomic::AtomicBool::new(false); - wait_for_worker(&progress, || { - while !called.load(Ordering::Acquire) { std::thread::yield_now(); } - Ok(()) - }, || { called.store(true, Ordering::Release); true }).unwrap(); - assert_eq!(wait_for_worker(&progress, || Err("bad shader".into()), || true).unwrap_err(), "bad shader"); - let cancelled = wait_for_worker(&progress, || { - while !progress.cancel.load(Ordering::Relaxed) { std::thread::yield_now(); } - Ok(()) - }, || false); - assert_eq!(cancelled.unwrap_err(), "Shader preparation cancelled"); - } - - #[test] - fn clock_advances_during_a_stall_and_remembers_recovery() { - let mut clock = StallClock::default(); - let s = Duration::from_secs; - assert_eq!(clock.sample(0, s(1)), (1, None)); - assert_eq!(clock.sample(0, s(5)), (5, None)); - assert_eq!(clock.sample(2, s(6)), (0, Some(0))); - assert_eq!(clock.sample(2, s(8)), (2, Some(2))); - assert_eq!(clock.sample(3, s(9)), (0, Some(3))); - assert_eq!(clock.sample(3, s(15)), (6, Some(9))); - assert_eq!(clock.sample(4, s(16)), (0, Some(0))); - } - - #[test] - fn only_a_successful_join_releases_the_last_percent() { - assert_eq!(percent(0, 0, false), 0); - assert_eq!(percent(1, 4, false), 25); - assert_eq!(percent(4, 4, false), 99); - assert_eq!(percent(4, 4, true), 100); - } -} diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 7b4338c231..27493a13d0 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1714,8 +1714,9 @@ fn used_compute(blob: &[u8], used: &std::collections::HashSet) -> bool { used.contains(&crate::hle::d3d12x::real::shaders_key(&[blob.to_vec()])) } -pub(crate) struct LaunchPreparation<'a> { - pub adapter: &'a str, +#[derive(Default)] +pub(crate) struct LaunchPreparation { + pub adapter: String, pub done: AtomicUsize, pub total: AtomicUsize, pub cancel: std::sync::atomic::AtomicBool, @@ -1767,7 +1768,7 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R fn precompile(input: &Input, limit: usize, windows: u32, split: Option, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet>, t0: std::time::Instant, startup: Option<&LaunchPreparation>) -> Result<(), String> { let pipelines = if pipelines { - let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter)) + let mut p = Pipelines::for_adapter(startup.map_or("auto", |p| p.adapter.as_str())) .map_err(|e| format!("No pipeline device: {e}"))?; if startup.is_some() && std::env::var_os("XCL_PIPELINE_MAX_KB").is_none() { p.max_dxil = 0; @@ -1789,7 +1790,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on // the compiles run on the DXC pool; these threads translate and keep it fed let threads = recomp::dxc::compile_threads() + 2; // no title runs: only a little commit is kept free besides the compiles - recomp::dxc::set_memory_reserve(2); + if startup.is_none() { recomp::dxc::set_memory_reserve(2); } // VS / PS: the 32-lane form wherever the GPU can run 32-lane waves (`pso::graphics_wave32`); // `--split` sets both let startup_device = pipelines.filter(|_| startup.is_some()); @@ -1825,7 +1826,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option, on continue; }; let Some(sh) = xbox::parse(&blob) else { - if startup.is_some() { failed.fetch_add(1, Ordering::Relaxed); } + if startup.is_some() && !matches!(shader::classify(&blob).0, shader::Kind::Dxil | shader::Kind::Dxbc) { + failed.fetch_add(1, Ordering::Relaxed); + } record_done(); continue; }; diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 027638eee7..4f238248a9 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -128,6 +128,9 @@ fn test_title_runs_and_game_folder_is_untouched() { copy_dir(&manifest.join("..").join("..").join("tests").join("data").join("testgame"), &game); std::fs::copy(&title, game.join("xcl_testtitle.exe")).unwrap(); std::fs::copy(&dll, game.join("testgame_mw.dll")).unwrap(); + // Already-compiled graphics bytecode still goes through startup discovery. + std::fs::create_dir(game.join("shaders")).unwrap(); + std::fs::copy(manifest.join("../../tests/data/dxil/dxc_vs_uav.dxil"), game.join("shaders/vertex.dxbc")).unwrap(); let before = snapshot(&game); let out = Command::new(&xcl) @@ -157,6 +160,10 @@ fn test_title_runs_and_game_folder_is_untouched() { assert!(stdout.contains("xcl_testtitle: done, failures: 0"), "the test title did not run to the end"); assert!(out.status.success(), "exit code {:?}", out.status.code()); + let log = std::fs::read_to_string(data.join("XCL.TestTitle/logs/xcl.log")).unwrap(); + let window = |tag| log.lines().find_map(|line| line.split_once(tag).map(|(_, hwnd)| hwnd)).unwrap(); + assert_eq!(window("Shader preparation window "), window("present: swap chain window ")); + // (2) the game folder is untouched assert_eq!(snapshot(&game), before, "GAME FOLDER WAS MODIFIED"); From b9c780ac136df9809c6a98d2d324401157c81320 Mon Sep 17 00:00:00 2001 From: bmjask <11672696+bmjask@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:08:18 -0500 Subject: [PATCH 221/258] Scripts: allow shader preparation time before the smoke guest timer The host starts the measured title interval only after the shader gate succeeds. Let a full-pack run specify a longer launcher deadline and record that setting in the evidence manifest. Keep the default timeout and regression block unchanged. --- scripts/smoke.ps1 | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/smoke.ps1 b/scripts/smoke.ps1 index db296218b2..ad15cbc0c0 100644 --- a/scripts/smoke.ps1 +++ b/scripts/smoke.ps1 @@ -2,7 +2,7 @@ # prints an `xcl-smoke` block to paste into the PR's "Regression run" section – once built # from main, once from the PR's head commit (CONTRIBUTING.md, "What a PR needs to be merged"). # -# .\scripts\smoke.ps1 -Game 'D:\Games\SomeTitle' [-Seconds 60] [-Xcl .\target\release\xcl.exe] [-Title
= Mutex::new(Table::new()); // The dirty-page scan consumes write-watch state for every submission thread. // Keep the scan, pending-list update and GPU uploads together. static REFRESH: Mutex<()> = Mutex::new(()); + +/// `XCL_LOOK_SKIP` (on by default, `0`: off): a submit whose lists were all closed before the last +/// write-watch look began, and not submitted since, takes no look of its own. +/// +/// The look (`GetWriteWatch` over the title's memory XCL keeps in step) was 60 % of a retail +/// title's frame in its world: ~6 ms at each of 80–100 submits a second. What the title wrote +/// for a list it wrote before closing it, and a look that began after the close took those +/// pages already; the next look takes the rest. A list submitted again (a recording the title +/// runs twice, its data written anew in between) always looks, and so does the first submit of +/// each frame. +fn look_skip_on() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_LOOK_SKIP").map_or(true, |v| v.trim() != "0")) +} + +fn now_us() -> u64 { + static T0: std::sync::OnceLock = std::sync::OnceLock::new(); + T0.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 + 1 +} + +/// When the last finished look began (µs, `now_us`; 0: none yet), and the frame it was in. +static LOOK_BEGAN_US: AtomicU64 = AtomicU64::new(0); +static LOOK_FRAME: AtomicU64 = AtomicU64::new(u64::MAX); + +/// Each title list's last Close (µs) and whether it was submitted since. +static CLOSED: Mutex>> = Mutex::new(None); + +/// The title closed `list` (the object it submits). +pub(super) fn note_list_closed(list: *mut c_void) { + if !look_skip_on() || list.is_null() { + return; + } + CLOSED.lock().unwrap().get_or_insert_with(std::collections::HashMap::new).insert(list as usize, (now_us(), false)); +} + +thread_local! { + /// The next `refresh` on this thread may leave its look out (`look_needed_for` said so). + static SKIP_LOOK: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Before a submit of `lists`: whether its refresh needs a look of its own (then `refresh` looks; +/// else it is told to leave it out). The lists count as submitted from here on. +pub(super) fn decide_look(lists: &[*mut c_void]) { + if !look_skip_on() { + return; + } + let began = LOOK_BEGAN_US.load(Ordering::Acquire); + let same_frame = LOOK_FRAME.load(Ordering::Acquire) == super::present::presents(); + let mut g = CLOSED.lock().unwrap(); + let m = g.get_or_insert_with(std::collections::HashMap::new); + let mut skip = began != 0 && same_frame && !lists.is_empty(); + for &l in lists { + match m.get_mut(&(l as usize)) { + Some((closed, submitted)) => { + if *submitted || *closed >= began { + skip = false; + } + *submitted = true; + } + None => skip = false, + } + } + drop(g); + SKIP_LOOK.with(|c| c.set(skip)); + static SKIPPED: AtomicU64 = AtomicU64::new(0); + static ALL: AtomicU64 = AtomicU64::new(0); + let all = ALL.fetch_add(1, Ordering::Relaxed) + 1; + if skip { + SKIPPED.fetch_add(1, Ordering::Relaxed); + } + if all.is_power_of_two() && all >= 256 { + crate::xlog_info!("title textures: {} of {all} submits took no write-watch look of their own (XCL_LOOK_SKIP)", SKIPPED.load(Ordering::Relaxed)); + } +} static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen, @@ -458,6 +532,14 @@ pub fn counts() -> (usize, u64) { (TEXTURES.lock().unwrap().by_res.len(), UPLOADS.load(Ordering::Relaxed)) } +/// The title textures kept in step that are committed resources of their own (not on shared +/// `vram::Pages` tiles): how many, and their console size in bytes (memory accounting, #2688; +/// the PC resource can take somewhat more). +pub fn committed_bytes() -> (usize, u64) { + let t = TEXTURES.lock().unwrap(); + t.by_res.values().chain(t.shadowed.values()).filter(|e| !e.placed).fold((0, 0), |(n, b), e| (n + 1, b + e.tex.size())) +} + /// Whether a non-depth render target / UAV texture is small enough to be a CPU-filled glyph or UI /// atlas (`<= 1M` pixels, up to `2048` on either axis, e.g. a retail title's `2048x128` R8 glyph cache). fn is_small_cpu_filled_target(w: u64, h: u32, samples: u32, flags: u32) -> bool { @@ -906,6 +988,8 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: unsafe fn refresh_once(queue: *mut c_void) { reclaim_completed_on_queue(queue as usize); + // (taken first: a return below must not leave it for the next submit on this thread) + let skip_look = SKIP_LOOK.with(|c| c.replace(false)); let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); if !sparse && TEXTURES_LEN.load(Ordering::Relaxed) == 0 { @@ -913,6 +997,8 @@ unsafe fn refresh_once(queue: *mut c_void) { } recheck_gpu_view_sources(); let watch_t0 = std::time::Instant::now(); + let look_began = now_us(); + let look_frame = super::present::presents(); let mut page = 0x1000u32; super::sparse::drain_lazy_commits_if_pending(); let ranges = cached_watch_ranges(u); @@ -924,9 +1010,11 @@ unsafe fn refresh_once(queue: *mut c_void) { if buf.len() < 16384 { buf.resize(16384, std::ptr::null_mut()); } - super::list_x::mirror_look_begin(); - for &(base, size) in ranges.iter() { - take_written(base, size, &mut buf, &mut dirty, &mut page); + if !skip_look { + super::list_x::mirror_look_begin(); + for &(base, size) in ranges.iter() { + take_written(base, size, &mut buf, &mut dirty, &mut page); + } } }); // views of physical pages are not write-watched: their writes are caught by guards @@ -938,6 +1026,12 @@ unsafe fn refresh_once(queue: *mut c_void) { dirty.len() }); super::sparse::note_watch(watch_t0.elapsed(), dirty_len); + if !skip_look { + // what later submits compare their lists' closes with + LOOK_BEGAN_US.store(look_began, Ordering::Release); + LOOK_FRAME.store(look_frame, Ordering::Release); + } + super::prof::add(super::prof::Kind::SubmitWatch, watch_t0.elapsed()); if super::present::trace_frame() { // every 600th look: what the CPU's view of a few textures holds now (does the title's // data reach the address at all, and is the texture still kept in step?) @@ -970,6 +1064,7 @@ unsafe fn refresh_once(queue: *mut c_void) { // the title's own memory: what the CPU wrote goes to its video memory first if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { DIRTY_BUF.with(|dcell| { + let _prof = super::prof::span(super::prof::Kind::SubmitSparse); let dirty = dcell.borrow(); super::sparse::before_execute(q, &dirty, page as usize); super::vram::before_execute(q); @@ -1023,7 +1118,9 @@ unsafe fn refresh_once(queue: *mut c_void) { }); seed_stream_recheck(&todo, &ranges, recheck_frame); let uploaded = !todo.is_empty(); + let upload_prof = super::prof::span(super::prof::Kind::SubmitTextures); upload_all(todo, ID3D12CommandQueue::from_raw_borrowed(&queue)); + drop(upload_prof); // Ensure the submitting queue waits for any `vram::map_levels` tile mappings queued inside // `upload_all`, even if an upload batch fell back to the upload queue or exited early. if uploaded { @@ -1548,6 +1645,7 @@ unsafe fn submit_on_title_queue(dev: &ID3D12Device, queue: &ID3D12CommandQueue, drop(f); return Err(e.to_string()); } + super::flight::signaled("texture uploads", key, &q.fence, q.value); q.bytes = q.bytes.saturating_add(f.bytes); let v = q.value; q.in_flight.push_back((v, f)); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 262592ecb2..321db34960 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -1324,6 +1324,7 @@ impl Pages { let coord = D3D12_TILED_RESOURCE_COORDINATE { Subresource: sub, ..Default::default() }; let region = D3D12_TILE_REGION_SIZE { NumTiles: num_tiles, UseBox: false.into(), ..Default::default() }; let _timer = step(Step::Map); + let flight_t = std::time::Instant::now(); self.queue.UpdateTileMappings( res, 1, @@ -1336,6 +1337,7 @@ impl Pages { Some(self.scratch_counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); + super::flight::tile_map("vram", windows::core::Interface::as_raw(&self.queue) as usize, (num_tiles) as u64, flight_t.elapsed()); } self.dirty_signal = true; } @@ -1349,6 +1351,7 @@ impl Pages { let coord = D3D12_TILED_RESOURCE_COORDINATE::default(); let region = D3D12_TILE_REGION_SIZE { NumTiles: total, UseBox: false.into(), ..Default::default() }; let flag = D3D12_TILE_RANGE_FLAG_NULL; + let flight_t = std::time::Instant::now(); self.queue.UpdateTileMappings( res, 1, @@ -1361,6 +1364,7 @@ impl Pages { Some(&total), D3D12_TILE_MAPPING_FLAG_NONE, ); + super::flight::tile_map("vram", windows::core::Interface::as_raw(&self.queue) as usize, (total) as u64, flight_t.elapsed()); self.dirty_signal = true; } @@ -1460,6 +1464,7 @@ impl Pages { if ok { self.value += 1; let _ = self.queue.Signal(&self.fence, self.value); + super::flight::signaled("vram pages", windows::core::Interface::as_raw(&self.queue) as usize, &self.fence, self.value); self.dirty_signal = false; slot.fence_val = self.value; } @@ -1471,6 +1476,7 @@ impl Pages { let _timer = step(Step::Signal); self.value += 1; let _ = self.queue.Signal(&self.fence, self.value); + super::flight::signaled("vram pages", windows::core::Interface::as_raw(&self.queue) as usize, &self.fence, self.value); self.dirty_signal = false; } } @@ -1489,6 +1495,7 @@ impl Pages { let flags: Vec = ranges.iter().map(|r| r.0).collect(); let offsets: Vec = ranges.iter().map(|r| r.1).collect(); let counts: Vec = ranges.iter().map(|r| r.2).collect(); + let flight_t = std::time::Instant::now(); self.queue.UpdateTileMappings( res, 1, @@ -1501,6 +1508,7 @@ impl Pages { Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); + super::flight::tile_map("vram", windows::core::Interface::as_raw(&self.queue) as usize, (region.NumTiles) as u64, flight_t.elapsed()); self.dirty_signal = true; } @@ -1868,6 +1876,7 @@ impl Pages { let flags: Vec = ranges.iter().map(|r| r.0).collect(); let offsets: Vec = ranges.iter().map(|r| r.1).collect(); let counts: Vec = ranges.iter().map(|r| r.2).collect(); + let flight_t = std::time::Instant::now(); self.queue.UpdateTileMappings( res, 1, @@ -1880,6 +1889,7 @@ impl Pages { Some(counts.as_ptr()), D3D12_TILE_MAPPING_FLAG_NONE, ); + super::flight::tile_map("vram", windows::core::Interface::as_raw(&self.queue) as usize, (total) as u64, flight_t.elapsed()); } } self.dirty_signal = true; @@ -2515,6 +2525,9 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let mut do_reclaim = false; let mut need_unmap_work = false; let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; + // the page mappings this queue waits for, waited on the CPU after the lock (as the sparse + // windows' are: `sparse::cpu_waited_for_mappings`) + let mut mapping_wait: Option<(ID3D12Fence, u64)> = None; { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -2528,8 +2541,7 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { pages.flush_signal(); let key = queue.as_raw() as usize; if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { - let _ = queue.Wait(&pages.fence, pages.value); - super::list_x::note_internal_wait(key, "texture page mappings", &pages.fence, pages.value); + mapping_wait = Some((pages.fence.clone(), pages.value)); pages.waited.insert(key, pages.value); } let low_commit = commit_low(); @@ -2550,6 +2562,12 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { || !pages.idle.is_empty(); } } + if let Some((fence, value)) = mapping_wait { + if !super::sparse::cpu_waited_for_mappings(&fence, value, "texture page mappings") { + let _ = queue.Wait(&fence, value); + super::list_x::note_internal_wait(queue.as_raw() as usize, "texture page mappings", &fence, value); + } + } if need_unmap_work { seal_and_drain_unmaps(&dev, dev_key, Some(queue)); } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 171bed2474..71686fc8e9 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -68,6 +68,7 @@ pub fn host_main(boot_path: &Path) -> i32 { [p, e, d, x, f[0], f[1], f[2], f[3], r, b >> 20, fail] }; let mut last = snap(); + let mut prof_last = crate::hle::d3d12x::prof::totals(); loop { std::thread::sleep(std::time::Duration::from_secs(2)); // a device removed while every title thread waits: nothing else would ask @@ -79,8 +80,17 @@ pub fn host_main(boot_path: &Path) -> i32 { let o = std::sync::atomic::Ordering::Relaxed; if SEEN.swap(frames, o) != frames || frames < 100 { IDLE.store(0, o); - } else if IDLE.fetch_add(1, o) == 2 { - crate::hle::d3d12x::culprit::on_watchdog_release(); + } else { + let idle = IDLE.fetch_add(1, o); + if idle == 2 { + crate::hle::d3d12x::culprit::on_watchdog_release(); + } + // `XCL_STALL_DUMP=1`: where every thread is, 8 s into a stall (3 stalls at most) + static DUMPS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if idle == 3 && std::env::var("XCL_STALL_DUMP").is_ok_and(|v| v.trim() == "1") && DUMPS.fetch_add(1, o) < 3 { + crate::xlog_info!("no frame for 8 s: thread dump"); + crate::eh::dump_threads(); + } } let now = snap(); let d: Vec = now.iter().zip(last).map(|(a, b)| a - b).collect(); @@ -88,6 +98,12 @@ pub fn host_main(boot_path: &Path) -> i32 { "activity (2 s): {} presents, {} submits, {} draws, {} dispatches, {} frame-event waits ({} timed out), {} frame statistics ({} not flipped); DirectStorage {} requests, {} MB, {} failed", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10] ); + // where the title's threads waited in XCL meanwhile (`d3d12x::prof`) + let prof_now = crate::hle::d3d12x::prof::totals(); + crate::xlog_info!("{}", crate::hle::d3d12x::prof::line(prof_last, prof_now, d[0], 2.0)); + prof_last = prof_now; + // tile mappings, resources made and the video memory budget (`d3d12x::flight`) + crate::xlog_info!("{}", crate::hle::d3d12x::flight::line()); // where the memory is: the process's commit, video memory, and XCL's parts of it let private = unsafe { use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; @@ -116,6 +132,14 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(pools as u64), mb(pools_mapped as u64) ); + // the same against DXGI's budget, by owner, with what XCL does not count (#2688) + crate::xlog_info!("{}", crate::hle::d3d12x::memory_report::snapshot().line()); + crate::xlog_info!("memory: the title's committed resources alive (MB): {}", crate::hle::d3d12x::real::live_committed_line()); + // and every 10 s where the rest is: the address space walked + static WALKS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if WALKS.fetch_add(1, o) % 5 == 0 { + crate::xlog_info!("{}", crate::hle::d3d12x::memory_report::walk_line()); + } last = now; } }); From 196a5628c9aa87f14d33a1ea503d2255a1df75c4 Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:09 +0100 Subject: [PATCH 232/258] xcl run: retry failed shader preparation batches A driver device limit can end workers during startup. Retry their batches once after the other workers finish, and count only batches that still fail. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- README.md | 1 + crates/xcl/src/shaders.rs | 59 ++++++++++++++++++++++++++++++++++----- 2 files changed, 53 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index dc548f92ad..c35620ec20 100644 --- a/README.md +++ b/README.md @@ -244,6 +244,7 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder the shader cache, at most `XCL_GFX_RECORDS_MB`, default 64) and built before the title starts on the next launch, with their driver blobs kept, so the title makes them from those in milliseconds. `XCL_PREPARE_GRAPHICS=0` leaves that pass out. Later launches reuse matching cache entries. + If a preparation worker fails, XCL retries its batch once after the other workers finish. Closing the window cancels the launch. A compiler or driver failure stops it and reports the cause. Null-renderer runs skip shader preparation. With presentation disabled, the gate runs without a window. - **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index c90b1e06eb..6e6e5980b7 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1939,6 +1939,12 @@ fn worker_command(me: &Path) -> std::process::Command { /// own part) the count of `records` in all on the screen while they run: whether preparation was /// cancelled (they are ended then), how many failed, and the summary line each wrote last /// (`graphics_summary`). +/// +/// A worker that fails has its part done again once the others are through, and counts as failed +/// only when that fails too. A driver gives only so many processes a device at once (an AMD one: +/// nine; the tenth `D3D12CreateDevice` and every one after it returns 0x887A0005), so with ten +/// workers beside the title's own device two ended at once, every start, and the title built +/// their fifth of the pipelines itself while it loaded its world. fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut command: impl FnMut(usize) -> std::process::Command) -> (bool, usize, Vec) { use std::io::BufRead; // the workers' pass has its own count on the screen: the records they have passed @@ -1948,14 +1954,21 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut progress.workers.store(workers, Ordering::Relaxed); let counts: Vec = (0..workers).map(|_| AtomicUsize::new(0)).collect(); let summaries: Vec> = (0..workers).map(|_| Mutex::new(String::new())).collect(); + let mut parts: Vec = (0..workers).collect(); + let (mut cancelled, mut failed) = (false, Vec::new()); + for again in [false, true] { + failed.clear(); let mut children = Vec::new(); - for i in 0..workers { + for &i in &parts { match command(i).spawn() { Ok(child) => children.push((i, child)), - Err(e) => crate::xlog_warn!("Shader preparation: worker {i} did not start: {e}"), + Err(e) => { + failed.push(i); + crate::xlog_warn!("Shader preparation: worker {i} did not start: {e}"); + } } } - let cancelled = std::thread::scope(|s| { + cancelled = std::thread::scope(|s| { for (i, child) in children.iter_mut() { let Some(err) = child.stderr.take() else { continue }; let (count, summary) = (&counts[*i], &summaries[*i]); @@ -1984,18 +1997,50 @@ fn in_workers(workers: usize, records: usize, progress: &LaunchPreparation, mut std::thread::sleep(std::time::Duration::from_millis(100)); } }); - let mut failed = 0; + let note = if again || cancelled { "" } else { " – its part is done again after the others" }; for (i, child) in children.iter_mut() { match child.wait() { Ok(st) if st.success() => {} - Ok(st) => { failed += 1; crate::xlog_warn!("Shader preparation: worker {i} ended with {st}"); } - Err(e) => { failed += 1; crate::xlog_warn!("Shader preparation: worker {i}: {e}"); } + Ok(st) => { failed.push(*i); crate::xlog_warn!("Shader preparation: worker {i} ended with {st}{note}"); } + Err(e) => { failed.push(*i); crate::xlog_warn!("Shader preparation: worker {i}: {e}{note}"); } } } + if cancelled || failed.is_empty() { + break; + } + parts = failed.clone(); + } progress.workers.store(0, Ordering::Relaxed); progress.total.store(total_before, Ordering::Relaxed); progress.done.store(done_before, Ordering::Relaxed); - (cancelled, failed, summaries.into_iter().map(|s| s.into_inner().unwrap()).collect()) + (cancelled, failed.len(), summaries.into_iter().map(|s| s.into_inner().unwrap()).collect()) +} + +#[cfg(test)] +mod worker_tests { + use super::*; + + /// A worker that fails has its part done again once the others are through, and only a part + /// that fails twice counts as failed. + #[test] + fn a_failed_workers_part_is_done_again() { + let exits = |code: i32| { + let mut c = std::process::Command::new("cmd"); + c.args(["/c", "exit", &code.to_string()]).stderr(std::process::Stdio::piped()); + c + }; + let progress = LaunchPreparation::default(); + // worker 1 fails the first time (as one a driver gave no device), worker 2 both times + let mut started = [0usize; 3]; + let (cancelled, failed, summaries) = in_workers(3, 30, &progress, |i| { + started[i] += 1; + exits(if i == 2 || (i == 1 && started[1] == 1) { 3 } else { 0 }) + }); + assert!(!cancelled); + assert_eq!(started, [1, 2, 2], "the parts of the workers that failed are started again, the other is not"); + assert_eq!(failed, 1, "only the part that failed twice"); + assert_eq!(summaries.len(), 3); + } } /// The graphics pipelines earlier runs used (`gfx_records`), built before the title starts by From 00fe5aec065d4446b8484666211a64bba36304f6 Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:09 +0100 Subject: [PATCH 233/258] Recompiler: bound long shader loops and keep mesh budgets simple Port #2865 to keep per-region budgets in compute and kernel shaders. Charge more budget for longer loops so a compute dispatch cannot spend its full iteration budget in a large loop. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- crates/xcl/src/gpu/dxil/compact.rs | 21 ++++-- crates/xcl/src/gpu/dxil/compact_tests.rs | 28 ++++++++ crates/xcl/src/gpu/dxil/kernel.rs | 18 +++-- crates/xcl/src/gpu/recomp/mod.rs | 48 +++++++++++-- crates/xcl/src/gpu/recomp/tests.rs | 89 ++++++++++++++++++++++++ 5 files changed, 186 insertions(+), 18 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index e10140f4bb..bb6cdb6137 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -515,8 +515,10 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { vec![ALL_SGPRS_MASK | SCC_LIVE_BIT; mblocks.len()] }; - // a loop head's guard names its loop region: heads of two regions are two classes - let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); + // a loop head's guard names its loop region and what an iteration spends (`loop_cost`): + // heads of two regions, or of two costs, are two classes + let loops = crate::gpu::recomp::loop_ranges(&cfg.insts); + let regions = crate::gpu::recomp::budget_regions(&loops); let build = |param_lit: bool, param_pc: bool| { let mut ids: HashMap<(Vec, &'static str), u32> = HashMap::new(); let (mut class, mut rep, mut next, mut blk_lit) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); @@ -525,7 +527,9 @@ pub fn plan(cfg: &Cfg, lw: &Lw) -> Option { let p_lit = if param_lit { single_param_lit(cfg, blk) } else { None }; blk_lit.push(p_lit); let region = if blk.is_header { - crate::gpu::recomp::budget_region(®ions, cfg.blocks[order[n]].pc).unwrap_or(0) as u64 + let pc = cfg.blocks[order[n]].pc; + let cost = crate::gpu::recomp::loop_cost(&loops, pc) as u64; + crate::gpu::recomp::budget_region(®ions, pc).unwrap_or(0) as u64 + ((cost - 1) << 32) } else { 0 }; @@ -804,7 +808,8 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let (at, to) = (lw.tmp_var(), lw.tmp_var()); let (at, to, budget) = (slot(lw, at), slot(lw, to), slot(lw, VAR_BUDGET)); - let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); + let loops = crate::gpu::recomp::loop_ranges(&cfg.insts); + let regions = crate::gpu::recomp::budget_regions(&loops); let owner = if regions.is_empty() { None } else { Some((slot(lw, VAR_BUDGET_OWNER), slot(lw, VAR_BUDGET_TOTAL))) }; lw.s.m.set_block(head); let b = lw.s.m.load(at, 4); @@ -919,6 +924,8 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block if blk.is_header { // a loop head spends the loop budget (of its region: the recompiler's `loop_guard`) let region = owner.zip(crate::gpu::recomp::budget_region(®ions, cfg.blocks[p.order[r]].pc)); + // (1 for a short loop: the guard's instructions are then what they always were) + let cost = crate::gpu::recomp::loop_cost(&loops, cfg.blocks[p.order[r]].pc); let mut left = lw.s.m.load(budget, 4); if let Some(((own_at, total_at), reg)) = region { let own = lw.s.m.load(own_at, 4); @@ -927,10 +934,10 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block let rv = lw.c(reg); lw.s.m.store(own_at, rv, 4); let total = lw.s.m.load(total_at, 4); - let spent = lw.cmpc(Pred::Eq, total, 0); + let spent = if cost == 1 { lw.cmpc(Pred::Eq, total, 0) } else { lw.cmpc(Pred::ULt, total, cost) }; left = lw.selc(spent, 0, left); } - let none = lw.cmpc(Pred::Eq, left, 0); + let none = if cost == 1 { lw.cmpc(Pred::Eq, left, 0) } else { lw.cmpc(Pred::ULt, left, cost) }; let (out, body) = (lw.block(Some(1)), lw.block(Some(1))); lw.cond_br(none, out, body); lw.s.m.set_block(out); @@ -938,7 +945,7 @@ pub fn emit_with_nest(lw: &mut Lw, cfg: &Cfg, p: &Plan, head: Block, exit: Block lw.s.m.store(to, end, 4); lw.s.m.br(target_latch); lw.s.m.set_block(body); - let one = lw.c(1); + let one = lw.c(cost); let l = lw.sub(left, one); lw.s.m.store(budget, l, 4); if let Some(((_, total_at), _)) = region { diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index 06c198724d..8f3a36ff24 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -106,6 +106,34 @@ fn gpu_compact_form_spends_the_loop_budget_as_the_plain_form() { assert_eq!(&c.sgpr[..2], &p.sgpr[..2]); } +/// In both of the direct translator's forms an iteration of a long loop spends more of the loop +/// budget (`recomp::loop_cost`): a loop of 80 instructions (320 B) that never ends runs half the +/// budget's iterations, as on the HLSL path +/// (`recomp::tests::gpu_an_endless_long_loop_stops_after_the_budget_by_its_cost`). +#[test] +fn gpu_an_endless_long_loop_stops_after_the_budget_by_its_cost_in_both_forms() { + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; + let i = |nm: &str, e: &str, f: &[(&str, u64)], lit: Option| encode(nm, e, f, lit).unwrap_or_else(|x| panic!("{nm}: {x}")); + let mut v = Vec::new(); + v.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)], None)); + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + for _ in 0..77 { + v.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)], None)); + } + v.extend(i("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None)); + v.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFB0)], None)); + v.extend(i("S_ENDPGM", "ENC_SOPP", &[], None)); + for compact in [true, false] { + let k = translate_full_as(&v, o, compact).unwrap_or_else(|e| panic!("compact {compact}: {e}")); + let r = runner::run_with_statics(&k.dxil, &KernelState::default(), &[], &[], &[], &k.static_samplers).expect("GPU run"); + assert_eq!(r.sgpr[0], (1 << 16) / 2, "compact {compact}"); + } +} + /// The direct translator's forms give each loop region its own budget as the HLSL path does /// (`recomp::tests::gpu_a_loop_after_a_spin_to_the_budget_still_runs`). #[test] diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index fb743c8573..f7f2579ab0 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -429,7 +429,14 @@ fn translate_on_this_thread( None => super::compact::emit(&mut lw, &cfg, p, h0, exit)?, } } - let regions = crate::gpu::recomp::budget_regions(&crate::gpu::recomp::loop_ranges(&cfg.insts)); + // Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh + // stages on the single-budget CFG so AMD LLPC does not trip on multi-PHI mesh loop headers. + let loops = crate::gpu::recomp::loop_ranges(&cfg.insts); + let regions = if compute || kernel { + crate::gpu::recomp::budget_regions(&loops) + } else { + Vec::new() + }; for &b in cfg.rpo.iter().filter(|_| plan.is_none()) { let h = head(&mut lw, b); lw.s.m.set_block(h); @@ -447,6 +454,9 @@ fn translate_on_this_thread( if cfg.headers.contains(&b) { // a lane's loop iterations are capped (the recompiler's LOOP_GUARD / loop_guard) let region = crate::gpu::recomp::budget_region(®ions, cfg.blocks[b].pc); + // an iteration of a long loop spends more than 1 (the recompiler's `loop_cost`); + // with 1 the guard is the instructions it always was + let cost = crate::gpu::recomp::loop_cost(&loops, cfg.blocks[b].pc); let mut left = lw.rd(VAR_BUDGET); if let Some(r) = region { let own = lw.rd(VAR_BUDGET_OWNER); @@ -455,14 +465,14 @@ fn translate_on_this_thread( let rv = lw.c(r); lw.wr(VAR_BUDGET_OWNER, rv); let total = lw.rd(VAR_BUDGET_TOTAL); - let spent = lw.cmpc(Pred::Eq, total, 0); + let spent = if cost == 1 { lw.cmpc(Pred::Eq, total, 0) } else { lw.cmpc(Pred::ULt, total, cost) }; left = lw.selc(spent, 0, left); } - let none = lw.cmpc(Pred::Eq, left, 0); + let none = if cost == 1 { lw.cmpc(Pred::Eq, left, 0) } else { lw.cmpc(Pred::ULt, left, cost) }; let cont = lw.block(Some(1)); lw.cond_br(none, end, cont); lw.s.m.set_block(cont); - let one = lw.c(1); + let one = lw.c(cost); let l = lw.sub(left, one); lw.wr(VAR_BUDGET, l); if region.is_some() { diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index ec33fdd3b3..6cdfe0835c 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -812,19 +812,47 @@ pub(crate) fn budget_region(regions: &[(u64, u64)], head: u64) -> Option { regions.iter().position(|&(a, b)| a <= head && head < b).map(|k| k as u32 + 1) } +/// An iteration of a loop spends one of the loop budget for every this many bytes of the loop's +/// code ([`loop_cost`]) ... +pub(crate) const LOOP_COST_BYTES: u64 = 128; +/// ... and at most this many: the longest loop still gets 256 iterations of one budget. +pub(crate) const LOOP_COST_MOST: u32 = 256; + +/// What an iteration of the loop headed at `head` spends of the loop budget: 1 for a short +/// loop, more for a long one (the innermost of `loops` that holds `head`, a unit for every +/// [`LOOP_COST_BYTES`] of it). The budget counts iterations, and what an iteration costs the GPU +/// grows with the loop: a retail program's 9 KB loop nest, given what made every one of its +/// loops run on, spent its 131 072 iterations in one group of 64 lanes for more than 20 s, and +/// the driver was reset. With the cost that nest stops after 1 771 iterations. A loop shorter +/// than twice the unit costs 1, and its guard is what it was. A ray-tracing program's budget is +/// small already (`dxil::kernel::RT_LOOP_BUDGET`): its loops cost 1. +pub(crate) fn loop_cost(loops: &[(u64, u64)], head: u64) -> u32 { + if crate::gpu::dxil::kernel::loop_budget() == crate::gpu::dxil::kernel::RT_LOOP_BUDGET { + return 1; + } + let innermost = loops.iter().filter(|&&(a, b)| a <= head && head < b).map(|&(a, b)| b - a).min(); + innermost.map_or(1, |len| (len / LOOP_COST_BYTES).clamp(1, LOOP_COST_MOST as u64) as u32) +} + /// The guard of the loop headed at `head`. In a program with loop regions, each region starts /// with [`LOOP_BUDGETS_PER_REGION`] budgets, and `xcl_btotal` keeps all of them to /// [`LOOP_BUDGETS_IN_ALL`]: a title's own spin that gives up after 0x10000 tries, the budget, /// otherwise left every loop after it without an iteration (a retail FSR pass then published a /// flag made from a register its main loop never set, and the pass waiting on that flag spun /// 260 ms a frame). -fn loop_guard(regions: &[(u64, u64)], head: u64) -> String { - match budget_region(regions, head) { - Some(r) => format!( +/// An iteration spends [`loop_cost`] of them (of `loops`, the ranges the loops are emitted from). +fn loop_guard(regions: &[(u64, u64)], loops: &[(u64, u64)], head: u64) -> String { + match (budget_region(regions, head), loop_cost(loops, head)) { + (Some(r), 1) => format!( "if (xcl_bown != {r}u) {{ xcl_bown = {r}u; xcl_budget = {}u; }} if (xcl_budget == 0u || xcl_btotal == 0u) break; xcl_budget--; xcl_btotal--;", LOOP_BUDGETS_PER_REGION << 16 ), - None => LOOP_GUARD.to_string(), + (Some(r), k) => format!( + "if (xcl_bown != {r}u) {{ xcl_bown = {r}u; xcl_budget = {}u; }} if (xcl_budget < {k}u || xcl_btotal < {k}u) break; xcl_budget -= {k}u; xcl_btotal -= {k}u;", + LOOP_BUDGETS_PER_REGION << 16 + ), + (None, 1) => LOOP_GUARD.to_string(), + (None, k) => format!("if (xcl_budget < {k}u) break; xcl_budget -= {k}u;"), } } @@ -1279,7 +1307,7 @@ fn emit_structured( } let raised: BTreeSet = match it { Item::Loop { a, b, latch, entry } => { - body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {}\n", loop_guard(c.regions, a))); + body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {}\n", loop_guard(c.regions, c.loops, a))); let (lcont, lin) = if entry.is_none() { (cont.enter(Some(a)), &inner) } else { (cont.enter(None), &none) }; let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, &lcont, lin, d + 1, blocks, flags); for &t in &r { @@ -1400,7 +1428,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d let start = c.leaders[i]; let inner = c.loops.iter().filter(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)).max_by_key(|x| x.1).copied(); if let Some((a, b)) = inner { - body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {}\n", loop_guard(c.regions, a))); + body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {}\n", loop_guard(c.regions, c.loops, a))); emit_range(c, em, body, a, b, depth + 1, blocks, flags); body.push_str(&format!("{pad}}}\n")); i = c.leaders.partition_point(|&l| l < b); @@ -1846,7 +1874,13 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // (optimising one big dispatcher loop took minutes on large retail programs). let leaders: Vec = leaders.into_iter().filter(|l| starts.contains(l)).collect(); let loops = loop_ranges(&insts); - let regions = budget_regions(&loops); + // Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh + // stages on the single-budget CFG. + let regions = if matches!(opt.mode, Mode::Compute(_) | Mode::Kernel) { + budget_regions(&loops) + } else { + Vec::new() + }; let edges: Vec<(u64, u64)> = insts.iter().filter_map(|d| rdna2::branch_target(d).map(|t| (d.pc, t))).collect(); let phase_split = gs_jump.is_some_and(|t| t.is_some()) && opt.split_wave64 && opt.wave64; let ctx = Ctx { insts: &insts, starts: &starts, leaders: &leaders, loops: &loops, regions: ®ions, edges: &edges, phase_split, memo: Default::default() }; diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index eeba83a48c..e0d50f4fd3 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1495,6 +1495,95 @@ fn gpu_endless_loops_in_many_regions_stop_after_four_budgets() { assert_eq!(r.sgpr[0], super::LOOP_BUDGETS_IN_ALL << 16, "four budgets of iterations in all"); } +/// A loop of 80 instructions (320 B) that never ends: `s0 += 1`, 77 more adds, a compare that +/// holds until s0 wraps, the branch back. `after`: what follows the loop. +fn long_endless_loop(after: &[(&'static str, &'static str, &'static [(&'static str, u64)], Option)]) -> Vec { + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + for _ in 0..77 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 4), ("SSRC1", 129)], None)); + } + list.push(("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFB0)], None)); + list.extend_from_slice(after); + prog(&list) +} + +/// An iteration of a short loop spends 1 of the loop budget, one of a long loop more: a unit for +/// every `LOOP_COST_BYTES` of the innermost loop that holds the head, `LOOP_COST_MOST` at most. +/// A ray-tracing program's loops spend 1 of its small budget. +#[test] +fn a_long_loop_spends_more_of_the_budget_an_iteration() { + let u = super::LOOP_COST_BYTES; + let loops = [(0x100, 0x100 + 40 * u), (0x100 + 8 * u, 0x100 + 13 * u), (0x9000, 0x9010), (0x10000, 0x10000 + 1000 * u)]; + assert_eq!(super::loop_cost(&loops, 0x100), 40); + assert_eq!(super::loop_cost(&loops, 0x100 + 8 * u), 5, "the innermost loop that holds the head"); + assert_eq!(super::loop_cost(&loops, 0x9000), 1); + assert_eq!(super::loop_cost(&loops, 0x8000), 1, "no loop holds it"); + assert_eq!(super::loop_cost(&loops, 0x10000), super::LOOP_COST_MOST); + assert_eq!(super::loop_cost(&[(0, 2 * u - 4)], 0), 1, "under two units"); + crate::gpu::dxil::kernel::RT_ALL_MISS_FOR_TEST.with(|c| c.set(Some(true))); + let rt = crate::gpu::dxil::kernel::with_rt_program(true, || super::loop_cost(&loops, 0x100)); + crate::gpu::dxil::kernel::RT_ALL_MISS_FOR_TEST.with(|c| c.set(None)); + assert_eq!(rt, 1, "a ray-tracing program"); + + // the guards: a short loop's is the text it was, the 320 B loop's spends 2 an iteration + let short = prog(&[ + ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None), + ("S_CMP_LG_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 128)], None), + ("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None), + ]); + let t = translate(&short, &Options { mode: Mode::Kernel, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains(super::LOOP_GUARD), "{}", t.hlsl); + let t = translate(&long_endless_loop(&[]), &Options { mode: Mode::Kernel, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains("if (xcl_budget < 2u) break; xcl_budget -= 2u;") && !t.hlsl.contains(super::LOOP_GUARD), "{}", t.hlsl); +} + +/// A long loop that never ends stops after as many iterations as its cost leaves of the budget: +/// half of them for a loop of 320 B. +#[test] +fn gpu_an_endless_long_loop_stops_after_the_budget_by_its_cost() { + if !gpu_ready() { + return; + } + let t = translate(&long_endless_loop(&[]), &runner::options(Mode::Kernel)).unwrap(); + let dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap(); + let r = runner::run(&dxil, &KernelState::default(), &[]).unwrap(); + assert_eq!(r.sgpr[0], (1 << 16) / 2); +} + +/// Per-region loop budgets (`xcl_bown` / `xcl_btotal`) are compute-only: Compute and Kernel +/// modes emit them for multi-region loops, while Pixel and Mesh stages keep the single-budget +/// CFG (avoiding multi-PHI mesh loop headers that crash AMD LLPC). +#[test] +fn per_region_loop_budgets_are_compute_only() { + let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); + for _ in 0..2 { + list.push(("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 129)], None)); + list.push(("S_CMP_LT_U32", "ENC_SOPC", &[("SSRC0", 0), ("SSRC1", 130)], None)); + list.push(("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", 0xFFFD)], None)); + } + let code = prog(&list); + + let cs = super::CsInterface { threads: [64, 1, 1], ..Default::default() }; + let ps = super::PsInterface::default(); + let ms = super::MsInterface { threads: 64, max_vertices: 64, max_primitives: 64, ..Default::default() }; + + for mode in [Mode::Kernel, Mode::Compute(cs.clone())] { + let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); + assert!(t.hlsl.contains("xcl_bown") && t.hlsl.contains("xcl_btotal"), "compute/kernel should emit per-region budgets"); + } + for mode in [Mode::Pixel(ps), Mode::Mesh(ms.clone())] { + let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); + assert!(!t.hlsl.contains("xcl_bown") && !t.hlsl.contains("xcl_btotal"), "pixel/mesh must not emit per-region budgets"); + } + + // Direct DXIL compute & mesh both translate cleanly for a multi-region loop program. + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; + assert!(!crate::gpu::dxil::kernel::translate_compute(&code, o, &cs).unwrap().dxil.is_empty()); + assert!(!crate::gpu::dxil::kernel::translate_mesh(&code, o, &ms).unwrap().dxil.is_empty()); +} + #[test] fn gpu_divergence_through_exec() { if !gpu_ready() { From 81c04142cd0bef90e81cb062d6ba9aa454e734d4 Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:09 +0100 Subject: [PATCH 234/258] D3D12.X: gate big pipeline compiles on free commit Port #2868. Use the pipeline workers' free-commit measure so low free RAM alone does not stall big compiles. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- crates/xcl/src/hle/d3d12x/pso_async.rs | 2 +- crates/xcl/src/hle/d3d12x/real.rs | 23 ++++++++++++++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 8331166986..3bc4a6045c 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -498,7 +498,7 @@ fn mem_throttle_enabled() -> bool { /// not it: a retail title's world entry dropped it to 1.3 GB for a few seconds with 12 GB of /// commit free – the pages go to the page file – and the throttle on it held every pipeline /// worker idle while the title waited 14 s for a compute pipeline.) -fn avail_commit_bytes() -> Option { +pub(super) fn avail_commit_bytes() -> Option { use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; m.dwLength = std::mem::size_of::() as u32; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 79a0ded25b..1fb7729514 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5329,12 +5329,15 @@ fn big_compile_headroom(dxil_len: usize) -> u64 { (3u64 << 30).max(dxil_len as u64 * 512) } -/// That much physical RAM and commit is free (true when that is not known). +/// That much commit is free (true when that is not known). Free physical memory is not the +/// measure, as for the pipeline workers (`pso_async::avail_commit_bytes`): under Wine it is the +/// whole machine's, and at 1–2 GB it held every worker here while the title waited for one. fn big_compile_commit_free(need: u64) -> bool { - use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - unsafe { GlobalMemoryStatusEx(&mut m) == 0 || m.ullAvailPhys.min(m.ullAvailPageFile) >= need } + big_compile_room(super::pso_async::avail_commit_bytes(), need) +} + +fn big_compile_room(avail_commit: Option, need: u64) -> bool { + avail_commit.map_or(true, |avail| avail >= need) } #[cfg(test)] @@ -5343,6 +5346,16 @@ mod big_compile_tests { use std::sync::atomic::AtomicBool; use std::time::{Duration, Instant}; + #[test] + fn big_compile_room_is_free_commit_not_free_ram() { + let need = big_compile_headroom(0); + assert!(big_compile_room(Some(need), need)); + assert!(!big_compile_room(Some(need - 1), need)); + // a world load: 1.3 GB of RAM free, 12 GB of commit – the compile may start + assert!(big_compile_room(Some(12 << 30), need)); + assert!(big_compile_room(None, need)); + } + #[test] fn wanted_builds_bypass_commit_and_unwanted_slot_but_respect_hard_cap() { static S: Slots = Slots::fixed(1, 2); From 39440cd82f5365f92e332d2943e56d800a5a91ee Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:09 +0100 Subject: [PATCH 235/258] D3D12.X: give mapped pipeline library blobs a readable tail Port #2859. Keep a readable dword beyond the logical blob length for the driver. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- crates/xcl/src/hle/d3d12x/pso_library.rs | 42 ++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/pso_library.rs b/crates/xcl/src/hle/d3d12x/pso_library.rs index 74c900f56c..4ec4839596 100644 --- a/crates/xcl/src/hle/d3d12x/pso_library.rs +++ b/crates/xcl/src/hle/d3d12x/pso_library.rs @@ -48,6 +48,8 @@ pub struct MappedBlob { mapping: HANDLE, view: *const u8, len: usize, + /// The file's bytes with room after them, where it is not mapped (`open`). + copy: Vec, } // The view is strictly read-only and backed by immutable OS handles owned uniquely by `MappedBlob`. @@ -81,6 +83,17 @@ impl MappedBlob { CloseHandle(file); return None; }; + // AMD's driver reads a dword at the end of the blob in CreatePipelineLibrary + // (amdxc64.dll+0x176cd5). A view ends with its file's last page, so where the file + // ends less than 4 bytes before that, the read runs into the unmapped page after it. + // Such a file (4 lengths in 4096) is read into memory with room after it. + const PAGE: usize = 4096; + if (PAGE - len % PAGE) % PAGE < 4 { + CloseHandle(file); + let mut copy = std::fs::read(path).ok().filter(|c| c.len() == len)?; + copy.extend_from_slice(&[0; 4]); + return Some(Self { path: path.to_path_buf(), file: std::ptr::null_mut(), mapping: std::ptr::null_mut(), view: copy.as_ptr(), len, copy }); + } let mapping = CreateFileMappingW(file, std::ptr::null(), PAGE_READONLY, 0, 0, std::ptr::null()); if mapping.is_null() { CloseHandle(file); @@ -98,6 +111,7 @@ impl MappedBlob { mapping, view: view.Value as *const u8, len, + copy: Vec::new(), }) } } @@ -126,7 +140,7 @@ impl MappedBlob { impl Drop for MappedBlob { fn drop(&mut self) { unsafe { - if !self.view.is_null() { + if !self.view.is_null() && self.copy.is_empty() { UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { Value: self.view as *mut c_void }); } if !self.mapping.is_null() { @@ -476,8 +490,9 @@ impl MmapPipelineLibrary { match dev1.CreatePipelineLibrary::(blob.as_slice()) { Ok(lib) => { crate::xlog_info!( - "D3D12.X: opened memory-mapped pipeline library gen-{gen:08x} ({:.1} MiB file-backed)", - blob.len() as f64 / (1024.0 * 1024.0) + "D3D12.X: opened memory-mapped pipeline library gen-{gen:08x} ({:.1} MiB {})", + blob.len() as f64 / (1024.0 * 1024.0), + if blob.copy.is_empty() { "file-backed" } else { "read into memory: the file ends at a page boundary" } ); initial_read_handles.push(lib); backing = Some(Arc::new(blob)); @@ -752,6 +767,27 @@ mod tests { assert!(MappedBlob::open(&empty).is_none()); } + /// The driver reads a dword at the end of the blob: it is readable whatever the file's length, + /// also where the file ends with its last page or less than 4 bytes before. + #[test] + fn mapped_blob_has_a_readable_dword_after_its_end() { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; + let dir = TempDir::new("end"); + for len in [4096usize, 8190, 8191, 4093, 4092, 100] { + let path = dir.0.join(format!("{len}.plib")); + let payload: Vec = (0..len).map(|i| (i * 7) as u8 | 1).collect(); + std::fs::write(&path, &payload).unwrap(); + let blob = MappedBlob::open(&path).unwrap(); + assert_eq!(blob.as_slice(), payload.as_slice(), "{len}"); + let end = blob.as_ptr() as usize + len; + for p in [end, end + 3] { + let mut i: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + assert!(unsafe { VirtualQuery(p as *const c_void, &mut i, std::mem::size_of_val(&i)) } != 0 && i.State == MEM_COMMIT, "{len}"); + } + assert_eq!(unsafe { (end as *const u32).read_unaligned() }, 0, "{len}"); + } + } + #[test] fn mapped_blob_reads_and_keeps_file_open_across_generation_save() { let dir = TempDir::new("gen-save"); From 5a44e4ffd3b058ccfeb2fbf21b3edc03028c6ef1 Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:09 +0100 Subject: [PATCH 236/258] D3D12.X: retain timed-out sparse readbacks until completion Port #2842. Check the fence after each event wake-up and keep a timed-out staging job alive while the GPU can still write to it. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- crates/xcl/src/hle/d3d12x/sparse.rs | 176 ++++++++++++++++++++++++---- 1 file changed, 151 insertions(+), 25 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 406fe02368..823a6ffdb6 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -755,6 +755,28 @@ fn plan_ring_chunk(ring_write: u64, want: usize, cap: usize) -> (u64, usize) { // D3D12 objects are free-threaded; staging pointers and event handle are only used under STATE lock unsafe impl Send for State {} +/// Wait for `fence` to reach `target` using a reusable auto-reset `event`, bounded by `timeout`. +/// Resets `event` before arming and loops until `GetCompletedValue() >= target` or the deadline +/// expires, so a late completion from an earlier timed-out wait cannot satisfy a newer wait early. +/// (As in #1419 by gridoe and #2821 for `main`, same signature, so the two merge as one.) +unsafe fn wait_fence_until(fence: &ID3D12Fence, event: HANDLE, target: u64, timeout: std::time::Duration) -> bool { + if target == 0 || fence.GetCompletedValue() >= target { + return true; + } + let _ = windows::Win32::System::Threading::ResetEvent(event); + let _ = fence.SetEventOnCompletion(target, event); + let deadline = std::time::Instant::now() + timeout; + while fence.GetCompletedValue() < target { + let rem = deadline.saturating_duration_since(std::time::Instant::now()); + if rem.is_zero() { + return false; + } + let ms = rem.as_millis().clamp(1, u32::MAX as u128) as u32; + windows::Win32::System::Threading::WaitForSingleObject(event, ms); + } + true +} + static STATE: Mutex> = Mutex::new(None); /// The state's queue again, outside `STATE` (`queue`). `STATE` is held around D3D12 calls (an @@ -1228,9 +1250,7 @@ impl State { if target == 0 || self.fence.GetCompletedValue() >= target { return; } - let _ = self.fence.SetEventOnCompletion(target, self.event); - windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); - if self.fence.GetCompletedValue() < target { + if !wait_fence_until(&self.fence, self.event, target, std::time::Duration::from_secs(5)) { crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue()); super::real::stop_if_device_removed(); } @@ -1250,20 +1270,19 @@ impl State { super::flight::signaled("sparse readback", windows::core::Interface::as_raw(&self.rb_queue) as usize, &self.rb_done_fence, self.rb_done_value); } + /// Whether `rb_done_fence` reached `target` within 5 s: if not, the staging bytes are not the + /// readback yet and must not be copied out. #[inline] - unsafe fn wait_for_rb(&self, target: u64) { - if target == 0 || self.rb_done_fence.GetCompletedValue() >= target { - return; - } - let _ = self.rb_done_fence.SetEventOnCompletion(target, self.event); - windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); - if self.rb_done_fence.GetCompletedValue() < target { - crate::xlog_warn!( - "sparse: the readback queue has not reached fence value {target} after 5 s (at {})", - self.rb_done_fence.GetCompletedValue() - ); - super::real::stop_if_device_removed(); + unsafe fn wait_for_rb(&self, target: u64) -> bool { + if wait_fence_until(&self.rb_done_fence, self.event, target, std::time::Duration::from_secs(5)) { + return true; } + crate::xlog_warn!( + "sparse: the readback queue has not reached fence value {target} after 5 s (at {})", + self.rb_done_fence.GetCompletedValue() + ); + super::real::stop_if_device_removed(); + false } #[inline] @@ -1473,8 +1492,12 @@ impl State { } s.signal_rb(); s.rb_last_fence = s.rb_done_value; - s.wait_for_rb(s.rb_done_value); + let done = s.wait_for_rb(s.rb_done_value); s.reclaim_ring(); + if !done { + // the GPU copy has not run: nothing to copy back yet + pending.clear(); + } } for (dst, off, len, snap) in pending.iter() { let (dst, off, len) = (*dst, *off, *len); @@ -1852,9 +1875,45 @@ const MAX_RB_JOBS: usize = 16; const MIN_RB_JOB_BYTES: usize = 256 << 10; static FREE_RB_JOBS: Mutex> = Mutex::new(Vec::new()); +/// A job whose readback was still queued on the GPU when `readback_now` gave up waiting: its +/// buffer, allocator and list stay alive until `fence` reaches `value`. Dropped earlier, the copy +/// still runs later and writes into freed memory (under RADV: a GPU page fault, CPG write). +struct InFlightRbJob { + job: ReadbackJob, + fence: ID3D12Fence, + value: u64, +} + +// SAFETY: ID3D12Fence is a free-threaded COM object; `ReadbackJob` is `Send`. +unsafe impl Send for InFlightRbJob {} + +static IN_FLIGHT_RB_JOBS: Mutex> = Mutex::new(Vec::new()); + +/// Keep `job` until its GPU readback (`fence` >= `value`) is done. +fn keep_in_flight_readback_job(job: ReadbackJob, fence: ID3D12Fence, value: u64) { + IN_FLIGHT_RB_JOBS.lock().unwrap().push(InFlightRbJob { job, fence, value }); +} + +/// Jobs kept by `keep_in_flight_readback_job` whose readback has finished go back to the pool. +unsafe fn reclaim_in_flight_readback_jobs() { + let done: Vec = { + let mut v = IN_FLIGHT_RB_JOBS.lock().unwrap(); + if v.is_empty() { + return; + } + let (done, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut *v).into_iter().partition(|j| j.fence.GetCompletedValue() >= j.value); + *v = keep; + done.into_iter().map(|j| j.job).collect() + }; + for job in done { + return_readback_job(job); + } +} + unsafe fn take_readback_job(dev: &ID3D12Device, need: usize) -> Option { let dev_key = dev.as_raw() as usize; let want = need.max(MIN_RB_JOB_BYTES).min(READBACK_STAGING); + reclaim_in_flight_readback_jobs(); { let mut free = FREE_RB_JOBS.lock().unwrap(); if let Some(i) = free.iter().position(|j| j.dev_key == dev_key && j.cap >= want) { @@ -2048,7 +2107,6 @@ pub unsafe fn readback_now(va: usize, len: usize) { let mut idx = 0usize; let mut sub_off = 0usize; let mut pending: Vec<(usize, usize, usize)> = Vec::new(); - let mut job_idle = true; let mut waited_title_queues = false; while idx < spans.len() { let mut used = 0usize; @@ -2092,17 +2150,16 @@ pub unsafe fn readback_now(va: usize, len: usize) { (s.rb_done_fence.clone(), s.rb_done_value) }; if wait_target.1 > 0 && wait_target.0.GetCompletedValue() < wait_target.1 { - let _ = wait_target.0.SetEventOnCompletion(wait_target.1, job.event); - windows::Win32::System::Threading::WaitForSingleObject(job.event, 5000); - if wait_target.0.GetCompletedValue() < wait_target.1 { + if !wait_fence_until(&wait_target.0, job.event, wait_target.1, std::time::Duration::from_secs(5)) { crate::xlog_warn!( "sparse: readback_now queue has not reached fence value {} after 5 s (at {})", wait_target.1, wait_target.0.GetCompletedValue() ); super::real::stop_if_device_removed(); - job_idle = false; - break; + // the copy is still queued: keep its buffer alive until it has run + keep_in_flight_readback_job(job, wait_target.0.clone(), wait_target.1); + return; } } // 3. Copy only still-committed non-hole 64-byte chunks that were NOT modified by the CPU @@ -2115,9 +2172,7 @@ pub unsafe fn readback_now(va: usize, len: usize) { } s.reclaim_ring(); } - if job_idle { - return_readback_job(job); - } + return_readback_job(job); } /// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that @@ -3865,6 +3920,77 @@ mod tests { assert_eq!(early.into_iter().collect::>(), vec![(a, a + TILE), (a + 2 * TILE, a + 4 * TILE)]); } + /// A late completion from an earlier timed-out `SetEventOnCompletion` leaves the reusable + /// auto-reset event signalled (or fires it mid-wait). `wait_fence_until` must ignore both + /// and wait until the fence actually reaches `target`. (The test of #2821, for `main`.) + #[test] + fn wait_fence_until_ignores_stale_event_signal() { + use std::time::{Duration, Instant}; + use windows::Win32::System::Threading::{CreateEventW, SetEvent}; + unsafe { + let Some(dev) = test_device() else { return }; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + let event = CreateEventW(None, false, false, None).expect("event"); + // a stale signal already set, then an earlier completion (2) firing mid-wait for 5 + SetEvent(event).expect("stale SetEvent"); + fence.SetEventOnCompletion(2, event).expect("stale completion arm"); + let f2 = fence.clone(); + let t = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(30)); + let _ = f2.Signal(2); + std::thread::sleep(Duration::from_millis(50)); + let _ = f2.Signal(5); + }); + let start = Instant::now(); + let ok = wait_fence_until(&fence, event, 5, Duration::from_secs(2)); + let elapsed = start.elapsed(); + t.join().unwrap(); + let _ = CloseHandle(event); + assert!(ok, "wait_fence_until timed out instead of observing Signal(5)"); + assert!(fence.GetCompletedValue() >= 5, "returned early at {}", fence.GetCompletedValue()); + assert!(elapsed >= Duration::from_millis(50), "returned too early ({elapsed:?}) on a stale event signal"); + } + } + + /// A `readback_now` job that timed out with its copy still queued must not be handed out + /// (or freed) before that copy has run, then goes back to the pool. + #[test] + fn a_timed_out_readback_job_is_kept_until_its_copy_ran() { + unsafe { + let Some(dev) = test_device() else { return }; + let job = take_readback_job(&dev, 1).expect("readback job"); + let buf = job.buf.as_raw() as usize; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("fence"); + keep_in_flight_readback_job(job, fence.clone(), 1); + let other = take_readback_job(&dev, 1).expect("another job"); + assert_ne!(other.buf.as_raw() as usize, buf, "a job whose copy is queued was handed out again"); + assert!(IN_FLIGHT_RB_JOBS.lock().unwrap().iter().any(|j| j.job.buf.as_raw() as usize == buf), "the queued job was dropped"); + return_readback_job(other); + fence.Signal(1).expect("signal"); + reclaim_in_flight_readback_jobs(); + assert!(!IN_FLIGHT_RB_JOBS.lock().unwrap().iter().any(|j| j.job.buf.as_raw() as usize == buf), "the job stayed in flight after its copy"); + assert!(FREE_RB_JOBS.lock().unwrap().iter().any(|j| j.buf.as_raw() as usize == buf), "the job did not go back to the pool"); + } + } + + /// A D3D12 device for the tests above (hardware, else WARP), or `None` after a skip notice. + unsafe fn test_device() -> Option { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() { + return dev; + } + let warp = CreateDXGIFactory1::().ok().and_then(|f| f.EnumWarpAdapter::().ok()); + if let Some(warp) = warp { + if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() { + return dev; + } + } + crate::gpu::recomp::runner::skip_test("no GPU"); + None + } + /// Time for n 64 KiB pages committed one at a time and decommitted one at a time in /// reverse, before the device exists (`cargo test --release -p xcl --lib -- /// --ignored --exact hle::d3d12x::sparse::tests::early_commit_timing --nocapture`, From 84d63fd1aef3a707edb318831fb2115f10629d67 Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:09 +0100 Subject: [PATCH 237/258] D3D12.X: order sparse readbacks with a fence per title queue A shared fence could move backward as separate title queues completed out of order. Signal a separate fence on each source queue. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- crates/xcl/src/hle/d3d12x/sparse.rs | 40 +++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 823a6ffdb6..6d43cd490c 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1840,15 +1840,38 @@ pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usiz _ => merged.push((a, n)), } } - s.rb_value += 1; - let v = s.rb_value; - if queue.Signal(&s.rb_fence, v).is_ok() { - let _ = s.rb_queue.Wait(&s.rb_fence, v); - super::list_x::note_internal_wait(s.rb_queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); + if let Some((f, v)) = readback_after(&s.rb_queue, queue) { + super::list_x::note_internal_wait(s.rb_queue.as_raw() as usize, "sparse readback behind a title queue", &f, v); } s.readback_ranges(&merged); } +/// The sparse readback queue `rb_queue` waits until `q` has done what it was given so far, on a +/// fence of `q`'s own: (fence, value), None if `q` could not signal it. +/// +/// One fence for all the title's queues, each signalling the next value, went back down: a queue +/// signals 11 and is done, another one still busy signals 10 after it – and the readback queue's +/// wait for 11 never ended. A retail title's frames stopped behind it (every title queue idle, +/// the readback queue stuck with work pending until the device was removed). A queue runs its +/// work in order, so the values of its own fence only go up. +unsafe fn readback_after(rb_queue: &ID3D12CommandQueue, q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + static FENCES: Mutex>> = Mutex::new(None); + let key = q.as_raw() as usize; + let mut g = FENCES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if !m.contains_key(&key) { + let mut dev: Option = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + m.insert(key, (f, 0)); + } + let e = m.get_mut(&key)?; + e.1 += 1; + q.Signal(&e.0, e.1).ok()?; + let _ = rb_queue.Wait(&e.0, e.1); + Some((e.0.clone(), e.1)) +} + /// Pooled per-`Map` synchronous readback resources so concurrent `ID3D12Resource::Map` readbacks /// record, submit, and GPU-wait OUTSIDE the global `STATE` lock (avoiding `STATE` convoy stalls). struct ReadbackJob { @@ -2380,11 +2403,8 @@ impl State { continue; } seen.push(raw); - self.rb_value += 1; - let v = self.rb_value; - if q.Signal(&self.rb_fence, v).is_ok() { - let _ = self.rb_queue.Wait(&self.rb_fence, v); - super::list_x::note_internal_wait(rb_q, "sparse readback behind a title queue", &self.rb_fence, v); + if let Some((f, v)) = readback_after(&self.rb_queue, q) { + super::list_x::note_internal_wait(rb_q, "sparse readback behind a title queue", &f, v); } } } From fb6433519519f7cfb70165eba88425ffdefd4605 Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:09 +0100 Subject: [PATCH 238/258] D3D12.X: retire freed sparse tiles in 4 MiB pools Port #2630. Smaller pools let more video memory return when a title frees runs of tiles and keeps the tiles between them. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- crates/xcl/src/hle/d3d12x/sparse.rs | 55 ++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 6d43cd490c..b8de41208e 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -34,8 +34,11 @@ use windows_sys::Win32::System::Memory::{ pub mod gpu_view; const TILE: usize = 0x1_0000; -/// tiles of a video-memory pool heap (64 MiB) -const POOL_TILES: u32 = 1024; +/// tiles of a video-memory pool heap (4 MiB). A heap goes back only when every tile of it is +/// free (`State::retire_free_pools`), and a title frees its tiles in runs spread over all its +/// heaps: with heaps of 64 MiB a retail title's world load unmapped 1.5 GB of its 4.6 GB of +/// tiles and 3 of 78 heaps went back (0.2 GB); with heaps of 4 MiB 1.25 GB went back. +const POOL_TILES: u32 = 64; /// tiles decommitted while no title work was submitted that stay mapped (`State::parked`) before /// they are unmapped together: 256 MB of video memory const PARKED_MAX: usize = 4096; @@ -1012,7 +1015,7 @@ impl State { return Some((t, true)); } // a pool retired a moment ago (its last tile came free) is taken back before a new - // 64 MB heap is made: freeing and allocating a tile in turn made a new pool each time, + // heap is made: freeing and allocating a tile in turn made a new pool each time, // up to 18 GB of retired heaps in 2 s (#913). Its tiles are reused as freed tiles are // (zeroed), so this is no less safe than reusing a tile of a pool in use. if let Some((heap, _, _, _)) = self.retired.pop() { @@ -1052,7 +1055,7 @@ impl State { h } - /// Pools whose every tile is free again go (64 MB of video memory each – and as much of the + /// Pools whose every tile is free again go (their video memory – and as much of the /// system's commit: a retail game's homes of physical pages left 0.75 GB of pools for /// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled. fn retire_free_pools(&mut self) { @@ -1067,12 +1070,13 @@ impl State { for &(h, _) in &self.free { count[h as usize] += 1; } - let gone: Vec = (0..count.len()).filter(|&h| count[h] == POOL_TILES && self.pools[h].is_some()).collect(); - if gone.is_empty() { + // (a flag a pool: a title's world load frees hundreds of pools' worth of tiles at once) + let gone: Vec = (0..count.len()).map(|h| count[h] == POOL_TILES && self.pools[h].is_some()).collect(); + if !gone.contains(&true) { return; } - self.free.retain(|&(h, _)| !gone.contains(&(h as usize))); - for h in gone { + self.free.retain(|&(h, _)| !gone[h as usize]); + for h in (0..gone.len()).filter(|&h| gone[h]) { if let Some(heap) = self.pools[h].take() { self.retired.push((heap, self.value, self.rb_done_value, now)); } @@ -2969,7 +2973,7 @@ mod tests { /// Freeing the last tile in use of a pool and taking a tile again takes the retired pool - /// back, not a new 64 MB heap each time (#913: 288 pools, 18 GB asked of a 12 GB card). + /// back, not a new heap each time (#913: 288 pools of 64 MB, 18 GB asked of a 12 GB card). #[test] fn a_pool_retired_a_moment_ago_is_taken_back() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; @@ -3529,6 +3533,39 @@ mod tests { } } + /// A title frees its tiles in runs spread over all its pools: the pools of the freed runs go + /// back. With pools of 64 MiB none of these did (every pool kept the tiles still in use). + /// (From upstream PR #2630.) + #[test] + fn pools_of_freed_runs_go_back() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + // 192 MiB of tiles, taken in order as a title's first commits take them + const TILES: usize = 3072; + let tiles: Vec<(u32, u32)> = (0..TILES).map(|_| s.take_tile().expect("a tile").0).collect(); + let made = s.pools.iter().filter(|p| p.is_some()).count(); + assert_eq!(made * POOL_TILES as usize, TILES, "the tiles fill whole pools"); + // of every 64 MiB the title keeps the first 4 MiB and frees the rest + let (mut kept, mut freed) = (0, 0); + for (i, &t) in tiles.iter().enumerate() { + if i % 1024 < 64 { + kept += 1; + } else { + s.free.push(t); + freed += 1; + } + } + s.retire_free_pools(); + let left = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize; + assert_eq!(s.free.len() + s.retired.len() * POOL_TILES as usize, freed, "every freed tile is free or its pool retired"); + assert!(left <= kept * 2, "{left} tiles of video memory stay in pools for {kept} tiles in use ({} MiB for {} MiB)", left * TILE >> 20, kept * TILE >> 20); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + unsafe fn test_state_with_reserved(tiles: usize) -> (usize, State) { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; From 97d83b5b06caa79abc1f2e3c8b4dfa1805ec363b Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:09 +0100 Subject: [PATCH 239/258] Memory: commit sparse title pages on first CPU access Keep full read-write sparse pages GPU-only until the title touches them on the CPU. Preserve title-facing query and protection behavior for lazy pages. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- crates/xcl/src/hle/d3d12x/sparse.rs | 97 +++++++++++++++++++++++++++++ crates/xcl/src/hle/kernelx.rs | 44 ++++++++++--- crates/xcl/src/hle/kernelx/lazy.rs | 56 +++++++++++++++++ 3 files changed, 190 insertions(+), 7 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b8de41208e..89cd5b0fb6 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1723,6 +1723,101 @@ pub unsafe fn alloc(size: usize, align: usize) -> Option<(usize, usize)> { Some((addr, rounded)) } +/// `alloc` for the title's own memory: its CPU pages are committed when the CPU first touches +/// them (`commit_title`). +pub unsafe fn alloc_title(size: usize, align: usize) -> Option<(usize, usize)> { + let u = crate::gpu::uma::get()?; + let (addr, rounded) = u.sparse_alloc(size, align)?; + if commit_title(addr, rounded, PAGE_READWRITE).is_null() { + u.sparse_release(addr); + return None; + } + Some((addr, rounded)) +} + +/// The title commits `[a, a + n)` in a sparse window with the protection `protect`: as +/// `committed`, but the CPU's copy of a whole 64 KiB page is made when the CPU first touches it +/// (`kernelx::lazy`). Returns the address, or null as VirtualAlloc does. +/// +/// A title page in a sparse window was committed on the CPU as well as mapped to a tile of +/// video memory. A retail title's render targets, depth buffers and GPU-written buffers there +/// took system memory and commit the CPU never touched, and each write-watch look walked them +/// (2-4 GB of tiles, ~5 ms a look, ~90 looks a second). Such a page's tile is now video memory +/// only (all holes: the look leaves it out and no upload writes it) until the CPU's first +/// access commits the page (zeros, as a new commit holds); from then on its writes are watched +/// and uploaded as before. Pages at the ends that do not fill a 64 KiB page, pages already +/// committed, another protection than read-write, and commits before the device exists are +/// committed now, as before. +pub unsafe fn commit_title(a: usize, n: usize, protect: u32) -> *mut c_void { + let eager = |a: usize, n: usize| -> bool { + if n == 0 { + return true; + } + if VirtualAlloc(a as *const c_void, n, MEM_COMMIT, protect).is_null() { + return false; + } + committed(a, n); + true + }; + let (lo, hi) = ((a + TILE - 1) & !(TILE - 1), a.saturating_add(n) & !(TILE - 1)); + if protect != PAGE_READWRITE || hi <= lo || lock_state().is_none() { + return if eager(a, n) { a as *mut c_void } else { std::ptr::null_mut() }; + } + if !eager(a, lo - a) || !eager(hi, a + n - hi) { + return std::ptr::null_mut(); + } + // the pages committed already (the title commits a range again) stay as they are + let mut lazy: Vec<(usize, usize)> = Vec::new(); + let mut at = lo; + while at < hi { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 { + return std::ptr::null_mut(); + } + let end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi).max(at + PAGE); + if m.State == MEM_COMMIT { + committed(at, end - at); + } else { + // whole 64 KiB pages lazy; a part of one at either end now + let s = ((at + TILE - 1) & !(TILE - 1)).min(end); + let e = (end & !(TILE - 1)).max(s); + if !eager(at, s - at) { + return std::ptr::null_mut(); + } + if e > s { + lazy.push((s, e - s)); + } + if !eager(e, end - e) { + return std::ptr::null_mut(); + } + } + at = end; + } + { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return std::ptr::null_mut() }; + for &(p, len) in &lazy { + s.ensure_mapped(p, len, |_| 0xFFFF); + } + } + // (marked after their tiles are mapped: a first touch finds them, `drain_lazy_commits`) + for &(p, len) in &lazy { + for page in (p..p + len).step_by(TILE) { + crate::hle::kernelx::lazy::mark(page); + } + LAZY_BYTES.fetch_add(len as u64, Ordering::Relaxed); + } + a as *mut c_void +} + +/// Bytes of the title's commits in the sparse windows that `commit_title` left lazy so far +/// (some of them committed since by a first touch, some decommitted). +pub fn lazy_title_bytes() -> u64 { + LAZY_BYTES.load(Ordering::Relaxed) +} + +static LAZY_BYTES: AtomicU64 = AtomicU64::new(0); + /// Allocate a zeroed, write-watched block strictly inside sparse window `window` (e.g. /// window 0 for 32-bit-addressed descriptor heaps). Returns `(address, rounded_size)`. pub unsafe fn alloc_in(window: usize, size: usize, align: usize) -> Option<(usize, usize)> { @@ -2224,6 +2319,8 @@ pub unsafe fn decommitted(a: usize, n: usize) { if n == 0 { return; } + // (pages `commit_title` left lazy go with them) + crate::hle::kernelx::lazy::unmark_range(a, n); let mut g = lock_state(); let Some(s) = g.as_mut() else { let (start, end) = page_span(a, n); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index d34b4d22e6..803fa2a354 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -429,11 +429,27 @@ const MEM_64K_PAGES: u32 = 0x2040_0000; /// Commit `[a, a + n)` of a sparse window (the title's reservations there) and give it video /// memory (`d3d12x::sparse`). unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { - let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, sanitize_protect(p)); - if !q.is_null() { - crate::hle::d3d12x::sparse::committed(q as usize, n); + crate::hle::d3d12x::sparse::commit_title(a, n, sanitize_protect(p)) +} + +/// A lazy page (`lazy`: the title's memory, committed on the CPU's first touch) reads as the +/// committed read-write memory it is to the title. +unsafe fn lazy_as_committed(mbi: *mut mem::MEMORY_BASIC_INFORMATION) { + let m = &mut *mbi; + if m.State != mem::MEM_RESERVE { + return; + } + let base = m.BaseAddress as usize; + let page = base & !0xFFFF; + if !lazy::is_lazy(page) { + return; + } + let end = lazy::lazy_run_end(page).min(base.saturating_add(m.RegionSize)); + if end > base { + m.State = mem::MEM_COMMIT; + m.Protect = mem::PAGE_READWRITE; + m.RegionSize = end - base; } - q } pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { @@ -487,7 +503,7 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: crate::gpu::uma::GRAIN }; let rounded = size.max(1).div_ceil(align) * align; - if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc_title(rounded, align) { trace_mem("VirtualAlloc (graphics, sparse VRAM)", 0, rounded, t as u64, p, q); return q as *mut c_void; } @@ -733,6 +749,8 @@ pub unsafe extern "system" fn VirtualAllocEx(proc_: HANDLE, addr: *const c_void, } pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { + // (a lazy page is the title's committed memory: Windows protects committed pages only) + lazy::commit_range(addr as usize, size); mem::VirtualProtect(addr, size, sanitize_protect(p), old) } @@ -809,7 +827,7 @@ pub unsafe extern "system" fn XMemAllocDefault(size: usize, attrs: u64) -> *mut return std::ptr::null_mut(); }; // Graphics memory types live in the sparse VRAM pool (fallback to coherent UMA, then Windows). - if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc(rounded, align) { + if let Some((q, _)) = crate::hle::d3d12x::sparse::alloc_title(rounded, align) { trace_mem("XMemAlloc (graphics, sparse VRAM)", 0, rounded, attrs, 0, q); return q as *mut c_void; } @@ -945,7 +963,11 @@ pub unsafe extern "system" fn VirtualQuery(address: *const c_void, mbi: *mut mem if let Some(n) = query_committed_window(address, mbi, len) { return n; } - mem::VirtualQuery(address, mbi, len) + let n = mem::VirtualQuery(address, mbi, len); + if n != 0 && len >= std::mem::size_of::() { + lazy_as_committed(mbi); + } + n } pub unsafe extern "system" fn VirtualQueryEx(process: HANDLE, address: *const c_void, mbi: *mut mem::MEMORY_BASIC_INFORMATION, len: usize) -> usize { @@ -953,6 +975,11 @@ pub unsafe extern "system" fn VirtualQueryEx(process: HANDLE, address: *const c_ if let Some(n) = query_committed_window(address, mbi, len) { return n; } + let n = mem::VirtualQueryEx(process, address, mbi, len); + if n != 0 && len >= std::mem::size_of::() { + lazy_as_committed(mbi); + } + return n; } mem::VirtualQueryEx(process, address, mbi, len) } @@ -991,6 +1018,9 @@ pub unsafe extern "system" fn XMemVirtualQuery(process: HANDLE, address: *const if mem::VirtualQueryEx(process, address, mbi, std::mem::size_of::()) == 0 { return 0; } + if is_current_process(process) { + lazy_as_committed(mbi); + } const READABLE: u32 = mem::PAGE_READONLY | mem::PAGE_READWRITE | mem::PAGE_WRITECOPY diff --git a/crates/xcl/src/hle/kernelx/lazy.rs b/crates/xcl/src/hle/kernelx/lazy.rs index 2777415ac6..adbdd2edf8 100644 --- a/crates/xcl/src/hle/kernelx/lazy.rs +++ b/crates/xcl/src/hle/kernelx/lazy.rs @@ -97,6 +97,62 @@ pub(crate) fn unmark(page: usize) -> bool { LAZY.write().unwrap_or_else(|e| e.into_inner()).remove(&page) } +/// `[p, p + len)` is decommitted or released: its lazy pages are not lazy any more. One it +/// covers in part is committed first (the rest of it stays the title's memory). +pub(crate) fn unmark_range(p: usize, len: usize) { + if len == 0 { + return; + } + let end = p.saturating_add(len); + let (whole, part): (Vec, Vec) = { + let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); + if g.is_empty() { + return; + } + g.range(p & !(PAGE - 1)..end).copied().partition(|&x| x >= p && x.saturating_add(PAGE) <= end) + }; + if !whole.is_empty() { + let mut g = LAZY.write().unwrap_or_else(|e| e.into_inner()); + for x in whole { + g.remove(&x); + } + } + for x in part { + unsafe { commit(x) }; + } +} + +/// The lazy pages of `[p, p + len)` committed now (before a call that needs them committed, +/// as VirtualProtect does; no guard is opened). +pub(crate) fn commit_range(p: usize, len: usize) { + if len == 0 { + return; + } + let pages: Vec = { + let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); + if g.is_empty() { + return; + } + g.range(p & !(PAGE - 1)..p.saturating_add(len)).copied().collect() + }; + for page in pages { + unsafe { commit(page) }; + } +} + +/// Where the run of lazy pages from `page` (64 KiB aligned) ends (`page` itself: not lazy). +pub fn lazy_run_end(page: usize) -> usize { + let g = LAZY.read().unwrap_or_else(|e| e.into_inner()); + let mut end = page; + for &x in g.range(page..) { + if x != end { + break; + } + end += PAGE; + } + end +} + /// The lazy pages of `[p, p + len)` committed – memory a kernel call or XCL writes. Views of /// physical pages there are read-only until written and a kernel call cannot fault: they are /// opened, and stay open while the returned value lives (hold it across the write). From cb8d0b7bb550610de4d0ac7ccb433bcbf6969424 Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:10 +0100 Subject: [PATCH 240/258] D3D12.X: record pipelines involved in driver crashes Record the compute, graphics or mesh pipeline in the driver when compilation stops the process. Skip the recorded pipeline on later launches and retain the available shader diagnostics. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- README.md | 2 + crates/xcl/src/eh.rs | 3 + crates/xcl/src/hle/d3d12x/driver_crash.rs | 260 ++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 72 +++++- crates/xcl/src/shaders.rs | 10 + 6 files changed, 342 insertions(+), 6 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/driver_crash.rs diff --git a/README.md b/README.md index c35620ec20..5986602286 100644 --- a/README.md +++ b/README.md @@ -292,6 +292,8 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `XCL_PSO_TRACE=1` logs every driver compile. A huge compute program the driver refuses is logged with the driver's verdict (`the driver refused the compute PSO of record HASH … with 0x…`): its dispatches are skipped. +- XCL records pipeline keys associated with driver crashes in `driver-crashes.txt` beside the + DXIL cache. Later runs skip those pipelines. Delete the file to retry them. - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. For each, it names the translated diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index b093522e8d..cc844d570c 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -62,6 +62,9 @@ pub fn set_title_filter(f: usize) -> usize { } unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i32 { + // a crash inside the driver's compiler: the pipeline it was given is noted first, so the next + // run does not end at it too + crate::hle::d3d12x::driver_crash::on_crash(); crate::hle::d3d12x::real::log_device_removed(); if !info.is_null() && !(*info).ExceptionRecord.is_null() { let rec = &*(*info).ExceptionRecord; diff --git a/crates/xcl/src/hle/d3d12x/driver_crash.rs b/crates/xcl/src/hle/d3d12x/driver_crash.rs new file mode 100644 index 0000000000..dfc52d84ef --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/driver_crash.rs @@ -0,0 +1,260 @@ +//! The driver's shader compiler crashing on one pipeline: an access violation inside +//! `Create*PipelineState` ends the process, and the next run ends at the same pipeline (seen in +//! AMD's compiler on a 331 KiB mesh pipeline, every run, a minute into a retail world). +//! +//! The pipeline a thread hands to the driver is noted while the driver has it (`building`). The +//! unhandled-exception filter, on the thread that crashed, writes that pipeline's key to +//! `driver-crashes.txt` beside the DXIL cache and its shaders to the log folder (`on_crash`). A +//! later run does not hand a pipeline with a key of that file to the driver (`blocked`): it fails +//! as one the driver refused. The key is of the translated shaders and the state, so a translation +//! that changes makes a new key and is tried again; deleting the file tries them all again. +//! +//! A preparation worker (`shaders::in_workers`) has no such filter, and a fast-fail inside the +//! driver calls none anyway: it says which pipeline it builds in a file of its own beside the +//! list (`driver-building--.txt`), gone when the pipeline is built. One left by a +//! process that is gone names a pipeline the driver did not come back from: `blocked` moves it +//! into the list, so the worker started again for that part (`in_workers`) goes on after it. + +use std::cell::Cell; +use std::collections::HashSet; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +/// A pipeline in the driver: its key and its shaders (file name ending, address, bytes). +struct Building { + key: String, + shaders: Vec<(String, usize, usize)>, +} + +thread_local! { + /// the pipeline this thread's driver call is building (null: none) + static BUILDING: Cell<*const Building> = const { Cell::new(std::ptr::null()) }; +} + +/// Until dropped, this thread's driver call builds the pipeline it was made for. +pub(crate) struct Guard { + _now: Box, + before: *const Building, + /// a worker's file that names the pipeline while the driver has it + marker: Option, +} + +impl Drop for Guard { + fn drop(&mut self) { + let _ = BUILDING.try_with(|b| b.set(self.before)); + if let Some(m) = &self.marker { + let _ = std::fs::remove_file(m); + } + } +} + +/// This process is a preparation worker (`shaders::worker_command`). +fn worker() -> bool { + static W: std::sync::OnceLock = std::sync::OnceLock::new(); + *W.get_or_init(|| std::env::var_os("XCL_PRECOMPILE_PARENT").is_some()) +} + +fn marker_name(pid: u32, thread: u32) -> String { + format!("driver-building-{pid}-{thread}.txt") +} + +/// The driver call this thread makes next builds the pipeline `key` from `shaders` (each with the +/// ending of the file it is dumped to after a crash); they outlive the returned guard. +pub(crate) fn building(key: &str, shaders: &[(String, &[u8])]) -> Guard { + let now = Box::new(Building { key: key.to_string(), shaders: shaders.iter().map(|(n, c)| (n.clone(), c.as_ptr() as usize, c.len())).collect() }); + let before = BUILDING.with(|b| b.replace(&*now)); + let marker = worker().then(|| mark(&path(), key)).flatten(); + Guard { _now: now, before, marker } +} + +/// A file beside `list` that names `key` as in the driver for this thread of this process. +fn mark(list: &Path, key: &str) -> Option { + let dir = list.parent()?; + std::fs::create_dir_all(dir).ok()?; + let m = dir.join(marker_name(std::process::id(), unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() })); + std::fs::write(&m, key).ok()?; + Some(m) +} + +/// The process `pid` is gone (or cannot be asked about, which a live worker of this user can). +fn gone(pid: u32) -> bool { + use windows_sys::Win32::Foundation::CloseHandle; + use windows_sys::Win32::System::Threading::{OpenProcess, WaitForSingleObject, PROCESS_SYNCHRONIZE}; + unsafe { + let h = OpenProcess(PROCESS_SYNCHRONIZE, 0, pid); + if h.is_null() { + return true; + } + let ended = WaitForSingleObject(h, 0) == 0; + CloseHandle(h); + ended + } +} + +/// The markers beside `list` of processes that are gone (`is_gone`): their keys go into the list +/// and the markers are removed. The keys. +fn collect_markers(list: &Path, is_gone: impl Fn(u32) -> bool) -> Vec { + let Some(dir) = list.parent() else { return Vec::new() }; + let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut found = Vec::new(); + for e in entries.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + let Some(pid) = name.strip_prefix("driver-building-").and_then(|r| r.split('-').next()).and_then(|p| p.parse::().ok()) else { continue }; + if !is_gone(pid) { + continue; + } + if let Some(key) = std::fs::read_to_string(e.path()).ok().and_then(|t| t.split_whitespace().next().map(str::to_string)) { + if note(list, &key).is_ok() { + found.push(key); + } + } + let _ = std::fs::remove_file(e.path()); + } + found +} + +/// The key of the compute pipelines of a console program (`record`: the hash of its container), +/// whole or in pieces: what a preparation worker and the title both know it by. +pub(crate) fn compute_key(record: u64) -> String { + format!("cs-{record:016x}") +} + +/// The keys of the pipelines the driver crashed on, one a line. +fn path() -> PathBuf { + crate::gpu::recomp::dxc::cache_dir().join("driver-crashes.txt") +} + +fn keys(text: &str) -> HashSet { + text.lines().filter_map(|l| l.split_whitespace().next()).map(str::to_string).collect() +} + +fn note(list: &Path, key: &str) -> std::io::Result<()> { + if let Some(dir) = list.parent() { + std::fs::create_dir_all(dir)?; + } + let mut f = std::fs::OpenOptions::new().create(true).append(true).open(list)?; + writeln!(f, "{key}")?; + f.sync_all() +} + +static BLOCKED: Mutex>> = Mutex::new(None); + +/// The driver crashed building the pipeline `key` in an earlier run, or a process that is gone +/// was still building it: it is not built. +pub(crate) fn blocked(key: &str) -> bool { + let mut g = BLOCKED.lock().unwrap_or_else(|e| e.into_inner()); + // tests start with none, not with what the machine's runs left + g.get_or_insert_with(|| if cfg!(test) { HashSet::new() } else { load(&path()) }).contains(key) +} + +/// The keys of `list`, with those of the markers that processes now gone left beside it. +fn load(list: &Path) -> HashSet { + for key in collect_markers(list, gone) { + crate::xlog_warn!("D3D12.X: a process that ended was building pipeline {key} in the driver – noted in {} and not built again", list.display()); + } + std::fs::read_to_string(list).map(|t| keys(&t)).unwrap_or_default() +} + +#[cfg(test)] +pub(super) fn block(key: &str) { + BLOCKED.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashSet::new).insert(key.to_string()); +} + +/// The pipeline this thread's driver call was building, if any: its key goes to `list` and its +/// shaders to `dir`; what to log. +unsafe fn crashed(list: &Path, dir: Option<&Path>) -> Option { + let p = BUILDING.try_with(|b| b.replace(std::ptr::null())).ok()?; + let b = p.as_ref()?; + let noted = match note(list, &b.key) { + Ok(()) => format!("noted in {} and not built again", list.display()), + Err(e) => format!("not noted in {} ({e})", list.display()), + }; + let mut shaders = Vec::new(); + for (name, at, len) in &b.shaders { + if !crate::gpu::shader::readable(*at, *len) { + continue; + } + let code = std::slice::from_raw_parts(*at as *const u8, *len); + let file = format!("driver-crash-{}-{name}", b.key); + let written = dir.is_some_and(|d| std::fs::create_dir_all(d).and_then(|()| std::fs::write(d.join(&file), code)).is_ok()); + shaders.push(format!("{file} ({:016x}, {len} B{})", crate::gpu::shader::fnv64(code), if written { "" } else { ", not written" })); + } + let dir = dir.map_or_else(String::new, |d| format!(" in {}", d.display())); + Some(format!("the driver crashed building pipeline {}: {noted}; its shaders{dir}: {}", b.key, shaders.join(", "))) +} + +/// From the unhandled-exception filter, on the thread that crashed. +pub fn on_crash() { + // (a process without a title, a preparation worker: beside the list) + let dir = crate::state::boot().map_or_else(|| path().with_file_name("driver-crashes"), |b| b.logs_dir()); + if let Some(msg) = unsafe { crashed(&path(), Some(&dir)) } { + crate::xlog_error!("D3D12.X: {msg}"); + crate::log::flush(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_crash_notes_the_pipeline_being_built_and_dumps_its_shaders() { + let dir = std::env::temp_dir().join(format!("xcl-driver-crash-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let list = dir.join("cache").join("driver-crashes.txt"); + let logs = dir.join("logs"); + unsafe { + // no driver call on this thread: nothing to note + assert!(crashed(&list, Some(&logs)).is_none()); + assert!(!list.exists()); + + let (ms, ps) = (vec![1u8, 2, 3], vec![4u8; 5]); + let outer = building("s-outer-10", &[("ms.dxil".to_string(), &ms[..])]); + { + let _inner = building("s-inner-8", &[("ms.dxil".to_string(), &ms[..]), ("ps.dxil".to_string(), &ps[..])]); + let msg = crashed(&list, Some(&logs)).expect("the inner pipeline"); + assert!(msg.contains("s-inner-8") && msg.contains("driver-crash-s-inner-8-ps.dxil"), "{msg}"); + // once: the filter may run again for the same crash + assert!(crashed(&list, Some(&logs)).is_none()); + } + // the inner call returned: the outer pipeline is the one being built again + assert!(crashed(&list, Some(&logs)).expect("the outer pipeline").contains("s-outer-10")); + drop(outer); + assert!(crashed(&list, Some(&logs)).is_none()); + } + assert_eq!(std::fs::read(logs.join("driver-crash-s-inner-8-ms.dxil")).unwrap(), [1, 2, 3]); + assert_eq!(std::fs::read(logs.join("driver-crash-s-inner-8-ps.dxil")).unwrap(), [4; 5]); + let noted = keys(&std::fs::read_to_string(&list).unwrap()); + assert_eq!(noted, HashSet::from(["s-inner-8".to_string(), "s-outer-10".to_string()])); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A worker's marker names the pipeline while the driver has it and is gone after; one left + /// by a process that is gone puts its key into the list, one of a live process stays. + #[test] + fn a_marker_left_by_a_process_that_is_gone_blocks_its_pipeline() { + let dir = std::env::temp_dir().join(format!("xcl-driver-marker-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let list = dir.join("driver-crashes.txt"); + let m = mark(&list, "cs-00000000000000aa").expect("a marker"); + assert_eq!(std::fs::read_to_string(&m).unwrap(), "cs-00000000000000aa"); + // built: the guard removes it (as `Guard::drop` does) + std::fs::remove_file(&m).unwrap(); + assert!(collect_markers(&list, |_| true).is_empty()); + + std::fs::write(dir.join(marker_name(111, 1)), "cs-0000000000000001").unwrap(); + std::fs::write(dir.join(marker_name(222, 7)), "cs-0000000000000002").unwrap(); + assert_eq!(collect_markers(&list, |pid| pid == 111), ["cs-0000000000000001"]); + assert!(!dir.join(marker_name(111, 1)).exists() && dir.join(marker_name(222, 7)).exists()); + assert_eq!(keys(&std::fs::read_to_string(&list).unwrap()), HashSet::from(["cs-0000000000000001".to_string()])); + assert!(!gone(std::process::id()), "this process is not gone"); + assert_eq!(compute_key(0xab), "cs-00000000000000ab"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn keys_are_the_first_word_of_each_line() { + assert_eq!(keys("s-1-a\r\n\n s-2-b later text\n"), HashSet::from(["s-1-a".to_string(), "s-2-b".to_string()])); + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index bebf02e5bd..ccc7c443dc 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -20,6 +20,7 @@ pub mod device_x; pub mod dxgi_device; mod cpu_writes; pub mod dred; +pub mod driver_crash; mod fence_x; mod format_alias; pub mod frame; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 1fb7729514..ec5f43c167 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5862,6 +5862,14 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL crate::xlog_warn!("D3D12.X: compute PSO of record {record:016x} ({} B DXIL) not built: over XCL_PSO_MAX_KB{}", dxil.len(), if !has_isa_blob { " and without a saved blob" } else { " (it has a saved blob)" }); return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); } + // one the driver crashed on in an earlier run, here or in a preparation worker, is not + // given to it again (`driver_crash`): its dispatches are left out like a refused program's + let crash_key = super::driver_crash::compute_key(record); + if super::driver_crash::blocked(&crash_key) { + note_translation_error(format!("the driver crashed building the compute pipeline of record {record:016x} in an earlier run (driver-crashes.txt beside the DXIL cache) – not built")); + return (E_OUTOFMEMORY, std::time::Duration::ZERO, false); + } + let _building = super::driver_crash::building(&crash_key, &[("cs.dxil".to_string(), dxil)]); // in the background, a few at a time and within the commit headroom the program asks for let (mut hr, mut in_driver) = driver_compile_identified( "compute", @@ -6872,6 +6880,17 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const .map(std::sync::Arc::new); } let has_isa_blob = cached_blob_has_isa(cached.as_deref().map(Vec::as_slice)); + // a pipeline the driver crashed on in an earlier run, here or in a preparation worker, is not + // given to it again (`driver_crash`): its draws are left out like a refused pipeline's + let crash_key = format!("g-{:016x}-{:x}", gkey.0, gkey.1); + if super::driver_crash::blocked(&crash_key) { + note_translation_error(format!("the driver crashed building the graphics pipeline {crash_key} in an earlier run (driver-crashes.txt beside the DXIL cache) – not built")); + return Some(E_INVALIDARG); + } + let mut crash_shaders: Vec<(String, &[u8])> = vec![("vs.dxil".to_string(), &vs_dxil[..])]; + crash_shaders.extend(ps_dxil.as_deref().map(|p| ("ps.dxil".to_string(), &p[..]))); + crash_shaders.extend(rect_gs.as_deref().map(|g| ("gs.dxil".to_string(), g))); + let _building = super::driver_crash::building(&crash_key, &crash_shaders); let build = create_graphics_pso_cached( &mut copy, has_isa_blob.then(|| cached.as_deref().map(Vec::as_slice)).flatten(), @@ -7846,14 +7865,41 @@ fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option(stream: &'a [u8], console: &[(&str, Option<&'a [u8]>)]) -> Vec<(String, &'a [u8])> { + let mut shaders = vec![("stream.bin".to_string(), stream)]; + for (ty, payload) in stream_subobjects(stream).unwrap_or_default() { + if !SHADER_SUBOBJECTS.iter().any(|t| t.0 as u32 == ty) { + continue; + } + let stage = match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty as i32) { + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS => "ms".to_string(), + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS => "ps".to_string(), + _ => format!("stage{ty}"), + }; + if let Some(code) = payload_shader(payload) { + shaders.push((format!("{stage}.dxil"), code)); + } + } + shaders.extend(console.iter().filter_map(|(stage, code)| Some((format!("console-{stage}.bin"), (*code)?)))); + shaders +} + /// Create the mesh pipeline (`stream`, RS and shaders already in it) and the compute pass; -/// the title gets the mesh pipeline state. +/// the title gets the mesh pipeline state. `console`: the title's shaders it is made from (for +/// `driver_crash`). #[allow(clippy::too_many_arguments)] -unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, console: &[(&str, Option<&[u8]>)], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; let mesh_lib_key = pso_lib::stream_key(&stream.0, mesh_rs as usize, stream.shader_bytes()); + if super::driver_crash::blocked(&mesh_lib_key) { + note_translation_error(format!("the driver crashed building the mesh pipeline {mesh_lib_key} from the console {kind} in an earlier run (driver-crashes.txt beside the DXIL cache) – not built")); + return E_INVALIDARG; + } let cs_lib_key = pso_lib::compute_key(&tp.cs, &tp.samplers, 0); // Try loading both halves from the memory-mapped pipeline library before acquiring any cold // compile slot so warm runs bypass `big_compile_turn` and commit waits completely. @@ -7883,6 +7929,7 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let hr = if mesh_loaded { S_OK } else { + let _building = super::driver_crash::building(&mesh_lib_key, &crash_dump_shaders(&stream.0, console)); driver_compile(kind, stream.shader_bytes(), false, || finish_pso(this, fs, desc.as_ptr() as *const c_void, riid, ppv)) }; if hr < 0 || ppv.is_null() || (*ppv).is_null() { @@ -8219,7 +8266,7 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri out.raw(*ty, payload, palign == 8); } } - let hr = finish_two_pass(this, &out, tp, rs, "MS", riid, ppv); + let hr = finish_two_pass(this, &out, tp, rs, "MS", &[("ms", Some(ms)), ("ps", console_ps)], riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); super::ambient::note_graphics_pso(*ppv as usize, console_ps); @@ -8298,7 +8345,7 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE if d.Flags.0 != 0 { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); } - let hr = finish_two_pass(this, &out, tp, rs, "GS", riid, ppv); + let hr = finish_two_pass(this, &out, tp, rs, "GS", &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))], riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))]); super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); @@ -10819,12 +10866,16 @@ mod mesh_stream_tests { } } + /// calls of `fake_create_pso_null_ok` + static FAKE_PSO_CALLS: AtomicU64 = AtomicU64::new(0); + unsafe extern "system" fn fake_create_pso_null_ok( _: *mut c_void, _: *const c_void, _: *const GUID, ppv: *mut *mut c_void, ) -> HRESULT { + FAKE_PSO_CALLS.fetch_add(1, Ordering::SeqCst); if !ppv.is_null() { *ppv = std::ptr::null_mut(); } @@ -10895,13 +10946,22 @@ mod mesh_stream_tests { unsafe { // Case 1: driver returns S_OK but leaves *ppv == null let mut out: *mut c_void = std::ptr::null_mut(); - let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &iid, &mut out); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &[], &iid, &mut out); assert_eq!(hr, E_INVALIDARG); assert!(out.is_null()); // Case 2: caller passes ppv == null - let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &iid, std::ptr::null_mut()); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &[], &iid, std::ptr::null_mut()); + assert_eq!(hr, E_INVALIDARG); + + // Case 3: the driver crashed on this pipeline in an earlier run – it is not given to it + let calls = FAKE_PSO_CALLS.load(Ordering::SeqCst); + assert!(calls >= 2, "the driver was asked in cases 1 and 2"); + super::super::driver_crash::block(&pso_lib::stream_key(&stream.0, 0x1234_5678, stream.shader_bytes())); + let mut out: *mut c_void = std::ptr::null_mut(); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &[], &iid, &mut out); assert_eq!(hr, E_INVALIDARG); + assert_eq!(FAKE_PSO_CALLS.load(Ordering::SeqCst), calls, "a pipeline of driver-crashes.txt reached the driver"); } } } diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 6e6e5980b7..a0a0a524e2 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1604,6 +1604,16 @@ impl Pipelines { } } } + // a pipeline the driver did not come back from in an earlier run is not given to it again + // (`driver_crash`); this one is named there while the driver has it + let crash_key = crate::hle::d3d12x::driver_crash::compute_key(record); + if crate::hle::d3d12x::driver_crash::blocked(&crash_key) { + self.refused.fetch_add(1, Ordering::Relaxed); + eprintln!(" pipeline left out: the driver did not come back from record {record:016x} in an earlier run"); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; + } + let _building = crate::hle::d3d12x::driver_crash::building(&crash_key, &[("cs.dxil".to_string(), dxil)]); use crate::hle::d3d12x::real::driver_cache; let path = path_override.or_else(|| { #[cfg(test)] From bf7c82ee1b2685bb40417e09c4128177aa68d719 Mon Sep 17 00:00:00 2001 From: ivall Date: Thu, 26 Nov 2026 23:28:10 +0100 Subject: [PATCH 241/258] D3D12.X: report in-flight waits and GPU work at device loss Track active profiling spans, queue waits and submissions, and report the dispatch associated with a device removal. Assisted-by: Claude (exact model unknown), Codex (GPT-6 family, exact model unknown) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 2 + crates/xcl/src/hle/d3d12x/bind.rs | 6 ++ crates/xcl/src/hle/d3d12x/culprit.rs | 46 +++++++++++++++- crates/xcl/src/hle/d3d12x/flight.rs | 15 ++++- crates/xcl/src/hle/d3d12x/list_x.rs | 72 ++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/prof.rs | 73 +++++++++++++++++++++++-- crates/xcl/src/hle/d3d12x/real.rs | 7 ++- 7 files changed, 208 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index b4cc460d13..914562f9f3 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -311,6 +311,8 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { (f.clone(), *v) }; super::flight::signaled("title", key, &fence, value); + // (how many PC lists that value stands for: 0 is a signal alone) + super::flight::event("title lists", key as u64, value, lists.len() as u64); for &l in lists { if let Some(&b) = s.of_list.get(&(l as usize)) { let entry = s.backings.entry(b).or_default(); diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3c940724d0..dafb11a066 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3785,6 +3785,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } }; let mark = super::culprit::before_dispatch(list, raw_pso, pso, [0, 0, max]); + if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { + super::culprit::indirect_args(mark, p); + } match chained_indirect( this, list, @@ -3873,6 +3876,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us count(if gfx { DRAWS } else { DISPATCHES }); // an indirect dispatch: its groups are in the argument buffer (`max` of them) let mark = if gfx { 0 } else { super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [0, 0, max]) }; + if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { + super::culprit::indirect_args(mark, p); + } if guarded.is_some() && count_buf == 0 { pc(this, sig, max, args, args_off, count_buf, count_off); } else { diff --git a/crates/xcl/src/hle/d3d12x/culprit.rs b/crates/xcl/src/hle/d3d12x/culprit.rs index 41317a268d..a24cf9d8ad 100644 --- a/crates/xcl/src/hle/d3d12x/culprit.rs +++ b/crates/xcl/src/hle/d3d12x/culprit.rs @@ -129,6 +129,37 @@ pub unsafe fn before_dispatch(list: &ID3D12GraphicsCommandList, title_pso: usize id } +/// Where in title memory the arguments of the indirect dispatches numbered so are (the newest +/// 65 536): a hung one is logged with the group counts there. +static ARGS: Mutex>> = Mutex::new(None); + +/// The indirect dispatch `id` (of `before_dispatch`) takes its group counts from `at` in title +/// memory. +pub fn indirect_args(id: u32, at: usize) { + if id == 0 { + return; + } + let mut g = ARGS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if m.len() >= 1 << 16 { + m.clear(); + } + m.insert(id, at); +} + +/// ` ; its arguments in title memory now: x×y×z groups` for the dispatch `id`, when known. What +/// the GPU read can differ: these are the bytes the CPU sees (a count another dispatch wrote may +/// not be back yet). +fn args_now(id: u32) -> String { + let Some(at) = ARGS.lock().unwrap().as_ref().and_then(|m| m.get(&id).copied()) else { return String::new() }; + if !crate::gpu::shader::readable(at, 12) { + return format!("; its arguments at {at:#x} cannot be read"); + } + // SAFETY: 12 readable bytes, checked above + let [x, y, z] = unsafe { (at as *const [u32; 3]).read_unaligned() }; + format!("; its arguments in title memory ({at:#x}) now: {x}x{y}x{z} groups") +} + /// After the dispatch: a marker out with its number. pub unsafe fn after_dispatch(list: &ID3D12GraphicsCommandList, id: u32) { if id == 0 { @@ -194,6 +225,19 @@ pub fn on_watchdog_release() { if BURSTS.fetch_add(1, Ordering::Relaxed) >= 8 { return; } + report(); +} + +/// The device was removed: the same report, once. A driver that gives up on a hung GPU after +/// 2 s does so before the watchdog's 3 s without progress, and the report never came. +pub fn on_device_removed() { + static DONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if enabled() && !DONE.swap(true, Ordering::Relaxed) { + report(); + } +} + +fn report() { let g = MARKERS.lock().unwrap(); let Some(m) = g.as_ref() else { return }; // SAFETY: slots index the mapped buffer of SLOTS pairs @@ -203,7 +247,7 @@ pub fn on_watchdog_release() { let left = not_done(&m.what, *list, *i, *o); crate::xlog_warn!("GPU culprit: list {list:#x}: marker in #{i}, last marker out #{o}; {} of its dispatches not known done:", left.len()); for (id, s) in left.iter().take(24) { - crate::xlog_warn!("GPU culprit: #{id}: {s}"); + crate::xlog_warn!("GPU culprit: #{id}: {s}{}", args_now(*id)); } } } diff --git a/crates/xcl/src/hle/d3d12x/flight.rs b/crates/xcl/src/hle/d3d12x/flight.rs index 9422c54164..df7782eda0 100644 --- a/crates/xcl/src/hle/d3d12x/flight.rs +++ b/crates/xcl/src/hle/d3d12x/flight.rs @@ -175,6 +175,7 @@ fn poll() { } } } + let stopped = lines.iter().any(|(warn, _)| *warn); for (warn, l) in lines { if warn { crate::xlog_warn!("{l}"); @@ -182,6 +183,10 @@ fn poll() { crate::xlog_info!("{l}"); } } + // a queue stopped: what the queues wait for on the GPU, while the fences can still be asked + if stopped { + super::list_x::log_pending_waits("a queue stopped"); + } // A GPU that has not moved for 3 s: which dispatches started and did not finish (the markers // are CPU memory, read without the driver), and at 8 s where every thread is. Here and not // in the activity thread: in a retail title's hang its DXGI queries blocked in the driver, @@ -343,9 +348,13 @@ pub fn dump(why: &str) { } } if let Ok(g) = EVENTS.try_lock() { - let skip = g.len().saturating_sub(400); - crate::xlog_error!("flight: the last {} events (ms, thread, what, numbers):", g.len() - skip); - for e in g.iter().skip(skip) { + // the tile mappings, most of the ring in a world load, are left out but for the slow ones + // (1 ms and more): they pushed the submits before a stop out of the 400 lines + let shown = |e: &&Event| e.what != "tile map" || e.c >= 1000; + let n = g.iter().filter(shown).count(); + let skip = n.saturating_sub(400); + crate::xlog_error!("flight: the last {} events but quick tile mappings (ms, thread, what, numbers), {} ms of them:", n - skip, g.front().map_or(0, |e| now.saturating_sub(e.ms))); + for e in g.iter().filter(shown).skip(skip) { crate::xlog_error!("flight: {} t{} {} {:#x} {} {}", e.ms, e.thread, e.what, e.a, e.b, e.c); } } diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index b51a3c7108..7330c2e324 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -1590,6 +1590,8 @@ pub(super) fn note_internal_wait(queue: usize, what: &'static str, fence: &ID3D1 let mut g = INTERNAL_WAITS.lock().unwrap(); let waits = g.get_or_insert_with(HashMap::new).entry(queue).or_default(); waits.retain(|w| unsafe { w.fence.GetCompletedValue() } < w.value); + // (flight: the queue, the value waited for and the fence's value now) + super::flight::event(what, queue as u64, value, unsafe { fence.GetCompletedValue() }); waits.push(InternalWait { what, fence: fence.clone(), value, at: Instant::now() }); } @@ -1612,6 +1614,61 @@ fn internal_waits_summary() -> String { unmet.into_iter().map(|(q, s)| format!("q{}: {s}", queue_id(q))).collect::>().join(", ") } +/// What the queues wait for on the GPU now – the title's `Wait*BitValueX` not met yet, its +/// fences, XCL's own queue waits – into the log when a queue stops (`flight`): the watchdog says +/// the same after 5 s, and a driver that gives up on the GPU after 2 s removes the device first. +/// At most 8 times, 3 s apart. +pub(super) fn log_pending_waits(why: &str) { + static LAST: Mutex> = Mutex::new(None); + static TIMES: AtomicU64 = AtomicU64::new(0); + { + let mut l = LAST.lock().unwrap(); + if l.is_some_and(|t| t.elapsed() < Duration::from_secs(3)) { + return; + } + *l = Some(Instant::now()); + } + if !once(&TIMES, 8) { + return; + } + let mut armed = Vec::new(); + if let Some(graph) = SYNC_GRAPH.lock().unwrap().as_mut() { + for (&va, cell) in graph.cells.iter_mut() { + if cell.armed_waits.is_empty() { + continue; + } + let completed = unsafe { prune_completed_waits(cell) }; + if completed == u64::MAX { + continue; + } + let producer = cell.submitted_queue.or(cell.recorded_last_queue); + // the signals submitted for the address and not done: value, queue, its place there + let signals: Vec = cell.submitted_signals.iter().map(|s| format!("{:#x} on {:#x} at #{}", s.val, s.queue, s.seq)).collect(); + for aw in &cell.armed_waits { + armed.push(format!( + "{va:#x} >= {:#x} for {} ms (waiter {:#x}/ty{} at #{}{}, producer {:x?}/ty{:?}, recorded {:#x}, submitted {:#x}, completed {completed:#x}, CPU-signalled {:#x}, signals [{}])", + aw.val, + aw.armed_at.elapsed().as_millis(), + aw.waiting_queue, + aw.waiting_queue_ty, + aw.wait_seq, + if aw.after_write64 { ", after a Write64 of its list" } else { "" }, + producer, + cell.recorded_list_type.map(|t| t.0), + cell.recorded_max, + cell.submitted_max, + cell.cpu_signaled_max, + signals.join(", ") + )); + } + } + } + let ids = QUEUE_IDS.lock().unwrap().iter().enumerate().map(|(i, q)| format!("q{i} {q:#x}")).collect::>().join(", "); + crate::xlog_warn!("D3D12.X: GPU waits as {why}: the title's value waits unmet: {}", if armed.is_empty() { "none".to_string() } else { armed.join("; ") }); + crate::xlog_warn!("D3D12.X: GPU waits as {why}: pending title ID3D12Fences: {}", super::fence_x::pending_summary()); + crate::xlog_warn!("D3D12.X: GPU waits as {why}: XCL's own queue waits unmet: {} (queues: {ids})", internal_waits_summary()); +} + fn queue_id(q: usize) -> usize { let mut g = QUEUE_IDS.lock().unwrap(); if let Some(pos) = g.iter().position(|&x| x == q) { @@ -2197,6 +2254,8 @@ unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { .is_some_and(|c| c.non_monotonic || c.submitted_max >= val) }; if skip { + // (flight: the value was submitted before, or the address is not monotonic) + super::flight::event("w64 signal not sent", sig_q as u64, val, va); continue; } let Some(fence) = ensure_cell_fence(va, &dev, dev_raw) else { continue }; @@ -2258,6 +2317,17 @@ unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { } } }; + // (flight: the queue, the value and the address, in the order the queue gets them) + super::flight::event( + match action { + SignalAction::Skip => "w64 signal left out", + SignalAction::GpuSignal => "w64 signal", + SignalAction::CpuCycleBreak(_) => "w64 signal on the CPU (cycle)", + }, + sig_q as u64, + val, + va, + ); match action { SignalAction::Skip => {} SignalAction::GpuSignal => { @@ -2417,6 +2487,8 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, (pre_ok.0, pre_ok.1, pre_ok.2, wait_seq) }; + // (flight: the waiting queue, the value and the address the title waits on) + super::flight::event("title value wait", q_raw as u64, w.value, w.va); if let Err(e) = q.Wait(&fence, w.value) { let mut g = SYNC_GRAPH.lock().unwrap(); if let Some(cell) = g.as_mut().and_then(|gr| gr.cells.get_mut(&w.va)) { diff --git a/crates/xcl/src/hle/d3d12x/prof.rs b/crates/xcl/src/hle/d3d12x/prof.rs index 233241dd43..39d9dec4cb 100644 --- a/crates/xcl/src/hle/d3d12x/prof.rs +++ b/crates/xcl/src/hle/d3d12x/prof.rs @@ -4,7 +4,8 @@ //! tile mappings before a submission, or for the GPU. Each kind of wait is timed where it happens //! (`span`), summed over all the threads, so a frame rate near 0 shows what holds it: the line //! gives each kind's time in the 2 s (over 2 000 ms: several threads at once), its calls and the -//! longest one. +//! longest one. A wait counts when it ends; one that has not ended yet (a draw 36 s into waiting +//! for its pipeline) is given as still going, with its time so far. use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; @@ -71,19 +72,60 @@ pub fn add(kind: Kind, d: Duration) { LONGEST[k].fetch_max(ns, Ordering::Relaxed); } +/// spans of each kind not dropped yet, and the sum of their starts (`now_ns`, wrapping) +static OPEN: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; +static OPEN_STARTS: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; +/// spans still going are in the line once they took this long in all (a frame's own short +/// waits, caught open as the line is written, are not) +const OPEN_SHOWN_NS: u64 = 500_000_000; + +/// Nanoseconds since the first span. +fn now_ns() -> u64 { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_nanos().min(u64::MAX as u128) as u64 +} + /// Times from now to its drop as `kind`. -pub struct Span(Kind, Instant); +pub struct Span(Kind, u64); pub fn span(kind: Kind) -> Span { - Span(kind, Instant::now()) + let at = now_ns(); + let k = kind as usize; + OPEN_STARTS[k].fetch_add(at, Ordering::Relaxed); + OPEN[k].fetch_add(1, Ordering::Relaxed); + Span(kind, at) +} + +impl Span { + /// The time since it started. + pub fn elapsed(&self) -> Duration { + Duration::from_nanos(now_ns().saturating_sub(self.1)) + } } impl Drop for Span { fn drop(&mut self) { - add(self.0, self.1.elapsed()); + let k = self.0 as usize; + OPEN[k].fetch_sub(1, Ordering::Relaxed); + OPEN_STARTS[k].fetch_sub(self.1, Ordering::Relaxed); + add(self.0, self.elapsed()); } } +/// The spans of kind `k` still going: how many, and their time so far in all. The two counters +/// are read one after the other while other threads change them: a pair that cannot be (more +/// time than every span running since the first) is given as none. +fn still_going(k: usize) -> (u64, u64) { + let (n, starts, now) = (OPEN[k].load(Ordering::Relaxed), OPEN_STARTS[k].load(Ordering::Relaxed), now_ns()); + let ns = n.wrapping_mul(now).wrapping_sub(starts); + if n == 0 || n > 1 << 20 || ns > n.saturating_mul(now) { (0, 0) } else { (n, ns) } +} + +/// ` ; N still going, M ms so far` for a kind's part of the line (nothing below `OPEN_SHOWN_NS`). +fn still_going_note((n, ns): (u64, u64)) -> String { + if n == 0 || ns < OPEN_SHOWN_NS { String::new() } else { format!("; {n} still going, {} ms so far", ns / 1_000_000) } +} + /// Totals so far: (ns, calls) of each kind. #[derive(Clone, Copy)] pub struct Totals([(u64, u64); KINDS]); @@ -99,10 +141,11 @@ pub fn line(before: Totals, now: Totals, presents: u64, secs: f64) -> String { let ns = now.0[k].0.saturating_sub(before.0[k].0); let calls = now.0[k].1.saturating_sub(before.0[k].1); let longest = LONGEST[k].swap(0, Ordering::Relaxed); - if calls == 0 { + let going = still_going_note(still_going(k)); + if calls == 0 && going.is_empty() { continue; } - parts.push(format!("{} {} ms ({calls}, longest {} ms)", NAMES[k], ns / 1_000_000, longest / 1_000_000)); + parts.push(format!("{} {} ms ({calls}, longest {} ms{going})", NAMES[k], ns / 1_000_000, longest / 1_000_000)); } let frame = if presents > 0 { format!("{:.0} ms a frame", secs * 1000.0 / presents as f64) } else { "no frame".to_string() }; let (_, failed, queued) = super::pso_async::counts(); @@ -136,4 +179,22 @@ mod tests { assert!(l.contains("placements "), "{l}"); assert!(l.contains("frame-event waits "), "{l}"); } + + /// A span that has not ended is counted as still going with its time so far, and no longer + /// once it is dropped; the line names it only when it is long. + #[test] + fn a_span_not_ended_yet_is_still_going() { + let k = Kind::SubmitAfter as usize; + let s = span(Kind::SubmitAfter); + std::thread::sleep(Duration::from_millis(5)); + let (n, ns) = still_going(k); + assert!(n >= 1 && ns >= 5_000_000, "{n} spans, {ns} ns"); + assert!(s.elapsed() >= Duration::from_millis(5)); + let calls = CALLS[k].load(Ordering::Relaxed); + drop(s); + assert!(CALLS[k].load(Ordering::Relaxed) > calls, "a dropped span is a call"); + assert_eq!(still_going_note((1, 36_000_000_000)), "; 1 still going, 36000 ms so far"); + assert_eq!(still_going_note((2, OPEN_SHOWN_NS - 1)), ""); + assert_eq!(still_going_note((0, 0)), ""); + } } diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index ec5f43c167..7b0c396efd 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -5243,10 +5243,10 @@ fn driver_compile_identified(kind: &str, bytes: usize, gate: bool, record: Op }); crate::xlog_info!("D3D12.X: driver compile start #{sequence}: {kind} PSO, {bytes} B DXIL{record}"); } - let started = std::time::Instant::now(); + let prof = super::prof::span(super::prof::Kind::DriverCompile); let r = build(); - let took = started.elapsed(); - super::prof::add(super::prof::Kind::DriverCompile, took); + let took = prof.elapsed(); + drop(prof); if log { crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_bytes || gated, gated, waited)); } @@ -9813,6 +9813,7 @@ pub fn log_device_removed() { crate::xlog_error!("D3D12 device removed: {:#x} {}", e.code().0 as u32, e.message()); // which of XCL's queues stopped first, and what went before (`flight`) super::flight::dump("device removed"); + super::culprit::on_device_removed(); unsafe { let mut pf_logged = false; if let Ok(dred1) = dev.cast::() { From bfb40311710ab82b54c043a3e447830dcd63e112 Mon Sep 17 00:00:00 2001 From: Alp Pesen <5701011+AlpPesen@users.noreply.github.com> Date: Fri, 27 Nov 2026 05:44:45 +0300 Subject: [PATCH 242/258] Recompiler: keep compute shaders on single loop budget to avoid AMD LLPC crash Keep real compute shaders (Mode::Compute in recomp/mod.rs and compute in dxil/kernel.rs) on the single-budget loop counter instead of per-region multi-PHI budgets (VAR_BUDGET_OWNER / VAR_BUDGET_TOTAL), preventing amdxc64.dll+0xd2a411 null-deref crashes on RDNA2 (#2874) while preserving Mode::Kernel for unit tests. Verified live on RX 6800 (driver 32.0.21045.29003): 0 driver crashes past 279 s (previously crashed at ~157 s on cs-2e0055c25f49848a, cs-6e148dbd563de205, cs-62b584e061c05fc5). Assisted-by: Antigravity (Gemini 4 Neon) --- crates/xcl/src/gpu/dxil/kernel.rs | 6 +++--- crates/xcl/src/gpu/recomp/mod.rs | 6 +++--- crates/xcl/src/gpu/recomp/tests.rs | 16 +++++++--------- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index f7f2579ab0..03bdf7ac9a 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -429,10 +429,10 @@ fn translate_on_this_thread( None => super::compact::emit(&mut lw, &cfg, p, h0, exit)?, } } - // Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh - // stages on the single-budget CFG so AMD LLPC does not trip on multi-PHI mesh loop headers. + // Keep real compute/graphics/mesh plain-form CFGs on the single-budget counter so AMD LLPC + // (`amdxc64.dll+0xd2a411`, #2874) does not crash on multi-PHI per-region loop headers. let loops = crate::gpu::recomp::loop_ranges(&cfg.insts); - let regions = if compute || kernel { + let regions = if kernel { crate::gpu::recomp::budget_regions(&loops) } else { Vec::new() diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 6cdfe0835c..6eb3bc5597 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -1874,9 +1874,9 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // (optimising one big dispatcher loop took minutes on large retail programs). let leaders: Vec = leaders.into_iter().filter(|l| starts.contains(l)).collect(); let loops = loop_ranges(&insts); - // Per-region loop budgets target compute spin-wait passes (PR #2793); keep graphics/mesh - // stages on the single-budget CFG. - let regions = if matches!(opt.mode, Mode::Compute(_) | Mode::Kernel) { + // Keep real compute/graphics/mesh shaders on the single-budget CFG so AMD LLPC + // (`amdxc64.dll+0xd2a411`, #2874) does not crash on multi-PHI per-region loop headers. + let regions = if matches!(opt.mode, Mode::Kernel) { budget_regions(&loops) } else { Vec::new() diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index e0d50f4fd3..af86a7ade5 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -1552,9 +1552,9 @@ fn gpu_an_endless_long_loop_stops_after_the_budget_by_its_cost() { assert_eq!(r.sgpr[0], (1 << 16) / 2); } -/// Per-region loop budgets (`xcl_bown` / `xcl_btotal`) are compute-only: Compute and Kernel -/// modes emit them for multi-region loops, while Pixel and Mesh stages keep the single-budget -/// CFG (avoiding multi-PHI mesh loop headers that crash AMD LLPC). +/// Per-region loop budgets (`xcl_bown` / `xcl_btotal`) stay on `Mode::Kernel` while real +/// Compute, Pixel, and Mesh stages keep the single-budget CFG (avoiding multi-PHI loop headers +/// that crash AMD LLPC at `amdxc64.dll+0xd2a411`, #2874). #[test] fn per_region_loop_budgets_are_compute_only() { let mut list: Vec<(&str, &str, &[(&str, u64)], Option)> = Vec::new(); @@ -1569,13 +1569,11 @@ fn per_region_loop_budgets_are_compute_only() { let ps = super::PsInterface::default(); let ms = super::MsInterface { threads: 64, max_vertices: 64, max_primitives: 64, ..Default::default() }; - for mode in [Mode::Kernel, Mode::Compute(cs.clone())] { + let tk = translate(&code, &Options { mode: Mode::Kernel, ..Default::default() }).unwrap(); + assert!(tk.hlsl.contains("xcl_bown") && tk.hlsl.contains("xcl_btotal"), "kernel should emit per-region budgets"); + for mode in [Mode::Compute(cs.clone()), Mode::Pixel(ps), Mode::Mesh(ms.clone())] { let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); - assert!(t.hlsl.contains("xcl_bown") && t.hlsl.contains("xcl_btotal"), "compute/kernel should emit per-region budgets"); - } - for mode in [Mode::Pixel(ps), Mode::Mesh(ms.clone())] { - let t = translate(&code, &Options { mode, ..Default::default() }).unwrap(); - assert!(!t.hlsl.contains("xcl_bown") && !t.hlsl.contains("xcl_btotal"), "pixel/mesh must not emit per-region budgets"); + assert!(!t.hlsl.contains("xcl_bown") && !t.hlsl.contains("xcl_btotal"), "compute/pixel/mesh must not emit per-region budgets"); } // Direct DXIL compute & mesh both translate cleanly for a multi-region loop program. From 926433d80944c3aad9e7e44710acd0e4f497303b Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:17 +0100 Subject: [PATCH 243/258] Recompiler: use direct DXIL for translated compute by default Keep the previous explicit HLSL override and reuse the cache identity of explicit direct compute. Assisted-by: Codex (exact model identifier unavailable) --- README.md | 6 ++-- crates/xcl/src/gpu/recomp/pso.rs | 49 +++++++++++++++++++++++--------- 2 files changed, 39 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 5986602286..cca98fa410 100644 --- a/README.md +++ b/README.md @@ -212,8 +212,10 @@ next to `xcl.exe`, directly next to `xcl.exe`, in `%LOCALAPPDATA%\XCL\D3D12\`, o (NVIDIA) console wave64 compute, geometry and mesh programs run as two 32-lane halves that exchange masks and lane values ([`docs/wave64-on-wave32.md`](docs/wave64-on-wave32.md)) – slower than 64-lane waves, most for groups of several waves; wave64 vertex and pixel shaders that read lanes 32–63 - can still differ there. With `XCL_DIRECT_DXIL=1` and `XCL_PER_LANE=1`, compute groups - made up of complete native waves can use the per-lane form for branches on whole-wave masks. + can still differ there. Compute passes try direct DXIL first and fall back to HLSL. Use + `XCL_DIRECT_DXIL=0` to prefer HLSL, or `XCL_DIRECT_DXIL=all` to also try direct DXIL for vertex + and pixel shaders. With `XCL_PER_LANE=1`, direct DXIL compute groups made up of complete native + waves can use the per-lane form for branches on whole-wave masks. Test results on other GPUs: [#42](https://github.com/ivall/xcl/issues/42). ```powershell diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index eafcfe9540..61c3994621 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -234,7 +234,7 @@ mod translated { #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(super) enum Backend { Hlsl, - /// direct DXIL for compute + the mesh pass (`=1`) + /// direct DXIL for compute passes (default or `=1`) DirectCompute, /// direct DXIL for VS / PS too (`=all`) DirectAll, @@ -242,10 +242,15 @@ mod translated { impl Backend { pub(super) fn current() -> Self { - match (crate::gpu::dxil::kernel::enabled(), crate::gpu::dxil::kernel::enabled_graphics()) { - (_, true) => Backend::DirectAll, - (true, false) => Backend::DirectCompute, - _ => Backend::Hlsl, + Self::from_setting(std::env::var_os("XCL_DIRECT_DXIL").as_deref()) + } + + pub(super) fn from_setting(value: Option<&std::ffi::OsStr>) -> Self { + match value { + None => Self::DirectCompute, + Some(value) if value == "1" => Self::DirectCompute, + Some(value) if value == "all" => Self::DirectAll, + Some(_) => Self::Hlsl, } } } @@ -618,9 +623,10 @@ fn enormous(stage: Stage, hlsl_len: usize) -> bool { /// The program's DXIL, and whether it is an `enormous` one the direct translator made (its /// disk cache entry then follows that translator's version: `translated::cached`). fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(Compiled, bool), String> { - // `XCL_DIRECT_DXIL=1`: compute shaders through the direct DXIL translator, the HLSL path - // for what it cannot translate yet - if stage == Stage::Compute && crate::gpu::dxil::kernel::enabled() { + use translated::Backend; + let backend = Backend::current(); + // Compute shaders use direct DXIL by default and fall back to HLSL when needed. + if stage == Stage::Compute && backend != Backend::Hlsl { if dxc::defer() { return Err("DXIL not compiled yet".into()); } @@ -635,7 +641,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: // `XCL_DIRECT_DXIL=all`: vertex / pixel shaders too (not with the PS debug hooks below) let ps_debug = stage == Stage::Pixel && (debug_color(blob).is_some() || ["XCL_DEBUG_LOD0", "XCL_DEBUG_PS_SUB", "XCL_DEBUG_PS_EXPR"].iter().any(|v| std::env::var_os(v).is_some())); - if matches!(stage, Stage::Vertex | Stage::Pixel) && !ps_debug && crate::gpu::dxil::kernel::enabled_graphics() { + if matches!(stage, Stage::Vertex | Stage::Pixel) && !ps_debug && backend == Backend::DirectAll { if dxc::defer() { return Err("DXIL not compiled yet".into()); } @@ -648,7 +654,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: } } let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?; - if enormous(stage, t.hlsl.len()) && !crate::gpu::dxil::kernel::enabled() { + if enormous(stage, t.hlsl.len()) && backend == Backend::Hlsl { if dxc::defer() { return Err("DXIL not compiled yet".into()); } @@ -1163,8 +1169,8 @@ fn compile_console_mesh( windows: u32, split_wave64: bool, ) -> Result { - // `XCL_DIRECT_DXIL=1`: the compute pass through the direct DXIL translator (HLSL fallback) - if crate::gpu::dxil::kernel::enabled() { + // The mesh compute pass follows the runtime's direct DXIL preference. + if translated::Backend::current() != translated::Backend::Hlsl { if dxc::defer() { return Err("DXIL not compiled yet".into()); } @@ -1288,8 +1294,8 @@ pub fn graphics_wave32_for_device(device: &ID3D12Device) -> bool { pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { let (code, g) = super::geometry_program(vs, gs)?; let record = g.record(); - // `XCL_DIRECT_DXIL=1`: the compute pass through the direct DXIL translator (HLSL fallback) - if crate::gpu::dxil::kernel::enabled() { + // The geometry compute pass follows the runtime's direct DXIL preference. + if translated::Backend::current() != translated::Backend::Hlsl { let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: split_wave64, mem_windows: mem_windows(), sampler_base: 0 }; match crate::gpu::dxil::kernel::translate_geometry(&code, o, &g) { Ok(k) => { @@ -1844,6 +1850,21 @@ mod shader_cache_tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn direct_dxil_defaults_to_the_explicit_compute_backend() { + use std::ffi::OsStr; + use translated::{identity_with, Backend}; + + let default = Backend::from_setting(None); + let compute = Backend::from_setting(Some(OsStr::new("1"))); + assert_eq!(default, Backend::DirectCompute); + assert_eq!(default, compute); + assert_eq!(identity_with("s", "t", default, 1), identity_with("s", "t", compute, 1)); + assert_eq!(Backend::from_setting(Some(OsStr::new("0"))), Backend::Hlsl); + assert_eq!(Backend::from_setting(Some(OsStr::new("all"))), Backend::DirectAll); + assert_eq!(Backend::from_setting(Some(OsStr::new(""))), Backend::Hlsl); + } + /// Direct DXIL entries have their own identity per routing mode and translator version; /// the HLSL identity is the pre-direct one (its entries stay valid). #[test] From 0574950e811e9910d31dbe0cbea62997e0b68678 Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:17 +0100 Subject: [PATCH 244/258] Shaders: cap AMD pipeline preparation workers Reserve a D3D12 device slot for the parent process on AMD. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/gpu/adapter.rs | 16 ++++++++++++++++ crates/xcl/src/shaders.rs | 32 +++++++++++++++++++++++++++----- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/xcl/src/gpu/adapter.rs b/crates/xcl/src/gpu/adapter.rs index cd0b61fd85..730ef2a186 100644 --- a/crates/xcl/src/gpu/adapter.rs +++ b/crates/xcl/src/gpu/adapter.rs @@ -149,6 +149,22 @@ pub fn candidates(factory: &IDXGIFactory6, sel: &Selector) -> Vec<(IDXGIAdapter1 hw.into_iter().enumerate().filter(|(i, _)| keep[*i]).map(|(_, a)| a).collect() } +/// The PCI vendor of the adapter the device is made on: the first one `configured` +/// (`d3d12_adapter`) or `XCL_ADAPTER` allows, else the first hardware one, as the device's +/// creation picks it. `None` for `warp` or with no hardware adapter. +pub fn chosen_vendor(configured: &str) -> Option { + let sel = Selector::from_env_or(configured); + if sel == Selector::Warp { + return None; + } + let factory: IDXGIFactory6 = unsafe { CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)) }.ok()?; + let mut list = candidates(&factory, &sel); + if list.is_empty() { + list = candidates(&factory, &Selector::Auto); + } + list.first().map(|(_, desc)| desc.VendorId) +} + /// "`sel` matches no adapter (have: 0 = …, 1 = …)" – for logs and test skips. pub fn no_match(factory: &IDXGIFactory6, sel: &Selector) -> String { let have: Vec = hardware(factory).iter().enumerate().map(|(i, (_, d))| format!("{i} = {}", name(d))).collect(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index a0a0a524e2..18a8d025df 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -1127,7 +1127,7 @@ enum MeasureError { /// Compile one exact console compute shader through DXC, then time only the driver's /// `CreateComputePipelineState`. The implicit D3D and driver caches must both be disabled; /// refusing to do that is an error rather than a misleading warm-cache measurement. -/// This is the HLSL path the runtime uses by default (not `XCL_DIRECT_DXIL`). +/// The measurement always uses the HLSL path, independently of `XCL_DIRECT_DXIL`. fn measure_pso(input: &Input, hash: u64, repeat: usize, windows: u32, split: Option) -> i32 { match measure_pso_result(input, hash, repeat, windows, split) { Ok(()) => 0, @@ -1804,7 +1804,7 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R progress.total.store(inputs.iter().map(Input::len).sum(), Ordering::Relaxed); let mut windows = crate::gpu::uma::configured_runtime_windows() as u32; if windows > 1 && recomp::pso::heap_windows() { windows |= recomp::HEAP_WINDOWS; } - let workers = prepare_workers(); + let workers = prepare_workers(&progress.adapter); for input in &inputs { if progress.cancel.load(Ordering::Relaxed) { return Err("Shader preparation cancelled".into()); } // a pack: its stages here, its compute pipelines in worker processes (the driver builds @@ -1829,14 +1829,25 @@ pub(crate) fn prepare_for_launch(root: &Path, progress: &LaunchPreparation) -> R /// `XCL_PREPARE_WORKERS`: the processes that build a pack's compute pipelines before a title /// starts (1: in this process, as before). Unset: the logical processors less four, and no -/// more than 3 GB of the commit the system has left for each. -fn prepare_workers() -> usize { +/// more than 3 GB of the commit the system has left for each, and no more than the driver of +/// the adapter `adapter` chooses gives a device (`workers_with_devices`). +fn prepare_workers(adapter: &str) -> usize { if let Some(n) = std::env::var("XCL_PREPARE_WORKERS").ok().and_then(|v| v.parse::().ok()) { return n.clamp(1, 32); } let cores = std::thread::available_parallelism().map_or(4, |n| n.get()); let (used, limit) = crate::host::system_commit(); - workers_for(cores, limit.saturating_sub(used)) + workers_with_devices(workers_for(cores, limit.saturating_sub(used)), crate::gpu::adapter::chosen_vendor(adapter)) +} + +/// The processes an AMD driver gives a D3D12 device at one time (Adrenalin 26.11.2, RX 9070: +/// `D3D12CreateDevice` in a tenth process fails with 0x887A0005, the worker ends without having +/// built anything and the driver tells the user of an error). +const AMD_DEVICE_PROCESSES: usize = 9; + +/// The workers that get a device beside the title's own on an adapter of PCI vendor `vendor`. +fn workers_with_devices(workers: usize, vendor: Option) -> usize { + if vendor == Some(0x1002) { workers.min(AMD_DEVICE_PROCESSES - 1) } else { workers } } /// The workers for `cores` logical processors (threads, not cores) and `free_mb` of commit left. @@ -2800,6 +2811,17 @@ mod tests { assert_eq!(workers_for(32, 0), 1); } + /// An AMD driver gives nine processes a device at one time: the title and eight workers. + /// Other vendors' drivers keep the count the processors and the commit give. + #[test] + fn preparation_workers_on_amd_leave_the_title_its_device() { + assert_eq!(workers_with_devices(12, Some(0x1002)), 8); + assert_eq!(workers_with_devices(10, Some(0x1002)), 8); + assert_eq!(workers_with_devices(4, Some(0x1002)), 4); + assert_eq!(workers_with_devices(28, Some(0x10de)), 28); + assert_eq!(workers_with_devices(28, None), 28); + } + /// A builder's progress line gives its record count; its other lines give none. #[test] fn a_builders_progress_line_gives_its_count() { From 827b793142da92feb46bfeaf60774bfd2fe0f93f Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:17 +0100 Subject: [PATCH 245/258] D3D12.X: enable the ambient stand-in for forced RT misses Use the ambient stand-in when the raytracing gate forces misses. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/ambient.rs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/ambient.rs b/crates/xcl/src/hle/d3d12x/ambient.rs index 72e3ed6848..6430d3c375 100644 --- a/crates/xcl/src/hle/d3d12x/ambient.rs +++ b/crates/xcl/src/hle/d3d12x/ambient.rs @@ -6,7 +6,9 @@ //! retain unoccluded sky glare indoors. //! //! Controlled by `XCL_AMBIENT`: -//! * `auto` (default): active only while `XCL_RT_GATE` is holding back BVH traversal. +//! * `auto` (default): active while the title's rays find nothing: `XCL_RT_GATE` holds BVH +//! traversal back, or runs it with every ray missing (`miss`) – the probe resolve then gets as +//! little bounce light as when it is held, and the picture was as dark. //! * `sky` / `1` / `on`: always active. //! * `0` / `off` / `none`: disabled. //! @@ -123,10 +125,15 @@ pub fn active() -> bool { match config().mode { Mode::Off => false, Mode::Sky => true, - Mode::Auto => !real::bvh_traversal_allowed(), + Mode::Auto => rays_find_nothing(real::bvh_traversal_allowed(), crate::gpu::dxil::kernel::rt_all_miss()), } } +/// The title's rays bring no light: traversal is held back, or runs with every ray missing. +fn rays_find_nothing(traversal_allowed: bool, every_ray_misses: bool) -> bool { + !traversal_allowed || every_ray_misses +} + /// Role of a console shader identified from FSSM/container metadata. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum PassRole { @@ -1572,6 +1579,16 @@ pub(super) unsafe fn after_compute_dispatch( mod tests { use super::*; + /// The stand-in is for a picture without bounce light: with traversal held back, and as much + /// with traversal running while every ray misses; not with rays that hit. + #[test] + fn the_stand_in_is_on_whenever_the_rays_find_nothing() { + assert!(rays_find_nothing(false, false), "traversal held back"); + assert!(rays_find_nothing(true, true), "every ray misses"); + assert!(rays_find_nothing(false, true)); + assert!(!rays_find_nothing(true, false), "rays that hit bring the title's own light"); + } + #[test] fn mode_and_shader_classification_match_expected_passes() { assert_eq!(parse_mode(None), Mode::Auto); From e4de6bb75041e8ef6f23148b24d1770dd95d2510 Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:17 +0100 Subject: [PATCH 246/258] D3D12.X: start indirect argument scratch at 128 KiB Most recordings need only a few argument records. Grow to the regular block size when a slot fills. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/bind.rs | 49 ++++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index dafb11a066..3531afa641 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -289,6 +289,24 @@ fn inline_guard_batch_on() -> bool { /// A recording's blocks of rewritten indirect arguments, and most bytes of them (past it, its /// two-pass ExecuteIndirects are skipped) const SCRATCH_BLOCK: u64 = 1 << 20; +/// The first block of a recording's slot: 512 arguments of 256 bytes. A retail title's world has +/// some 130 recordings a frame alive for several frames, most with a few indirect calls: at +/// `SCRATCH_BLOCK` each, 493 blocks were made in 15 s and stayed alive (493 MiB of video memory, +/// and as much commit). A slot that fills its first block goes on in `SCRATCH_BLOCK`s. +const SCRATCH_FIRST_BLOCK: u64 = 128 << 10; + +/// The bytes of the block a slot takes for `bytes` of arguments: its first one small, the ones +/// after it `SCRATCH_BLOCK`, and never less than what is asked. +fn scratch_block_bytes(bytes: u64, first: bool) -> u64 { + bytes.max(if first { SCRATCH_FIRST_BLOCK } else { SCRATCH_BLOCK }) +} + +/// The free block (`FREE_RES`: buffer, bytes, device) to take for `size` bytes with `remaining` +/// left of the recording's cap: the smallest that holds them, so a small first block does not +/// take a record buffer of megabytes that the next two-pass draw then makes anew. +fn pick_free_block(free: &[(u64, usize)], dev: usize, size: u64, remaining: u64) -> Option { + free.iter().enumerate().filter(|(_, (cap, d))| *d == dev && *cap >= size && *cap <= remaining).min_by_key(|(_, (cap, _))| *cap).map(|(i, _)| i) +} /// Default per-recording cap on rewritten indirect-argument scratch (MiB). Overridable via /// `XCL_INDIRECT_SCRATCH_MB` (clamped 4..=128 MiB) so dense open-world indirect draw lists do /// not exhaust scratch mid-recording and drop trailing draws. @@ -2401,7 +2419,7 @@ unsafe fn alloc_prelude_scratch(this: *mut c_void, dev: &ID3D12Device, bytes: u6 }) { return Ok(r); } - let size = bytes.max(SCRATCH_BLOCK); + let size = scratch_block_bytes(bytes, with(this, |s| s.prelude_scratch.buf.is_none())); let cap = scratch_cap(); let remaining = cap.saturating_sub(with(this, |s| s.scratch_taken)); if size > remaining { @@ -2410,7 +2428,8 @@ unsafe fn alloc_prelude_scratch(this: *mut c_void, dev: &ID3D12Device, bytes: u6 let dev_key = dev.as_raw() as usize; let picked = { let mut free = FREE_RES.lock().unwrap(); - free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= size && *cap <= remaining).map(|i| free.swap_remove(i)) + let shapes: Vec<(u64, usize)> = free.iter().map(|(_, cap, d)| (*cap, *d)).collect(); + pick_free_block(&shapes, dev_key, size, remaining).map(|i| free.swap_remove(i)) }; let block = match picked { Some(e) => e, @@ -3282,7 +3301,7 @@ unsafe fn scratch_args_in(this: *mut c_void, dev: &ID3D12Device, bytes: u64, slo }) { return Ok(r); } - let size = bytes.max(SCRATCH_BLOCK); + let size = scratch_block_bytes(bytes, with(this, |s| s.scratch[slot].buf.is_none())); let cap = scratch_cap(); let remaining = cap.saturating_sub(with(this, |s| s.scratch_taken)); if size > remaining { @@ -3291,7 +3310,8 @@ unsafe fn scratch_args_in(this: *mut c_void, dev: &ID3D12Device, bytes: u64, slo let dev_key = dev.as_raw() as usize; let picked = { let mut free = FREE_RES.lock().unwrap(); - free.iter().position(|(_, cap, d)| *d == dev_key && *cap >= size && *cap <= remaining).map(|i| free.swap_remove(i)) + let shapes: Vec<(u64, usize)> = free.iter().map(|(_, cap, d)| (*cap, *d)).collect(); + pick_free_block(&shapes, dev_key, size, remaining).map(|i| free.swap_remove(i)) }; let block = match picked { Some(e) => e, @@ -4980,6 +5000,27 @@ mod tests { assert_eq!(two_pass_list_mb(Some("1000")), 128); } + /// A slot's first block of rewritten arguments is small, the ones after it are + /// `SCRATCH_BLOCK`, a request larger than either gets its own size; and a free block is + /// taken smallest first, of the same device, within what the recording may still take. + #[test] + fn a_recordings_first_argument_block_is_small_and_free_blocks_go_smallest_first() { + assert_eq!(scratch_block_bytes(256, true), SCRATCH_FIRST_BLOCK); + assert_eq!(scratch_block_bytes(256, false), SCRATCH_BLOCK); + assert_eq!(scratch_block_bytes(SCRATCH_FIRST_BLOCK + 256, true), SCRATCH_FIRST_BLOCK + 256); + assert_eq!(scratch_block_bytes(4 << 20, true), 4 << 20); + assert_eq!(scratch_block_bytes(4 << 20, false), 4 << 20); + assert!(SCRATCH_FIRST_BLOCK < SCRATCH_BLOCK && SCRATCH_FIRST_BLOCK % 256 == 0); + // (bytes, device): a 32 MiB record buffer, two blocks, one of another device + let free = [(32u64 << 20, 7usize), (1 << 20, 7), (128 << 10, 7), (128 << 10, 9)]; + assert_eq!(pick_free_block(&free, 7, 128 << 10, 32 << 20), Some(2)); + assert_eq!(pick_free_block(&free, 7, 512 << 10, 32 << 20), Some(1)); + assert_eq!(pick_free_block(&free, 7, 2 << 20, 32 << 20), Some(0)); + // the record buffer is past what the recording may still take + assert_eq!(pick_free_block(&free, 7, 2 << 20, 16 << 20), None); + assert_eq!(pick_free_block(&free, 8, 256, 32 << 20), None); + } + #[test] fn inline_guard_batch_defaults_off_and_opts_in() { assert!(!parse_inline_guard_batch(None)); From afe7f47ed8610f7de3069b27ae47ab49d591abf2 Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:17 +0100 Subject: [PATCH 247/258] D3D12.X: trim idle scratch buffers under commit pressure Release recyclable scratch for the device when the system is short on commit. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/bind.rs | 40 ++++++++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/present.rs | 11 +++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3531afa641..aa643ab9b6 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -465,6 +465,14 @@ fn recycle_into_pool(free: &Mutex>, items: Vec, mut keep: impl FnMu drop(overflow); } +/// Give back scratch that completed recordings returned to the reuse pools. Drop COM objects +/// outside the locks because their release hooks can re-enter `release_allocator_res`. +pub(super) fn trim_free_scratch(dev_key: usize) { + let buffers: Vec<_> = FREE_RES.lock().unwrap().extract_if(.., |(_, _, dev)| *dev == dev_key).collect(); + let io: Vec<_> = FREE_IO.lock().unwrap().extract_if(.., |block| block.dev_key == dev_key).collect(); + drop((buffers, io)); +} + pub(super) fn release_allocator_res(allocator: usize) { // Bind each removed entry before locking the free pool (avoiding nested `ALLOC_* -> FREE_*` // lock holding from `if let` temporary lifetimes) and drop overflow COM objects outside both @@ -7038,6 +7046,38 @@ void ms(uint3 g : SV_GroupID) { o.Store((v * 16u + g.x) * 4u, rec.Load(g.x * 4u) assert_eq!(rejected, vec![true, false, true, false]); } + #[test] + fn trimming_free_scratch_releases_only_the_requested_devices_idle_buffers() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + + unsafe { + let mut dev: Option = None; + let _ = D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev); + let Some(dev) = dev else { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return; + }; + let buffer = default_uav_buffer(&dev, IO_BLOCK_BYTES, "test scratch").unwrap(); + let (trimmed, other, allocator) = (0x7500_1030, 0x7500_1031, 0x7500_1032); + FREE_RES.lock().unwrap().extend([ + (buffer.clone(), IO_BLOCK_BYTES, trimmed), + (buffer.clone(), IO_BLOCK_BYTES, other), + ]); + ALLOC_RES.lock().unwrap().get_or_insert_with(HashMap::new).insert(allocator, vec![(buffer, IO_BLOCK_BYTES, trimmed)]); + + trim_free_scratch(trimmed); + { + let free = FREE_RES.lock().unwrap(); + assert!(!free.iter().any(|entry| entry.2 == trimmed)); + assert!(free.iter().any(|entry| entry.2 == other)); + } + assert!(ALLOC_RES.lock().unwrap().as_ref().unwrap().contains_key(&allocator)); + release_allocator_res(allocator); + trim_free_scratch(trimmed); + trim_free_scratch(other); + } + } + #[test] fn recycle_into_pool_drops_overflow_outside_pool_lock() { struct ReentrantDrop { diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index 51c6f5949c..b4b7427a37 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -131,7 +131,16 @@ unsafe fn present_x_frame(queue: *mut c_void, plane_count: u32, planes: *const u } super::real::stop_if_device_removed(); super::alloc_pool::release_finished(); - crate::gpu::texture::trim_idle_staging(frames, super::vram::commit_low()); + let low_commit = super::vram::commit_low(); + crate::gpu::texture::trim_idle_staging(frames, low_commit); + if let Some(queue) = ID3D12CommandQueue::from_raw_borrowed(&queue).filter(|_| low_commit) { + let mut dev: Option = None; + if queue.GetDevice(&mut dev).is_ok() { + if let Some(dev) = dev { + super::bind::trim_free_scratch(dev.as_raw() as usize); + } + } + } if !PRESENTX.swap(true, Ordering::Relaxed) { crate::xlog_info!("D3D12.X: PresentX – the title presents its own frames ({plane_count} plane(s))"); } From 1abb912b915d402bddad79f677fcc61056d04e93 Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:17 +0100 Subject: [PATCH 248/258] Tests: order indirect argument aliases and default to WARP Use an explicit aliasing barrier for the overlapping placed resources. Keep native-driver execution available by adapter selection. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/bind.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index aa643ab9b6..f0778abe09 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -5072,10 +5072,9 @@ mod tests { } /// A dispatch writes an ExecuteIndirect's group count through another buffer over the same - /// memory (as translated shaders write through the memory windows), a UAV barrier (what a - /// console barrier becomes), then the ExecuteIndirect: it runs the count just written, not - /// the one the memory held before the list (`fresh_indirect_arguments`; without it an RTX - /// 5090 ran the old count in nearly every try). + /// memory (as translated shaders write through the memory windows), then the ExecuteIndirect + /// runs the count just written. The test orders the placed aliases explicitly so the driver + /// sees valid D3D12 accesses before `fresh_indirect_arguments` runs. #[test] fn execute_indirect_reads_the_arguments_written_before_it() { use crate::gpu::{fence, recomp::runner::skip_test}; @@ -5105,7 +5104,8 @@ void main(uint t : SV_GroupIndex) { unsafe { let setup = || -> Result<(ID3D12Device, String), String> { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI factory unavailable: {e}"))?; - let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + // The driver-specific probe runs on hardware only when selected explicitly. + let sel = crate::gpu::adapter::Selector::from_env_or("warp"); let (adapter, name): (IDXGIAdapter1, String) = if sel == crate::gpu::adapter::Selector::Warp { (factory.EnumWarpAdapter().map_err(|e| format!("WARP unavailable: {e}"))?, "WARP (software renderer)".into()) } else { @@ -5173,6 +5173,13 @@ void main(uint t : SV_GroupIndex) { Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: ManuallyDrop::new(None) }) }, }; + // D3D12 requires an aliasing barrier for the switch from `written` to `args` + // inside one ExecuteCommandLists call, even for buffers that inherit bytes. + let alias_barrier = D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Aliasing: ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER::default()) }, + }; let run = |list: &ID3D12GraphicsCommandList, close: &dyn Fn()| { close(); queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); @@ -5199,7 +5206,7 @@ void main(uint t : SV_GroupIndex) { alloc.Reset().unwrap(); *count = 0; let list = record(new); - list.ResourceBarrier(&[uav_barrier.clone()]); + list.ResourceBarrier(&[uav_barrier.clone(), alias_barrier.clone()]); list.SetComputeRoot32BitConstants(0, 2, [1u32, 0].as_ptr() as _, 0); // from here as XCL records a title's ExecuteIndirect: on the adopted list let raw = list.as_raw(); From 6937a9665ebf9074709c8c459faa296e814a3c62 Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:18 +0100 Subject: [PATCH 249/258] D3D12.X: intern pipeline shader blobs by contents Share identical shader bytes from different title addresses and check byte equality before reusing a hash match. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/real.rs | 108 ++++++++++++++++++++---------- 1 file changed, 73 insertions(+), 35 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 7b0c396efd..65801c0e21 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -7021,39 +7021,47 @@ enum OwnedDesc { /// A pipeline's copy of one of its console shaders, shared with every pipeline that copied the /// same bytes (`intern_blob`). -type Blob = std::sync::Arc<[u8]>; +struct Blob { + bytes: std::sync::Arc<[u8]>, + hash: u64, +} -/// The copies kept: (title address, length) → the copy, while a pipeline holds it. -static BLOBS: Mutex>, usize)>> = Mutex::new(None); +/// The copies kept by hash and length while a pipeline holds them. Collisions share a bucket. +type BlobBuckets = HashMap<(u64, usize), Vec>>; +static BLOBS: Mutex> = Mutex::new(None); -/// The copy of the shader `bytes` a pipeline keeps until it is built: the one an earlier -/// pipeline made of the same bytes at the same address, or a new one. A retail title makes -/// ~80 000 pipelines in its first minute from a few thousand shaders, and every one waiting to -/// be built (`pso_async::lazy`) held copies of its own. (Equal bytes are checked: an address -/// the title used again for another shader gets a copy of its own.) +/// Share each distinct shader across pipeline descriptors, even when the title copied it to +/// multiple addresses. Keep the hash for the pipeline's shader keys. fn intern_blob(bytes: &[u8]) -> Blob { - let key = (bytes.as_ptr() as usize, bytes.len()); + intern_hashed_blob(bytes, crate::gpu::shader::fnv64(bytes)) +} + +fn intern_hashed_blob(bytes: &[u8], hash: u64) -> Blob { + let key = (hash, bytes.len()); let mut g = BLOBS.lock().unwrap(); let (m, since_prune) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if let Some(b) = m.get(&key).and_then(std::sync::Weak::upgrade) { - if *b == *bytes { - return b; - } + let bucket = m.entry(key).or_default(); + if let Some(bytes) = bucket.iter().filter_map(std::sync::Weak::upgrade).find(|b| b.as_ref() == bytes) { + return Blob { bytes, hash }; } - let b: Blob = std::sync::Arc::from(bytes); - m.insert(key, std::sync::Arc::downgrade(&b)); + let bytes: std::sync::Arc<[u8]> = std::sync::Arc::from(bytes); + bucket.retain(|w| w.strong_count() > 0); + bucket.push(std::sync::Arc::downgrade(&bytes)); *since_prune += 1; if *since_prune >= 4096 { *since_prune = 0; - m.retain(|_, w| w.strong_count() > 0); + m.retain(|_, bucket| { + bucket.retain(|w| w.strong_count() > 0); + !bucket.is_empty() + }); } - b + Blob { bytes, hash } } /// The shader copies pipelines hold (`intern_blob`): how many and their bytes. pub fn pipeline_blob_bytes() -> (usize, usize) { BLOBS.lock().unwrap().as_ref().map_or((0, 0), |(m, _)| { - m.values().filter_map(std::sync::Weak::upgrade).fold((0, 0), |(n, b), x| (n + 1, b + x.len())) + m.values().flatten().filter_map(std::sync::Weak::upgrade).fold((0, 0), |(n, b), x| (n + 1, b + x.len())) }) } @@ -7063,19 +7071,49 @@ unsafe impl Send for OwnedDesc {} /// pipeline by in the next run. /// `shaders_key` of the one shader `blob`. pub(crate) fn shader_key(blob: &[u8]) -> u64 { - ((0xcbf2_9ce4_8422_2325u64 ^ crate::gpu::shader::fnv64(blob)).wrapping_mul(0x0000_0100_0000_01b3)) | 1 + shader_set_key([crate::gpu::shader::fnv64(blob)]) } pub(crate) fn shaders_key>(blobs: &[B]) -> u64 { - let mut h = 0xcbf2_9ce4_8422_2325u64; - for b in blobs { - h = (h ^ crate::gpu::shader::fnv64(b.as_ref())).wrapping_mul(0x0000_0100_0000_01b3); - } - h | 1 + shader_set_key(blobs.iter().map(|b| crate::gpu::shader::fnv64(b.as_ref()))) +} + +fn shader_set_key(hashes: impl IntoIterator) -> u64 { + hashes.into_iter().fold(0xcbf2_9ce4_8422_2325u64, |key, hash| (key ^ hash).wrapping_mul(0x0000_0100_0000_01b3)) | 1 } #[cfg(test)] mod shaders_key_tests { + #[test] + fn lazy_pipelines_share_identical_shader_bytes_at_distinct_addresses() { + let a = vec![1, 2, 3, 4]; + let mut b = a.clone(); + assert_ne!(a.as_ptr(), b.as_ptr()); + + let first = super::intern_blob(&a); + let second = super::intern_blob(&b); + assert!(std::sync::Arc::ptr_eq(&first.bytes, &second.bytes)); + + b[0] = 5; + let changed = super::intern_blob(&b); + assert!(!std::sync::Arc::ptr_eq(&first.bytes, &changed.bytes)); + assert_eq!(&*first.bytes, &a); + assert_eq!(&*changed.bytes, &b); + assert_eq!(super::shader_set_key([first.hash, changed.hash]), super::shaders_key(&[a, b.clone()])); + b[0] = 1; + assert!(std::sync::Arc::ptr_eq(&first.bytes, &super::intern_blob(&b).bytes)); + } + + #[test] + fn same_length_shader_hash_collisions_keep_distinct_bytes() { + let first = super::intern_hashed_blob(b"abc", u64::MAX); + let second = super::intern_hashed_blob(b"def", u64::MAX); + assert_eq!(&*first.bytes, b"abc"); + assert_eq!(&*second.bytes, b"def"); + assert!(std::sync::Arc::ptr_eq(&first.bytes, &super::intern_hashed_blob(b"abc", u64::MAX).bytes)); + assert!(std::sync::Arc::ptr_eq(&second.bytes, &super::intern_hashed_blob(b"def", u64::MAX).bytes)); + } + #[test] fn the_key_of_one_shader_is_the_key_of_a_set_of_it() { let a = vec![1u8, 2, 3]; @@ -7103,10 +7141,10 @@ impl OwnedDesc { OwnedDesc::Graphics(_, b, ..) => b, OwnedDesc::Stream(_, _, b) => b, }; - let key = shaders_key(blobs); + let key = shader_set_key(blobs.iter().map(|b| b.hash)); // each shader by itself too: what a title's shader preparation translates before the // next run (`pso_async::earlier_used_shaders`) - let parts: Vec = blobs.iter().map(|b| shader_key(b)).collect(); + let parts: Vec = blobs.iter().map(|b| shader_set_key([b.hash])).collect(); super::pso_async::shaders_of(key, parts.clone()); (key, parts) } @@ -7140,7 +7178,7 @@ unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec) { if let Some(bytes) = shader_bytes(b) { blobs.push(intern_blob(bytes)); let v = blobs.last().unwrap(); - *b = bytecode(v); + *b = bytecode(&v.bytes); } else { *b = D3D12_SHADER_BYTECODE::default(); } @@ -7209,7 +7247,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option { buf[at..at + 16].fill(0); } else if crate::gpu::shader::readable(p, n) { blobs.push(intern_blob(std::slice::from_raw_parts(p as *const u8, n))); - buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().as_ptr() as u64).to_le_bytes()); + buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().bytes.as_ptr() as u64).to_le_bytes()); } else { return None; } @@ -7352,17 +7390,17 @@ unsafe fn go_background( // (a graphics pipeline used in this run is built before the next starts: `gfx_records`) let described = if super::pso_async::lazy() { owned.record(key, &parts) } else { None }; // a big compute program that writes nothing but images: binds can go on without it - let big_image_only = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); + let big_image_only = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(&b.bytes))); let image_only = big_image_only && super::pso_async::image_skip(); - let bvh_trav = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| is_rt_gated_cs(b))); + let bvh_trav = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| is_rt_gated_cs(&b.bytes))); let heavy_compute = compute && super::pso_async::async_heavy_compute() - && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::compute_code_len(b).is_some_and(|n| n >= crate::gpu::effects::HEAVY_CODE))); - let ambient_cs = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| super::ambient::is_ambient_compute(b))); + && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::compute_code_len(&b.bytes).is_some_and(|n| n >= crate::gpu::effects::HEAVY_CODE))); + let ambient_cs = compute && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| super::ambient::is_ambient_compute(&b.bytes))); if compute { if let OwnedDesc::Compute(_, b) = &owned { if let Some(cs) = b.first() { - note_compute_threads(*ppv as usize, cs); + note_compute_threads(*ppv as usize, &cs.bytes); } } if bvh_trav { @@ -10858,9 +10896,9 @@ mod mesh_stream_tests { let owned = own_stream(d_valid.as_ptr() as *const c_void).expect("valid stream"); let OwnedDesc::Stream(_, buf, blobs) = owned else { panic!("expected Stream") }; assert_eq!(blobs.len(), 1); - assert_eq!(&*blobs[0], &shader[..]); + assert_eq!(&*blobs[0].bytes, &shader[..]); let rebased = u64::from_le_bytes(buf[8..16].try_into().unwrap()) as usize; - assert_eq!(rebased, blobs[0].as_ptr() as usize); + assert_eq!(rebased, blobs[0].bytes.as_ptr() as usize); assert_ne!(rebased, shader.as_ptr() as usize); assert_eq!(&buf[32..48], &[0u8; 16], "zero-len shader entry cleared"); assert_eq!(&buf[56..72], &[0u8; 16], "cached PSO cleared"); From 229b98006958913980e36e85cea483ab753b3cf2 Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:18 +0100 Subject: [PATCH 250/258] D3D12.X: synchronize sparse mappings and retire VRAM safely Port the mapping and retirement changes from #2981. Seal only the unmaps covered by the queue signals and keep zero-buffer aliases alive through retirement. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/real.rs | 6 + crates/xcl/src/hle/d3d12x/sparse.rs | 22 +++ crates/xcl/src/hle/d3d12x/vram.rs | 222 +++++++++++++++++++++++++--- 3 files changed, 229 insertions(+), 21 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 65801c0e21..6848dfb76b 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9657,6 +9657,12 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis } } drop(record_prof); + // Flush and wait for any tile mappings / recycled-tile zero-fills queued concurrently while + // `record_deferred` built/waited on PSOs so the title's submit never races `UpdateTileMappings`. + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&this) { + super::sparse::wait_pending_mappings(q); + super::vram::wait_pending_mappings(q); + } super::list_x::note_queue_for_lists(this as usize, &mapped); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { // a list still on the GPU from its previous submit: that one first (the PC does not take diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 89cd5b0fb6..8f6765f01f 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -2831,6 +2831,28 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } } +/// Fast-path wait for any sparse-window tile mappings queued after `title_textures::refresh` +/// (for example while `record_deferred` waited on PSO builds). +pub(super) unsafe fn wait_pending_mappings(queue: &ID3D12CommandQueue) { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return }; + if s.mapping_queued.load(Ordering::Relaxed) { + s.signal(); + } + let q = queue.as_raw() as usize; + let waited_before = s.waited.get(&q).copied().unwrap_or(0); + if s.value > 0 && waited_before < s.value { + let (fence, value) = (s.fence.clone(), s.value); + let mappings = s.mapped_value > waited_before; + s.waited.insert(q, value); + drop(g); + if !(mappings && cpu_waited_for_mappings(&fence, value, "sparse uploads and tile mappings")) { + let _ = queue.Wait(&fence, value); + super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &fence, value); + } + } +} + /// `XCL_SPARSE_CPU_WAIT_MS` (1 000 by default, 0: off): how long a title submit waits on the /// CPU for a mapping queue's tile mappings (the sparse windows', the video memory pages') before /// its lists go, instead of the title's queue waiting for them on the GPU. diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index 321db34960..cfe24c0fd9 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -290,6 +290,7 @@ pub(super) unsafe fn recycle_ready(resource: usize) -> bool { if info.was_mapped { if let Some(res) = ID3D12Resource::from_raw_borrowed(&(resource as *mut c_void)) { pages.unmap(res, info.total); + pages.flush_signal(); } } pages.reserved_pool.push(info.key, resource, info.total, info.levels) @@ -941,12 +942,12 @@ impl PoolHeaps { } } - fn take_heap(&mut self, idx: u32) -> Option { - self.zero_bufs.get_mut(idx as usize).map(|b| b.take()); + fn take_heap(&mut self, idx: u32) -> Option<(ID3D12Heap, Option)> { + let zero_buf = self.zero_bufs.get_mut(idx as usize).and_then(|b| b.take()); let h = self.slots.get_mut(idx as usize)?.take()?; self.live -= 1; self.free_slots.push(idx); - Some(h) + Some((h, zero_buf)) } unsafe fn zero_buffer(&mut self, dev: &ID3D12Device, idx: usize) -> Option { @@ -1104,6 +1105,18 @@ struct PendingUnmapBatch { marks: Option>, } +/// Seal a pre-signal snapshot of unsealed unmaps with `marks` into `pending`, leaving any ops +/// pushed concurrently after the snapshot untouched in `unsealed` for a future fresh signal. +fn seal_snapshot_ops( + ops: Vec, + marks: Option>, + pending: &mut std::collections::VecDeque>, +) { + if !ops.is_empty() { + pending.push_back(PendingUnmapBatch { ops, marks }); + } +} + /// Pop every front batch in `queue` whose fence marks have all completed. fn drain_ready_unmap_batches( queue: &mut std::collections::VecDeque>, @@ -1267,15 +1280,15 @@ impl Pages { /// Sweep expired idle pages, drain cooled tiles, and reclaim any completely empty 64 MiB /// pool heaps (above the warm spare count), returning their `ID3D12Heap`s to be dropped /// outside `PAGES.lock()`. - fn sweep_and_reclaim(&mut self, now: std::time::Instant, low_commit: bool) -> Vec { + fn sweep_and_reclaim(&mut self, now: std::time::Instant, low_commit: bool) -> Vec { self.sweep(now); self.pool.drain_cooling_before(now, self.cool_bound()); let keep_spare = if low_commit { 0 } else { keep_spare_pools() }; let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare, POOL_PAGES); let mut dropped = Vec::with_capacity(reclaimed_ids.len()); for idx in reclaimed_ids { - if let Some(h) = self.pools.take_heap(idx) { - dropped.push(h); + if let Some((heap, zero_buf)) = self.pools.take_heap(idx) { + dropped.push(RetiringHeap { _zero_buf: zero_buf, _heap: heap }); } } if !dropped.is_empty() { @@ -2360,9 +2373,17 @@ impl RetireQueue { } } -unsafe impl Send for RetireQueue {} +/// Reclaimed pool/arena heap paired with its optional placed `zero_buf` alias. +/// `_zero_buf` is declared before `_heap` so Rust drops the placed buffer before its backing heap. +struct RetiringHeap { + _zero_buf: Option, + _heap: ID3D12Heap, +} + +unsafe impl Send for RetiringHeap {} +unsafe impl Send for RetireQueue {} -static RETIRE: Mutex>>> = Mutex::new(None); +static RETIRE: Mutex>>> = Mutex::new(None); static RETIRING_BATCHES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// Collect all known live command queues belonging to `dev_key` (deduplicated by raw ptr). @@ -2387,7 +2408,7 @@ unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueu /// Retire `newly_reclaimed` across all live queues on `dev_key`, sweep completed batches, and prune /// dead-queue fences; drops every finished `ID3D12Heap` and `ID3D12Fence` outside all locks. -unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_reclaimed: Vec, unmap_mark: Option<(ID3D12Fence, u64)>, extra_queue: Option<&ID3D12CommandQueue>) { +unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_reclaimed: Vec, unmap_mark: Option<(ID3D12Fence, u64)>, extra_queue: Option<&ID3D12CommandQueue>) { let queues = collect_device_queues(dev_key, extra_queue); let live_keys: HashSet = queues.iter().map(|&(k, _)| k).collect(); let _drop_outside_locks = { @@ -2424,14 +2445,17 @@ unsafe fn signal_device_queues( /// `dev_key`, drain every completed unmap batch onto `pages.queue` (skipping cancelled/remapped /// targets and tiles), and drop popped COM resource references outside `PAGES.lock()`. unsafe fn seal_and_drain_unmaps(dev: &ID3D12Device, dev_key: usize, extra_queue: Option<&ID3D12CommandQueue>) { - let (need_seal_unmaps, need_cool_probe, has_pending_or_probe) = { - let g = PAGES.lock().unwrap(); - let Some(Some(pages)) = g.get(&dev_key) else { return }; - let need_unmaps = !pages.unsealed_unmaps.is_empty(); + // Snapshot `unsealed_unmaps` BEFORE releasing `PAGES.lock()` to signal live queues so any + // unmaps pushed concurrently after `signal_device_queues` are never sealed with stale marks. + let (snapshot_ops, need_cool_probe, has_pending_or_probe) = { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { return }; + let ops = std::mem::take(&mut pages.unsealed_unmaps); let need_probe = pages.has_live_queues && pages.cool_probe.is_none() && (!pages.pool.cooling.is_empty() || !pages.idle.is_empty()); let has_waiters = !pages.pending_unmaps.is_empty() || pages.cool_probe.is_some(); - (need_unmaps, need_probe, has_waiters) + (ops, need_probe, has_waiters) }; + let need_seal_unmaps = !snapshot_ops.is_empty(); if !need_seal_unmaps && !need_cool_probe && !has_pending_or_probe { return; } @@ -2444,11 +2468,12 @@ unsafe fn seal_and_drain_unmaps(dev: &ID3D12Device, dev_key: usize, extra_queue: let mut drop_outside: Vec = Vec::new(); { let mut g = PAGES.lock().unwrap(); - let Some(Some(pages)) = g.get_mut(&dev_key) else { return }; - if !pages.unsealed_unmaps.is_empty() { - let ops = std::mem::take(&mut pages.unsealed_unmaps); - pages.pending_unmaps.push_back(PendingUnmapBatch { ops, marks: marks.clone() }); - } + let Some(Some(pages)) = g.get_mut(&dev_key) else { + drop(g); + drop(snapshot_ops); + return; + }; + seal_snapshot_ops(snapshot_ops, marks.clone(), &mut pages.pending_unmaps); if pages.has_live_queues && pages.cool_probe.is_none() && (!pages.pool.cooling.is_empty() || !pages.idle.is_empty()) { if let Some(probe_marks) = marks { pages.cool_probe = Some((probe_at, probe_marks)); @@ -2503,6 +2528,8 @@ unsafe fn seal_and_drain_unmaps(dev: &ID3D12Device, dev_key: usize, extra_queue: if !newly_fenced_tiles.is_empty() { pages.flush_signal(); pages.fenced_tiles.push_back((pages.value, newly_fenced_tiles)); + } else if pages.dirty_signal { + pages.flush_signal(); } pages.drain_fenced_tiles(); } @@ -2572,13 +2599,60 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { seal_and_drain_unmaps(&dev, dev_key, Some(queue)); } if do_reclaim { - newly_reclaimed.extend(ARENAS.lock().unwrap().sweep_dropped_for(dev_key, now)); + newly_reclaimed.extend( + ARENAS + .lock() + .unwrap() + .sweep_dropped_for(dev_key, now) + .into_iter() + .map(|heap| RetiringHeap { _zero_buf: None, _heap: heap }), + ); } if do_reclaim || !newly_reclaimed.is_empty() || RETIRING_BATCHES.load(std::sync::atomic::Ordering::Acquire) > 0 { retire_heaps_and_sweep(&dev, dev_key, newly_reclaimed, unmap_mark, Some(queue)); } } +/// Pure-CPU predicate: whether `queue` (last waited at `waited`) must flush/wait on `vram` +/// mappings or pending recycled-tile zero-fills before submitting GPU work. +#[inline] +fn needs_mapping_wait(dirty_signal: bool, has_pending_zero: bool, waited: u64, value: u64) -> bool { + dirty_signal || has_pending_zero || waited < value +} + +/// Fast-path wait for any tile mappings or recycled-tile zero-fills queued on `queue`'s device +/// after `title_textures::refresh` (for example while `record_deferred` waited on PSO builds). +pub(super) unsafe fn wait_pending_mappings(queue: &ID3D12CommandQueue) { + let mut dev: Option = None; + if queue.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let dev_key = dev.as_raw() as usize; + let key = queue.as_raw() as usize; + let mut mapping_wait: Option<(ID3D12Fence, u64)> = None; + { + let mut g = PAGES.lock().unwrap(); + if let Some(Some(pages)) = g.get_mut(&dev_key) { + let waited = pages.waited.get(&key).copied().unwrap_or(0); + if needs_mapping_wait(pages.dirty_signal, !pages.pending_zero_tiles.is_empty(), waited, pages.value) { + pages.flush_zero_tiles(&dev); + pages.flush_signal(); + if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { + mapping_wait = Some((pages.fence.clone(), pages.value)); + pages.waited.insert(key, pages.value); + } + } + } + } + if let Some((fence, value)) = mapping_wait { + if !super::sparse::cpu_waited_for_mappings(&fence, value, "texture page mappings") { + let _ = queue.Wait(&fence, value); + super::list_x::note_internal_wait(key, "texture page mappings", &fence, value); + } + } +} + #[cfg(test)] pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); @@ -2917,7 +2991,13 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st let dev_key = dev.as_raw() as usize; let (taken, expired) = ARENAS.lock().unwrap().take_for(dev_key, va, info.SizeInBytes as usize, align, now, |size, align| arena_heap(dev, va, size, align)); if !expired.is_empty() { - retire_heaps_and_sweep(dev, dev_key, expired, None, None); + retire_heaps_and_sweep( + dev, + dev_key, + expired.into_iter().map(|heap| RetiringHeap { _zero_buf: None, _heap: heap }).collect(), + None, + None, + ); } let (heap, offset, id) = taken?; let hr = super::real::dev_create_placed_resource(this, heap.as_raw() as usize, offset, desc as *const _ as usize, state as usize, clear as usize, riid, ppv); @@ -4013,4 +4093,104 @@ mod tests { let mut empty = Vec::new(); assert!(coalesce_tile_runs(&mut empty).is_empty()); } + + #[test] + fn seal_and_drain_unmaps_does_not_attach_stale_marks_to_concurrent_unmaps() { + use std::collections::VecDeque; + use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }; + let mut unsealed: Vec<&'static str> = vec!["unmap_before_signal"]; + let mut pending: VecDeque>> = VecDeque::new(); + // Step 1: Take snapshot BEFORE signaling queues. + let snapshot = std::mem::take(&mut unsealed); + // Step 2: Signal queues at fence value 1 while lock is dropped. + let q_fence = Arc::new(AtomicU64::new(0)); + let stale_marks = Some(vec![(q_fence.clone(), 1)]); + // Step 3: Concurrent thread pushes a newer unmap AFTER queue signal (and after a newer submit). + unsealed.push("unmap_after_signal"); + // Step 4: Seal ONLY the pre-signal snapshot with `stale_marks`. + seal_snapshot_ops(snapshot, stale_marks, &mut pending); + assert_eq!(unsealed, vec!["unmap_after_signal"], "concurrent unmap must stay unsealed for a fresh fence mark"); + // Even once fence value 1 completes, only the pre-signal op drains. + q_fence.store(1, Ordering::SeqCst); + let ready = drain_ready_unmap_batches(&mut pending, |f| f.load(Ordering::SeqCst)); + assert_eq!(ready, vec!["unmap_before_signal"]); + assert!(pending.is_empty()); + // A subsequent seal attaches fresh fence value 2 to the concurrent op. + let snapshot2 = std::mem::take(&mut unsealed); + seal_snapshot_ops(snapshot2, Some(vec![(q_fence.clone(), 2)]), &mut pending); + assert!(drain_ready_unmap_batches(&mut pending, |f| f.load(Ordering::SeqCst)).is_empty()); + q_fence.store(2, Ordering::SeqCst); + assert_eq!( + drain_ready_unmap_batches(&mut pending, |f| f.load(Ordering::SeqCst)), + vec!["unmap_after_signal"] + ); + } + + #[test] + fn wait_pending_mappings_flushes_post_refresh_dirty_signal() { + // Already caught up, no dirty mappings, no pending zero-fills -> fast-path skips wait. + assert!(!needs_mapping_wait(false, false, 6314, 6314)); + // Unsignaled UpdateTileMappings queued during record_deferred (e.g. L21120) -> must flush & wait. + assert!(needs_mapping_wait(true, false, 6314, 6314)); + // Recycled tiles queued for GPU zero-fill during record_deferred -> must flush & wait. + assert!(needs_mapping_wait(false, true, 6314, 6314)); + // Another thread flushed/signaled vram pages 6315..6317 during record_deferred -> must wait. + assert!(needs_mapping_wait(false, false, 6314, 6317)); + } + + #[test] + fn retire_queue_keeps_zero_buf_alive_until_marks_complete() { + use std::sync::{ + atomic::{AtomicU64, AtomicUsize, Ordering}, + Arc, + }; + struct DropTracker(Arc, &'static str, Arc>>); + impl Drop for DropTracker { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + self.2.lock().unwrap().push(self.1); + } + } + struct FakeRetiringHeap { + _zero_buf: Option, + _heap: DropTracker, + } + let dropped = Arc::new(AtomicUsize::new(0)); + let order = Arc::new(std::sync::Mutex::new(Vec::new())); + let item = FakeRetiringHeap { + _zero_buf: Some(DropTracker(dropped.clone(), "zero_buf", order.clone())), + _heap: DropTracker(dropped.clone(), "heap", order.clone()), + }; + let mut rq: RetireQueue> = RetireQueue::new(); + let unmap_f = Arc::new(AtomicU64::new(0)); + let q_f = Arc::new(AtomicU64::new(0)); + let queues = vec![(1usize, q_f.clone())]; + let immediate = rq.retire_with( + vec![item], + Some((unmap_f.clone(), 1)), + &queues, + || Some(q_f.clone()), + |_, _, _| true, + ); + assert!(immediate.is_empty()); + assert_eq!(dropped.load(Ordering::SeqCst), 0, "neither zero_buf nor heap may drop before marks complete"); + + let live: HashSet = [1usize].into_iter().collect(); + // Queue done, unmap mark still pending -> still alive. + q_f.store(1, Ordering::SeqCst); + let (done, _) = rq.sweep_with(&live, |f| f.load(Ordering::SeqCst)); + assert!(done.is_empty()); + assert_eq!(dropped.load(Ordering::SeqCst), 0); + + // Once unmap_mark completes too, batch reaps and drops zero_buf BEFORE heap. + unmap_f.store(1, Ordering::SeqCst); + let (done, _) = rq.sweep_with(&live, |f| f.load(Ordering::SeqCst)); + assert_eq!(done.len(), 1); + drop(done); + assert_eq!(dropped.load(Ordering::SeqCst), 2); + assert_eq!(*order.lock().unwrap(), vec!["zero_buf", "heap"]); + } } From 16b943719e6047b10580df08e49e7a99ba8bbe47 Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:18 +0100 Subject: [PATCH 251/258] D3D12.X: bound sparse upload waits and retry unsent data Adapt #2821 to bound fence waits and retry unsent writes when a slot is still busy. Use smaller upload and readback staging buffers with chunked transfers. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/sparse.rs | 333 ++++++++++++++----- crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs | 13 +- 2 files changed, 258 insertions(+), 88 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 8f6765f01f..1681f0ca32 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -43,15 +43,16 @@ const POOL_TILES: u32 = 64; /// they are unmapped together: 256 MB of video memory const PARKED_MAX: usize = 4096; /// bytes of the ring-buffered upload staging buffer -const STAGING: usize = 64 << 20; +const STAGING: usize = 16 << 20; /// alignment of sub-allocations inside the upload staging ring (write-combined cacheline) const RING_ALIGN: usize = 64; /// number of in-flight upload command allocators / lists const UPLOAD_SLOTS: usize = 16; /// bytes of the dedicated pre-zeroed buffer for tile/hole clears (1 MiB) const ZERO_BUF: usize = 1 << 20; -/// bytes of the GPU→CPU readback staging buffer -const READBACK_STAGING: usize = 16 << 20; +/// bytes of the GPU→CPU readback staging buffer and maximum per readback job +const READBACK_STAGING: usize = 4 << 20; +const QUEUE_WAIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); const PAGE: usize = 0x1000; const PAGES_PER_TILE: usize = TILE / PAGE; @@ -296,6 +297,8 @@ struct State { runs: Option>, /// reusable buffer for dirty runs in `before_execute` (avoids per-submit heap alloc) scratch_runs: Vec<(usize, usize)>, + /// Write-watch may already have been reset for pages with unsent CPU writes. + retry_pages: Vec, } impl Drop for State { @@ -763,13 +766,18 @@ unsafe impl Send for State {} /// expires, so a late completion from an earlier timed-out wait cannot satisfy a newer wait early. /// (As in #1419 by gridoe and #2821 for `main`, same signature, so the two merge as one.) unsafe fn wait_fence_until(fence: &ID3D12Fence, event: HANDLE, target: u64, timeout: std::time::Duration) -> bool { - if target == 0 || fence.GetCompletedValue() >= target { - return true; + let completed = fence.GetCompletedValue(); + if completed >= target { + return completed != u64::MAX; } let _ = windows::Win32::System::Threading::ResetEvent(event); let _ = fence.SetEventOnCompletion(target, event); let deadline = std::time::Instant::now() + timeout; - while fence.GetCompletedValue() < target { + loop { + let completed = fence.GetCompletedValue(); + if completed >= target { + return completed != u64::MAX; + } let rem = deadline.saturating_duration_since(std::time::Instant::now()); if rem.is_zero() { return false; @@ -777,7 +785,6 @@ unsafe fn wait_fence_until(fence: &ID3D12Fence, event: HANDLE, target: u64, time let ms = rem.as_millis().clamp(1, u32::MAX as u128) as u32; windows::Win32::System::Threading::WaitForSingleObject(event, ms); } - true } static STATE: Mutex> = Mutex::new(None); @@ -975,6 +982,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { mapped_value: 0, runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }) })(); match made { @@ -1249,15 +1257,18 @@ impl State { super::flight::signaled("sparse", windows::core::Interface::as_raw(&self.queue) as usize, &self.fence, self.value); } - #[inline] - unsafe fn wait_for(&self, target: u64) { - if target == 0 || self.fence.GetCompletedValue() >= target { - return; - } - if !wait_fence_until(&self.fence, self.event, target, std::time::Duration::from_secs(5)) { - crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue()); - super::real::stop_if_device_removed(); + #[cfg(test)] + unsafe fn wait_for(&self, target: u64) -> bool { + self.wait_for_upload(target, QUEUE_WAIT_TIMEOUT) + } + + unsafe fn wait_for_upload(&self, target: u64, timeout: std::time::Duration) -> bool { + if wait_fence_until(&self.fence, self.event, target, timeout) { + return true; } + crate::xlog_warn!("sparse: the queue has not reached fence value {target} after {} ms (at {})", timeout.as_millis(), self.fence.GetCompletedValue()); + super::real::stop_if_device_removed(); + false } #[inline] @@ -1278,7 +1289,7 @@ impl State { /// readback yet and must not be copied out. #[inline] unsafe fn wait_for_rb(&self, target: u64) -> bool { - if wait_fence_until(&self.rb_done_fence, self.event, target, std::time::Duration::from_secs(5)) { + if wait_fence_until(&self.rb_done_fence, self.event, target, QUEUE_WAIT_TIMEOUT) { return true; } crate::xlog_warn!( @@ -1307,37 +1318,40 @@ impl State { /// Acquire the next upload command slot, waiting only if that slot's previous submission is /// still executing on the GPU, then reset its allocator and list. - unsafe fn begin_slot(&mut self) -> usize { + unsafe fn begin_slot(&mut self, timeout: std::time::Duration) -> Option { let idx = self.next_slot; + let fv = self.slots.get(idx)?.fence_val; self.next_slot = (self.next_slot + 1) % self.slots.len(); - let fv = self.slots[idx].fence_val; - if fv > 0 && self.fence.GetCompletedValue() < fv { - self.wait_for(fv); + if fv > 0 { + if !self.wait_for_upload(fv, timeout) { + return None; + } self.reclaim_ring(); } let slot = &self.slots[idx]; - let _ = slot.alloc.Reset(); - let _ = slot.list.Reset(&slot.alloc, None); - idx + slot.alloc.Reset().ok()?; + slot.list.Reset(&slot.alloc, None).ok()?; + Some(idx) } /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work /// via `queue.Wait(&self.fence, self.value)`). - unsafe fn submit_slot(&mut self, idx: usize) { - let closed = self.slots[idx].list.Close().is_ok(); - if closed { - if let Ok(l) = self.slots[idx].list.cast::() { - super::title_textures::own_work(|| { - self.queue.ExecuteCommandLists(&[Some(l)]); - }); - } - } + unsafe fn submit_slot(&mut self, idx: usize) -> bool { + let list = &self.slots[idx].list; + let Ok(l) = list.Close().and_then(|()| list.cast::()) else { + self.ring_write = self.ring_submitted; + return false; + }; + super::title_textures::own_work(|| { + self.queue.ExecuteCommandLists(&[Some(l)]); + }); self.signal(); self.slots[idx].fence_val = self.value; if self.ring_write > self.ring_submitted { self.inflight.push_back((self.value, self.ring_write)); self.ring_submitted = self.ring_write; } + true } unsafe fn staging_ptr(&mut self) -> Option<*mut u8> { @@ -1444,6 +1458,41 @@ impl State { } } + /// Make the scanned hashes of unsent chunks differ on the next scan. Leave the hashes of + /// chunks already sent untouched, even when they share a CPU page with a retry. + fn invalidate_sent_range(&mut self, a: usize, n: usize) { + let end = a + n; + let mut at = a; + while at < end { + let page = at & !(PAGE - 1); + let tile = page & !(TILE - 1); + let page_end = (page + PAGE).min(end); + if let Some(sent) = self.mapped.get_mut(&tile).and_then(|entry| entry.sent[(page - tile) / PAGE].as_deref_mut()) { + for hash in &mut sent[(at - page) / CHUNK..(page_end - page).div_ceil(CHUNK)] { + *hash ^= 1; + } + } + at = page_end; + } + } + + fn retry_dirty_from(&mut self, runs: &[(usize, usize)], start: (usize, usize)) { + for (a, n) in unsent_runs(runs, start) { + self.invalidate_sent_range(a, n); + self.retry_pages.extend((a & !(PAGE - 1)..a + n).step_by(PAGE)); + } + } + + unsafe fn scan_retry_pages(&mut self, out: &mut Vec<(usize, usize)>) { + if self.retry_pages.is_empty() { + return; + } + self.retry_pages.sort_unstable(); + self.retry_pages.dedup(); + scan_dirty_pages_into(&mut self.mapped, &self.retry_pages, PAGE, scan_threads(), out); + self.retry_pages.clear(); + } + /// Update `sent` hashes for all 64-byte chunks overlapping `[va, va + len)` so the CPU /// copy-back we just wrote to `va` is not re-uploaded by the next `before_execute`. unsafe fn sync_sent_range(&mut self, va: usize, len: usize) { @@ -1483,25 +1532,20 @@ impl State { let mut pending: Vec<(usize, usize, usize, Vec>)> = Vec::new(); let mut used = 0usize; let mut open = false; - let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize, Vec>)>, used: &mut usize, p: *mut u8| { + let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize, Vec>)>, used: &mut usize, p: *mut u8| -> bool { if *open { *open = false; s.order_rb_after_uploads(); - if s.rb_list.Close().is_ok() { - if let Ok(l) = s.rb_list.cast::() { - super::title_textures::own_work(|| { - s.rb_queue.ExecuteCommandLists(&[Some(l)]); - }); - } - } + let Ok(l) = s.rb_list.Close().and_then(|()| s.rb_list.cast::()) else { return false }; + super::title_textures::own_work(|| { + s.rb_queue.ExecuteCommandLists(&[Some(l)]); + }); s.signal_rb(); s.rb_last_fence = s.rb_done_value; - let done = s.wait_for_rb(s.rb_done_value); - s.reclaim_ring(); - if !done { - // the GPU copy has not run: nothing to copy back yet - pending.clear(); + if !s.wait_for_rb(s.rb_done_value) { + return false; } + s.reclaim_ring(); } for (dst, off, len, snap) in pending.iter() { let (dst, off, len) = (*dst, *off, *len); @@ -1548,6 +1592,7 @@ impl State { } pending.clear(); *used = 0; + true }; for &(a, n) in ranges { if n == 0 { @@ -1564,15 +1609,15 @@ impl State { done += (n - done).min(to_tile_end); continue; } - if used == READBACK_STAGING { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); + if used == READBACK_STAGING && !flush_and_copy(self, &mut open, &mut pending, &mut used, p) { + return; } let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); if !open { - self.wait_for_rb(self.rb_last_fence); - let _ = self.rb_alloc.Reset(); - let _ = self.rb_list.Reset(&self.rb_alloc, None); + if !self.wait_for_rb(self.rb_last_fence) || self.rb_alloc.Reset().is_err() || self.rb_list.Reset(&self.rb_alloc, None).is_err() { + return; + } open = true; } let snap_base = cur & !(CHUNK - 1); @@ -1603,11 +1648,14 @@ impl State { /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` /// (zero staging ring bytes consumed, zero CPU stall). - unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) { - if runs.is_empty() || !self.ensure_zero_buf() { - return; + unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)], timeout: std::time::Duration) -> bool { + if runs.is_empty() { + return true; } - let slot_idx = self.begin_slot(); + if !self.ensure_zero_buf() { + return false; + } + let Some(slot_idx) = self.begin_slot(timeout) else { return false }; let mut last_wi: Option = None; let zero_buf = self.zero_buf.as_ref().unwrap(); let list = &self.slots[slot_idx].list; @@ -1632,28 +1680,33 @@ impl State { done += chunk; } } - self.submit_slot(slot_idx); + self.submit_slot(slot_idx) } /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via - /// the 64 MiB ring staging buffer (zero CPU stall on the common path). - unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) { - self.upload_runs(runs, &|at, p, n| { + /// the ring staging buffer. Preserve any unsent chunks when a submission stalls. + unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], timeout: std::time::Duration) -> bool { + if let Err(start) = self.upload_runs(runs, timeout, &|at, p, n| { std::ptr::copy_nonoverlapping(at as *const u8, p, n); true - }); + }) { + self.retry_dirty_from(runs, start); + return false; + } + true } /// Copies `runs` (address in a window, bytes) into video memory; `read(address, to, bytes)` /// gives their bytes (false: the run's piece is left as it is). - unsafe fn upload_runs(&mut self, runs: &[(usize, usize)], read: &dyn Fn(usize, *mut u8, usize) -> bool) { + unsafe fn upload_runs(&mut self, runs: &[(usize, usize)], timeout: std::time::Duration, read: &dyn Fn(usize, *mut u8, usize) -> bool) -> Result<(), (usize, usize)> { if runs.is_empty() { - return; + return Ok(()); } - let Some(p) = self.staging_ptr() else { return }; - let mut open_slot: Option = None; + let p = self.staging_ptr().ok_or((0, 0))?; + // A failed Close invalidates this whole batch, including earlier runs recorded in it. + let mut open_slot: Option<(usize, (usize, usize))> = None; let mut last_wi: Option = None; - for &(a, n) in runs { + for (index, &(a, n)) in runs.iter().enumerate() { let mut done = 0usize; while done < n { let cur = a + done; @@ -1664,7 +1717,14 @@ impl State { last_wi = Some(i); i } - None => break, + None => { + if let Some((slot, start)) = open_slot.take() { + if !self.submit_slot(slot) { + return Err(start); + } + } + return Err((index, done)); + } }, }; let b = self.windows[wi].0; @@ -1673,22 +1733,26 @@ impl State { if (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { self.reclaim_ring(); if (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { - if let Some(slot_idx) = open_slot.take() { - self.submit_slot(slot_idx); + if let Some((slot_idx, start)) = open_slot.take() { + if !self.submit_slot(slot_idx) { + return Err(start); + } self.reclaim_ring(); } while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { - let Some(&(fv, _)) = self.inflight.front() else { break }; - self.wait_for(fv); + let &(fv, _) = self.inflight.front().ok_or((index, done))?; + if !self.wait_for_upload(fv, timeout) { + return Err((index, done)); + } self.reclaim_ring(); } } } let slot_idx = match open_slot { - Some(idx) => idx, + Some((idx, _)) => idx, None => { - let idx = self.begin_slot(); - open_slot = Some(idx); + let idx = self.begin_slot(timeout).ok_or((index, done))?; + open_slot = Some((idx, (index, done))); idx } }; @@ -1703,12 +1767,22 @@ impl State { done += chunk; } } - if let Some(slot_idx) = open_slot { - self.submit_slot(slot_idx); + if let Some((slot_idx, start)) = open_slot { + if !self.submit_slot(slot_idx) { + return Err(start); + } } + Ok(()) } } +fn unsent_runs(runs: &[(usize, usize)], (index, done): (usize, usize)) -> impl Iterator + '_ { + runs.iter().skip(index).enumerate().filter_map(move |(i, &(a, n))| { + let sent = if i == 0 { done } else { 0 }; + (sent < n).then(|| (a + sent, n - sent)) + }) +} + /// Allocate a zeroed, write-watched block in the sparse VRAM windows (never straddling a /// 4 GiB window boundary when `size <= 4 GiB`). Commits the CPU pages and maps VRAM tiles /// (or queues them until the D3D12 device exists). Returns `(address, rounded_size)`. @@ -2157,7 +2231,10 @@ pub unsafe fn readback_now(va: usize, len: usize) { for &(a, n) in &zeroed { s.clear_sent_range(a, n); } - s.upload_zeros(&zeroed); + if !s.upload_zeros(&zeroed, QUEUE_WAIT_TIMEOUT) { + s.to_zero = zeroed; + return; + } } // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` and snapshot // each 64-byte chunk's Phase-1 hash so Phase 3 never clobbers concurrent CPU writes. @@ -2190,8 +2267,8 @@ pub unsafe fn readback_now(va: usize, len: usize) { } pg = tile_end; } - if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); + if !s.upload_dirty_with_timeout(&dirty_runs, QUEUE_WAIT_TIMEOUT) { + return; } let mut spans = Vec::new(); let mut done = 0usize; @@ -2771,17 +2848,19 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: let mut dirty_runs = std::mem::take(&mut s.scratch_runs); dirty_runs.clear(); scan_dirty_pages_into(&mut s.mapped, dirty, page, scan_threads(), &mut dirty_runs); + s.scan_retry_pages(&mut dirty_runs); let t_scanned = std::time::Instant::now(); PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. - if !zero_runs.is_empty() { - s.upload_zeros(&zero_runs); - } - if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); - } - if gpu_view::on() { + let uploaded = if s.upload_zeros(&zero_runs, QUEUE_WAIT_TIMEOUT) { + s.upload_dirty_with_timeout(&dirty_runs, QUEUE_WAIT_TIMEOUT) + } else { + s.to_zero.extend_from_slice(&zero_runs); + s.retry_dirty_from(&dirty_runs, (0, 0)); + false + }; + if uploaded && gpu_view::on() { gpu_view::apply_sync(s, dirty, gpu_view_prep); } PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); @@ -2789,7 +2868,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: static CALLS: AtomicU64 = AtomicU64::new(0); static BYTES: AtomicU64 = AtomicU64::new(0); static MICROS: AtomicU64 = AtomicU64::new(0); - let bytes: usize = zero_runs.iter().chain(dirty_runs.iter()).map(|r| r.1).sum(); + let bytes: usize = if uploaded { zero_runs.iter().chain(dirty_runs.iter()).map(|r| r.1).sum() } else { 0 }; let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; let b = BYTES.fetch_add(bytes as u64, Ordering::Relaxed) + bytes as u64; let us = MICROS.fetch_add(t0.elapsed().as_micros() as u64, Ordering::Relaxed) + t0.elapsed().as_micros() as u64; @@ -3158,6 +3237,7 @@ mod tests { mapped_value: 0, runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; let (first, reused) = s.take_tile().expect("a tile from a new pool"); @@ -3479,6 +3559,7 @@ mod tests { mapped_value: 0, runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; // Mirrors `place_buffer`: map both tiles probing real OS page commitment. @@ -3587,6 +3668,7 @@ mod tests { mapped_value: 0, runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; s.commit_range(base, TILE); @@ -3688,7 +3770,6 @@ mod tests { unsafe fn test_state_with_reserved(tiles: usize) -> (usize, State) { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; use windows::Win32::Graphics::Dxgi::*; - use windows_sys::Win32::System::Memory::MEM_RESERVE; let factory: IDXGIFactory4 = CreateDXGIFactory1().expect("DXGI factory"); let mut dev: Option = None; @@ -3699,6 +3780,12 @@ mod tests { D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).expect("WARP D3D12 device"); } let dev = dev.expect("D3D12 device"); + test_state_with_device(dev, tiles) + } + + unsafe fn test_state_with_device(dev: ID3D12Device, tiles: usize) -> (usize, State) { + use windows_sys::Win32::System::Memory::MEM_RESERVE; + let base = VirtualAlloc(std::ptr::null(), tiles * TILE, MEM_RESERVE, PAGE_NOACCESS) as usize; assert!(base != 0 && base % TILE == 0); let mut reserved: Option = None; @@ -3758,10 +3845,84 @@ mod tests { mapped_value: 0, runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; (base, s) } + #[test] + fn sparse_stalled_upload_retries_only_unsent_chunks_without_a_new_cpu_write() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + assert_eq!(VirtualAlloc(base as *const c_void, TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); + s.commit_range(base, TILE); + s.wait_for(s.value); + s.sync_sent_range(base, PAGE); + let before = *s.mapped[&base].sent[0].as_deref().unwrap(); + + s.ring_write = STAGING as u64; + s.ring_submitted = s.ring_write; + s.inflight.push_back((s.value + 1, s.ring_write)); + let runs = [(base + CHUNK, 2 * CHUNK)]; + assert!(!s.upload_dirty_with_timeout(&runs, std::time::Duration::from_millis(20))); + let after = s.mapped[&base].sent[0].as_deref().unwrap(); + assert_eq!(after[0], before[0]); + assert_eq!(after[3], before[3]); + + let mut pending = Vec::new(); + s.scan_retry_pages(&mut pending); + assert_eq!(pending, runs); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn sparse_staging_bounds_memory_and_transfers_larger_ranges() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let Some(dev) = test_device() else { return }; + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + if dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_err() + || opts.TiledResourcesTier.0 < D3D12_TILED_RESOURCES_TIER_1.0 + { + crate::gpu::recomp::runner::skip_test("no tiled resources"); + return; + } + + let bytes = (16 << 20) + TILE; + let (base, mut s) = test_state_with_device(dev, bytes / TILE); + let alloc: ID3D12CommandAllocator = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.Close().unwrap(); + s.slots.push(UploadSlot { alloc, list, fence_val: 0 }); + assert_eq!(VirtualAlloc(base as *const c_void, bytes, MEM_COMMIT, PAGE_READWRITE) as usize, base); + s.commit_range(base, bytes); + + let mut expected = vec![0; bytes]; + for (i, tile) in expected.chunks_exact_mut(TILE).enumerate() { + tile.fill((i % 251 + 1) as u8); + } + s.upload_runs(&[(base, bytes)], QUEUE_WAIT_TIMEOUT, &|at, dst, len| { + expected[at - base..at - base + len].as_ptr().copy_to_nonoverlapping(dst, len); + true + }).unwrap(); + s.readback_ranges(&[(base, bytes)]); + let copied = std::slice::from_raw_parts(base as *const u8, bytes); + assert!(copied == expected, "bytes must survive across upload wraps and readback batches"); + + let upload_bytes = s.staging.as_ref().unwrap().0.GetDesc().Width; + let readback_bytes = s.readback.as_ref().unwrap().0.GetDesc().Width; + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + assert_eq!((upload_bytes, readback_bytes), (16 << 20, 4 << 20)); + } + } + /// `flush_parked` must keep unmapped pool tiles out of `free` (and `take_tile` must not reuse /// them) while the sparse queue's unmap fence is still in flight on the GPU. #[test] diff --git a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs index e963bc1d0f..347294b6e6 100644 --- a/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs +++ b/crates/xcl/src/hle/d3d12x/sparse/gpu_view.rs @@ -283,10 +283,18 @@ impl State { } out }).collect(); - self.upload_runs(&split, &|dst, p, len| { + if let Err(start) = self.upload_runs(&split, QUEUE_WAIT_TIMEOUT, &|dst, p, len| { let page = dst & !(PAGE - 1); from.get(&page).is_some_and(|r| read_title(r + (dst - page), p, len)) - }); + }) { + let mut retry_bytes = 0; + for (a, bytes) in unsent_runs(&split, start) { + self.invalidate_sent_range(a, bytes); + m.fresh.push(a & !(TILE - 1)); + retry_bytes += bytes; + } + return n - retry_bytes; + } n } } @@ -653,6 +661,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; let mut m = Mirrors::default(); s.ensure_mapped(window, TILE, |_| query_tile_holes(source)); From 706d0ce0e76fd265d5872985a9f8e33524c8ac1b Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:18 +0100 Subject: [PATCH 252/258] D3D12.X: reclaim completed texture uploads across queues Port #2912 so finished staging allocations are reaped even when the originating queue goes quiet. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/real.rs | 9 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 96 ++++++++++++++++++--- 2 files changed, 92 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 6848dfb76b..cd587c32f3 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -9287,7 +9287,14 @@ unsafe fn release_taking_first(this: *mut c_void, take: impl FnOnce() -> T, a } unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { - release_taking_first(this, || super::list_x::on_queue_release(this as usize), drop) + release_taking_first( + this, + || { + super::list_x::on_queue_release(this as usize); + super::title_textures::on_queue_release(this as usize); + }, + drop, + ) } unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 53c5790fa0..1a5f7a6ec6 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1583,22 +1583,38 @@ unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue> (qd?.as_raw() == dev.as_raw()).then(|| q.clone()) } -/// Non-blockingly release completed in-flight upload batches for `queue_key` so staging buffers do -/// not stay pinned during quiet frames with no new texture uploads. -unsafe fn reclaim_completed_on_queue(queue_key: usize) { - if queue_key == 0 { - return; +fn drain_completed( + in_flight: &mut std::collections::VecDeque<(u64, T)>, + bytes: &mut u64, + done: u64, + size_of: impl Fn(&T) -> u64, +) { + while in_flight.front().is_some_and(|&(v, _)| v <= done) { + let (_, f) = in_flight.pop_front().unwrap(); + *bytes = bytes.saturating_sub(size_of(&f)); } +} + +/// Non-blockingly release completed in-flight upload batches across all tracked title queues so +/// staging buffers do not stay pinned on idle or secondary queues. +unsafe fn reclaim_completed_on_queue(_queue_key: usize) { let mut g = ON_QUEUE.lock().unwrap(); - let Some(q) = g.get_mut(&queue_key) else { return }; - if q.in_flight.is_empty() { - return; + for q in g.values_mut() { + if q.in_flight.is_empty() { + continue; + } + let done = q.fence.GetCompletedValue(); + drain_completed(&mut q.in_flight, &mut q.bytes, done, |f| f.bytes); } - let done = q.fence.GetCompletedValue(); - while q.in_flight.front().is_some_and(|&(v, _)| v <= done) { - let (_, f) = q.in_flight.pop_front().unwrap(); - q.bytes = q.bytes.saturating_sub(f.bytes); +} + +/// Drop tracked upload state for a released command queue so its fence and staging buffers do not +/// leak and a later queue at the same address cannot reuse a stale fence. +pub(super) fn on_queue_release(queue_key: usize) { + if queue_key == 0 { + return; } + ON_QUEUE.lock().unwrap().remove(&queue_key); } unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u32) { @@ -3944,4 +3960,60 @@ mod tests { assert!(t.mark_gpu_written(0x100)); assert!(t.watchable_ranges().is_empty()); } + + #[test] + fn drain_completed_reclaims_only_finished_batches() { + let mut q = std::collections::VecDeque::from([(1u64, 4096u64), (2, 8192), (5, 16384)]); + let mut bytes = 4096 + 8192 + 16384; + drain_completed(&mut q, &mut bytes, 2, |&b| b); + assert_eq!(q.len(), 1); + assert_eq!(q.front(), Some(&(5, 16384))); + assert_eq!(bytes, 16384); + drain_completed(&mut q, &mut bytes, 5, |&b| b); + assert!(q.is_empty()); + assert_eq!(bytes, 0); + } + + #[test] + fn on_queue_release_removes_tracked_queue_entry() { + on_queue_release(0); // no-op on null queue key + let mut dev: Option = None; + if unsafe { windows::Win32::Graphics::Direct3D12::D3D12CreateDevice(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0, &mut dev) }.is_err() { + crate::gpu::recomp::runner::skip_test("no D3D12 adapter"); + return; + } + let dev = dev.unwrap(); + let fence: ID3D12Fence = unsafe { dev.CreateFence(3, D3D12_FENCE_FLAG_NONE) }.expect("fence"); + let fake_key = 0xDEAD_BEEF_CAFE_0001usize; + { + let mut g = ON_QUEUE.lock().unwrap(); + g.insert(fake_key, QueueUploads { fence, value: 3, in_flight: std::collections::VecDeque::new(), bytes: 0 }); + assert!(g.contains_key(&fake_key)); + } + on_queue_release(fake_key); + assert!(!ON_QUEUE.lock().unwrap().contains_key(&fake_key), "on_queue_release must remove the queue entry from ON_QUEUE"); + } + + #[test] + fn register_reuses_precomputed_xg_texture_arc() { + let mut desc = [0u8; 0x38]; + desc[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + desc[0x10..0x18].copy_from_slice(&64u64.to_le_bytes()); + desc[0x18..0x1C].copy_from_slice(&64u32.to_le_bytes()); + desc[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + desc[0x1E..0x20].copy_from_slice(&1u16.to_le_bytes()); + desc[0x20..0x24].copy_from_slice(&28u32.to_le_bytes()); // RGBA8 + desc[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + let pre = Arc::new(xg::Texture::new(&desc).unwrap()); + let fake_res = 0xDEAD_BEEF_1234usize as *mut c_void; + unsafe { + register(std::ptr::null_mut(), fake_res, 0x7000_0000, &desc, D3D12_RESOURCE_STATE_COMMON, Some(Arc::clone(&pre))).unwrap(); + } + let stored = { + let t = TEXTURES.lock().unwrap(); + Arc::clone(&t.by_res.get(&(fake_res as usize)).expect("registered entry").tex) + }; + assert!(Arc::ptr_eq(&pre, &stored), "register must reuse precomputed Arc without recomputing"); + let _ = forget(fake_res as usize); + } } From 47cbd3aa07e03868ed06f8083b93c6fbc9d006fe Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:18 +0100 Subject: [PATCH 253/258] D3D12.X: pool small fallback resource allocations Port #2985 so supported fallback resources can share backing heaps and reuse the decoded layout. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/device_x.rs | 26 +- crates/xcl/src/hle/d3d12x/title_textures.rs | 18 +- crates/xcl/src/hle/d3d12x/vram.rs | 1 + crates/xcl/src/hle/d3d12x/vram_small.rs | 534 +++++++++++++++++++- 4 files changed, 560 insertions(+), 19 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 27e97adc29..39bfe27d1e 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -1130,18 +1130,20 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, let flags = u32::from_le_bytes(d[0x30..0x34].try_into().unwrap()); let mut placed_hr = None; let mut pc_tex_desc: Option = None; - let mut water_tex: Option<(windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, u32, u32, crate::hle::xg::Texture)> = None; + let mut water_tex: Option<(windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT, u32, u32, std::sync::Arc)> = None; + let mut xg_tex: Option> = None; if !buffer { let pc = std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC); pc_tex_desc = Some(pc); let timer = place_times::step(Step::Desc); - let xg_tex = crate::hle::xg::Texture::new(&x).ok(); - let console_bytes = xg_tex.as_ref().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); + let tex = crate::hle::xg::Texture::new(&x).ok().map(std::sync::Arc::new); + let console_bytes = tex.as_ref().map(|t| t.size()).filter(|&s| s != u64::MAX && s != 0); if console_bytes.is_some() && super::cpu_writes::is_water_readback_desc(&pc) { - if let Some(t) = xg_tex { + if let Some(t) = tex.clone() { water_tex = Some((pc.Format, pc.Width as u32, pc.Height, t)); } } + xg_tex = tex; drop(timer); if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { @@ -1153,7 +1155,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, super::depth_uav::register_if_depth_uav(this, *ppv, &x, state, console_state); super::format_alias::register_title_texture(this as usize, *ppv as usize, va as usize, &pc, flags, state); if let Some((fmt, w, h, t)) = water_tex { - super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, w, h, std::sync::Arc::new(t)); + super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, w, h, t); } else if super::cpu_writes::has_water_readback() { super::cpu_writes::unregister_water_readback(*ppv as usize); } @@ -1167,13 +1169,19 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, let hr = match placed_hr { Some(hr) => hr, None => { - let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; - real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, d.as_ptr() as usize, state as usize, clear as usize, riid, ppv) + let pc_desc = pc_tex_desc.unwrap_or_else(|| std::ptr::read_unaligned(d.as_ptr() as *const D3D12_RESOURCE_DESC)); + match super::vram_small::place_fallback(this, &pc_desc, state, clear, riid, ppv) { + Some(hr) => hr, + None => { + let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + real::dev_create_committed_resource(this, &heap as *const _ as usize, 0, d.as_ptr() as usize, state as usize, clear as usize, riid, ppv) + } + } } }; if hr >= 0 && !buffer && !(*ppv).is_null() { if let Some((fmt, w, h, t)) = water_tex { - super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, w, h, std::sync::Arc::new(t)); + super::cpu_writes::register_water_readback(*ppv as usize, va as usize, fmt, w, h, t); } else if super::cpu_writes::has_water_readback() { super::cpu_writes::unregister_water_readback(*ppv as usize); } @@ -1184,7 +1192,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, static M: AtomicU64 = AtomicU64::new(0); if !aliased_to_gpu { let timer = place_times::step(Step::Register); - let registered = super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)); + let registered = super::title_textures::register(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32), xg_tex); drop(timer); match registered { Ok(()) => { diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 1a5f7a6ec6..6c650249a9 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -548,11 +548,21 @@ fn is_small_cpu_filled_target(w: u64, h: u32, samples: u32, flags: u32) -> bool } /// A texture the title placed at `va` (its console desc `desc`): kept in step with the memory. -pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, desc: &[u8; 0x38], state: D3D12_RESOURCE_STATES) -> Result<(), String> { +pub(super) unsafe fn register( + device: *mut c_void, + res: *mut c_void, + va: usize, + desc: &[u8; 0x38], + state: D3D12_RESOURCE_STATES, + precomputed_tex: Option>, +) -> Result<(), String> { // (a new texture object, or the address of an old one again: its first upload is not left out) LAST_CONTENT.lock().unwrap().remove(&(res as usize)); STREAM_RECHECK.lock().unwrap().remove(&(res as usize)); - let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?; + let tex = match precomputed_tex { + Some(t) => t, + None => Arc::new(xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?), + }; // the console's 32-bit 116 / 117 floats are half floats on the PC (`pc_resource_desc`): the // title's bytes are not the resource's texels if matches!(u32::from_le_bytes(desc[0x20..0x24].try_into().unwrap()), 116 | 117) { @@ -599,7 +609,7 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, va, src, in_gpu_view, - tex: Arc::new(tex), + tex, states: vec![state], pending: true, gpu_written: false, @@ -2715,7 +2725,7 @@ mod tests { ).unwrap(); let texture: ID3D12Resource = texture.unwrap(); let key = texture.as_raw() as usize; - register(raw_device, texture.as_raw(), va, &console, D3D12_RESOURCE_STATE_COMMON).unwrap(); + register(raw_device, texture.as_raw(), va, &console, D3D12_RESOURCE_STATE_COMMON, None).unwrap(); let _registered = RegisteredTexture(key); for value in [0x3D, 0x9A] { std::ptr::write_bytes(src as *mut u8, value, PAGE); diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index cfe24c0fd9..902a53b1e0 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -254,6 +254,7 @@ unsafe fn release_raw_com(raw: usize) { pub(super) fn forget_for_recycle(resource: usize, held: bool) -> Option { let placed = PLACED_TEXTURES.write().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); if !placed { + super::vram_small::forget_fallback(resource); return None; } let info = if super::vram_small::forget(resource) { diff --git a/crates/xcl/src/hle/d3d12x/vram_small.rs b/crates/xcl/src/hle/d3d12x/vram_small.rs index e33ec692bd..147bca241c 100644 --- a/crates/xcl/src/hle/d3d12x/vram_small.rs +++ b/crates/xcl/src/hle/d3d12x/vram_small.rs @@ -15,6 +15,7 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -305,13 +306,252 @@ pub(super) fn forget(resource: usize) -> bool { false } -/// `(used_bytes, pool_bytes)` across all devices. +/// 64 KiB allocation unit (`D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT`) for default-heap fallback resources. +const FALLBACK_UNIT: usize = 0x1_0000; +/// Largest fallback resource pooled here: 4 MiB (`64 * 64 KiB`). +const FALLBACK_MAX_UNITS: u32 = 64; +/// Units per shared 16 MiB default fallback heap (`256 * 64 KiB`). +const FALLBACK_POOL_UNITS: u32 = 256; + +/// Sub-allocated 16 MiB `D3D12_HEAP_TYPE_DEFAULT` heaps (`D3D12_HEAP_FLAG_NONE`, ResourceHeapTier 2) +/// replacing per-resource `CreateCommittedResource` calls on the non-reservable fallback path +/// (e.g., `TEXTURE1D`, 3D packed-mip textures, and small non-UMA buffers). +struct DefaultFallbackPools { + pools: Vec>, + /// Per-size-class (`1..=FALLBACK_MAX_UNITS`) reusable blocks `(pool, offset)`. + free: [Vec<(u32, u32)>; (FALLBACK_MAX_UNITS as usize) + 1], + /// Released blocks waiting `COOL` before reuse so in-flight GPU work finishes. + cooling: VecDeque<(Block, Instant)>, + /// Live resource raw pointer -> `(pool, offset_units, size_units)`. + resources: HashMap, + /// Total 64 KiB units currently backing live resources. + used_units: usize, +} + +impl DefaultFallbackPools { + fn new() -> Self { + DefaultFallbackPools { + pools: Vec::new(), + free: std::array::from_fn(|_| Vec::new()), + cooling: VecDeque::new(), + resources: HashMap::new(), + used_units: 0, + } + } + + fn drain_cooling(&mut self, now: Instant) { + while self.cooling.front().is_some_and(|&(_, at)| now.duration_since(at) >= COOL) { + if let Some(((pool, offset, units), _)) = self.cooling.pop_front() { + self.free[units as usize].push((pool, offset)); + } + } + } + + fn try_acquire(&mut self, units: u32, now: Instant) -> Option<(H, Block)> { + debug_assert!((1..=FALLBACK_MAX_UNITS).contains(&units)); + self.drain_cooling(now); + let (pool, offset) = if let Some(b) = self.free[units as usize].pop() { + b + } else if let Some((idx, p)) = self.pools.iter_mut().enumerate().rev().find(|(_, p)| p.next_unit + units <= FALLBACK_POOL_UNITS) { + let off = p.next_unit; + p.next_unit += units; + (idx as u32, off) + } else { + return None; + }; + let heap = self.pools[pool as usize].heap.clone(); + self.used_units += units as usize; + Some((heap, (pool, offset, units))) + } + + fn add_pool_and_acquire(&mut self, heap: H, units: u32, now: Instant) -> (H, Block) { + if let Some(got) = self.try_acquire(units, now) { + return got; + } + let pool_idx = self.pools.len() as u32; + self.pools.push(Pool { heap, next_unit: 0 }); + if let Some(got) = self.try_acquire(units, now) { + return got; + } + unreachable!("fresh fallback pool {pool_idx} must fit {units} units"); + } + + fn rollback(&mut self, block: Block) { + self.used_units -= block.2 as usize; + self.free[block.2 as usize].push((block.0, block.1)); + } + + fn note_resource(&mut self, res: usize, block: Block) { + self.resources.insert(res, block); + } + + fn forget(&mut self, res: usize, now: Instant) -> bool { + let Some(block) = self.resources.remove(&res) else { + return false; + }; + self.used_units -= block.2 as usize; + self.cooling.push_back((block, now)); + true + } + + fn bytes(&self) -> (usize, usize) { + (self.used_units * FALLBACK_UNIT, self.pools.len() * FALLBACK_POOL_UNITS as usize * FALLBACK_UNIT) + } +} + +unsafe impl Send for DefaultFallbackPools {} + +static FALLBACK_POOLS: Mutex>> = Mutex::new(BTreeMap::new()); +static FALLBACK_LIVE: AtomicUsize = AtomicUsize::new(0); +static TIER2_CACHE: Mutex> = Mutex::new(BTreeMap::new()); + +fn fallback_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_VRAM_FALLBACK_POOL").map_or(true, |v| v.trim() != "0")) +} + +fn tier2_cached(dev: &ID3D12Device) -> bool { + let dev_key = dev.as_raw() as usize; + if let Some(&ok) = TIER2_CACHE.lock().unwrap().get(&dev_key) { + return ok; + } + let mut opts = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); + let ok = unsafe { + dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, &mut opts as *mut _ as *mut c_void, std::mem::size_of_val(&opts) as u32).is_ok() + && opts.ResourceHeapTier.0 >= 2 + }; + TIER2_CACHE.lock().unwrap().insert(dev_key, ok); + ok +} + +fn fallback_candidate(desc: &D3D12_RESOURCE_DESC) -> bool { + let max_bytes = FALLBACK_MAX_UNITS as u64 * FALLBACK_UNIT as u64; + if desc.SampleDesc.Count > 1 { + return false; + } + match desc.Dimension { + D3D12_RESOURCE_DIMENSION_BUFFER => desc.Width > 0 && desc.Width <= max_bytes, + D3D12_RESOURCE_DIMENSION_TEXTURE1D | D3D12_RESOURCE_DIMENSION_TEXTURE2D | D3D12_RESOURCE_DIMENSION_TEXTURE3D => true, + _ => false, + } +} + +/// Place a non-reservable fallback resource (`TEXTURE1D`, packed-mip 3D texture, small non-UMA buffer, etc.) +/// into a shared 16 MiB `D3D12_HEAP_TYPE_DEFAULT` heap via `CreatePlacedResource` instead of paying a +/// per-resource `CreateCommittedResource` WDDM allocation. Returns `None` to fall back to `CreateCommittedResource`. +#[allow(clippy::too_many_arguments)] +pub(super) unsafe fn place_fallback( + this: *mut c_void, + desc: &D3D12_RESOURCE_DESC, + state: u32, + clear: *const c_void, + riid: *const windows_sys::core::GUID, + ppv: *mut *mut c_void, +) -> Option { + if !fallback_enabled() || !fallback_candidate(desc) { + return None; + } + let dev = ID3D12Device::from_raw_borrowed(&this)?; + if !tier2_cached(dev) { + return None; + } + let placed_desc = D3D12_RESOURCE_DESC { Alignment: 0, ..*desc }; + let info = dev.GetResourceAllocationInfo(0, &[placed_desc]); + if info.SizeInBytes == u64::MAX || info.SizeInBytes == 0 || info.Alignment == 0 || info.Alignment > FALLBACK_UNIT as u64 { + return None; + } + let units = (info.SizeInBytes as usize).div_ceil(FALLBACK_UNIT) as u32; + if !(1..=FALLBACK_MAX_UNITS).contains(&units) { + return None; + } + let dev_key = dev.as_raw() as usize; + let now = Instant::now(); + + let (heap, block) = { + let mut g = FALLBACK_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(DefaultFallbackPools::new); + pools.try_acquire(units, now) + } + .or_else(|| { + let heap_desc = D3D12_HEAP_DESC { + SizeInBytes: FALLBACK_POOL_UNITS as u64 * FALLBACK_UNIT as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT as u64, + Flags: D3D12_HEAP_FLAG_NONE, + }; + let mut new_heap: Option = None; + if let Err(e) = super::title_textures::own_work(|| dev.CreateHeap(&heap_desc, &mut new_heap)) { + crate::xlog_warn!("D3D12.X: default fallback pool CreateHeap: {e}"); + return None; + } + let new_heap = new_heap?; + let mut g = FALLBACK_POOLS.lock().unwrap(); + let pools = g.entry(dev_key).or_insert_with(DefaultFallbackPools::new); + Some(pools.add_pool_and_acquire(new_heap, units, Instant::now())) + })?; + + let hr = super::real::dev_create_placed_resource( + this, + heap.as_raw() as usize, + block.1 as usize * FALLBACK_UNIT, + &placed_desc as *const _ as usize, + state as usize, + clear as usize, + riid, + ppv, + ); + if hr < 0 || (*ppv).is_null() { + let mut g = FALLBACK_POOLS.lock().unwrap(); + if let Some(pools) = g.get_mut(&dev_key) { + pools.rollback(block); + } + return None; + } + let raw = *ppv as usize; + FALLBACK_POOLS.lock().unwrap().entry(dev_key).or_insert_with(DefaultFallbackPools::new).note_resource(raw, block); + FALLBACK_LIVE.fetch_add(1, Ordering::Release); + Some(hr) +} + +/// Release a default-fallback-pool resource on COM release. +pub(super) fn forget_fallback(resource: usize) -> bool { + if FALLBACK_LIVE.load(Ordering::Acquire) == 0 { + return false; + } + let mut g = FALLBACK_POOLS.lock().unwrap(); + let now = Instant::now(); + for pools in g.values_mut() { + if pools.forget(resource, now) { + FALLBACK_LIVE.fetch_sub(1, Ordering::Relaxed); + return true; + } + } + false +} + +/// `(used_bytes, pool_bytes)` across all devices (4 KiB small pools + 64 KiB default fallback pools). pub(super) fn bytes() -> (usize, usize) { - let g = SMALL_POOLS.lock().unwrap(); - g.values().fold((0, 0), |(used, pools), p| { - let (u, t) = p.bytes(); - (used + u, pools + t) - }) + let (su, sp) = { + let g = SMALL_POOLS.lock().unwrap(); + g.values().fold((0, 0), |(used, pools), p| { + let (u, t) = p.bytes(); + (used + u, pools + t) + }) + }; + let (fu, fp) = { + let g = FALLBACK_POOLS.lock().unwrap(); + g.values().fold((0, 0), |(used, pools), p| { + let (u, t) = p.bytes(); + (used + u, pools + t) + }) + }; + (su + fu, sp + fp) +} + +#[cfg(test)] +pub(super) fn fallback_bytes_for(device: usize) -> (usize, usize) { + let g = FALLBACK_POOLS.lock().unwrap(); + g.get(&device).map_or((0, 0), DefaultFallbackPools::bytes) } #[cfg(test)] @@ -598,4 +838,286 @@ mod tests { drop((sampled_view, rt)); } } + + #[test] + fn fallback_pool_packs_cools_recycles_and_rolls_back() { + let t0 = Instant::now(); + let at = |ms: u64| t0 + Duration::from_millis(ms); + let mut p: DefaultFallbackPools = DefaultFallbackPools::new(); + let alloc = |p: &mut DefaultFallbackPools, units: u32, res: usize, now: Instant| -> (u32, Block) { + let (h, b) = p.try_acquire(units, now).unwrap_or_else(|| { + let id = p.pools.len() as u32; + p.add_pool_and_acquire(id, units, now) + }); + p.note_resource(res, b); + (h, b) + }; + + // 8 x 64 KiB resources pack contiguously into 512 KiB of pool 0. + for i in 0..8usize { + let (h, b) = alloc(&mut p, 1, 1000 + i, at(0)); + assert_eq!((h, b), (0, (0, i as u32, 1))); + } + assert_eq!(p.bytes(), (8 * FALLBACK_UNIT, FALLBACK_POOL_UNITS as usize * FALLBACK_UNIT)); + + // Release resource 1003; must stay in cooling until COOL (2s) elapses. + assert!(p.forget(1003, at(100))); + assert_eq!(p.bytes().0, 7 * FALLBACK_UNIT); + let (_, b_wait) = alloc(&mut p, 1, 1100, at(1500)); + assert_eq!(b_wait, (0, 8, 1), "still cooling at +1.4s, must not reuse yet"); + let (_, b_rec) = alloc(&mut p, 1, 1101, at(2200)); + assert_eq!(b_rec, (0, 3, 1), "block (0, 3, 1) recycled after COOL"); + + // Rollback on creation failure returns the block immediately to the free list. + let (_, b_fail) = p.try_acquire(4, at(2300)).unwrap(); + assert_eq!(b_fail, (0, 9, 4)); + p.rollback(b_fail); + let (_, b_reused) = alloc(&mut p, 4, 1102, at(2300)); + assert_eq!(b_reused, (0, 9, 4)); + + // Concurrent CreateHeap race: add_pool_and_acquire reuses existing room without pushing an empty pool. + let pools_before = p.pools.len(); + let (h_raced, _) = p.add_pool_and_acquire(999, 2, at(2400)); + assert_eq!(h_raced, 0); + assert_eq!(p.pools.len(), pools_before, "must not push redundant fallback pool when room exists"); + } + + #[test] + fn fallback_candidate_filters_msaa_and_oversized_buffers() { + let mut buf = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + assert!(fallback_candidate(&buf)); + buf.Width = (FALLBACK_MAX_UNITS as u64 * FALLBACK_UNIT as u64) + 1; + assert!(!fallback_candidate(&buf), "buffers > 4 MiB stay committed"); + buf.Width = 0; + assert!(!fallback_candidate(&buf)); + + let mut tex1d = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE1D, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + ..Default::default() + }; + assert!(fallback_candidate(&tex1d)); + tex1d.SampleDesc.Count = 4; + assert!(!fallback_candidate(&tex1d), "MSAA requires 4 MiB alignment"); + } + + #[test] + fn gpu_fallback_pool_places_texture1d_and_small_buffers_cleanly() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory1().expect("DXGI factory"); + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let mut dev: Option = None; + for (adapter, _) in crate::gpu::adapter::candidates(&factory, &sel) { + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() && dev.is_some() { + break; + } + } + let Some(dev) = dev else { + crate::gpu::recomp::runner::skip_test("no D3D12 device"); + return; + }; + if !tier2_cached(&dev) { + crate::gpu::recomp::runner::skip_test("resource heap tier < 2"); + return; + } + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let dev_key = dev.as_raw() as usize; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + + let (used0, _) = fallback_bytes_for(dev_key); + let tex1d_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE1D, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let mut p1 = std::ptr::null_mut(); + let hr1 = place_fallback(dev.as_raw(), &tex1d_desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p1); + assert!(hr1.is_some_and(|h| h >= 0) && !p1.is_null(), "TEXTURE1D fallback placement failed: {hr1:x?}"); + assert!(!super::super::vram::is_placed_texture(p1 as usize), "fallback pool resources must preserve non-shared committed semantics"); + let r1 = ID3D12Resource::from_raw(p1); + + let buf_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let mut p2 = std::ptr::null_mut(); + let hr2 = place_fallback(dev.as_raw(), &buf_desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p2); + assert!(hr2.is_some_and(|h| h >= 0) && !p2.is_null(), "small buffer fallback placement failed: {hr2:x?}"); + assert!(!super::super::vram::is_placed_texture(p2 as usize)); + let r2 = ID3D12Resource::from_raw(p2); + + let (used1, pool1) = fallback_bytes_for(dev_key); + assert_eq!(used1 - used0, 2 * FALLBACK_UNIT, "TEXTURE1D + 4 KiB buffer must consume 2 x 64 KiB fallback units"); + assert!(pool1 >= FALLBACK_POOL_UNITS as usize * FALLBACK_UNIT); + drop((r2, r1)); + let (used2, _) = fallback_bytes_for(dev_key); + assert_eq!(used2, used0, "COM release must return both fallback blocks via forget_fallback"); + } + } + + /// Offline D3D12 microbenchmark: measures (1) `CreateCommittedResource` vs `DefaultFallbackPools::place_fallback` + /// (`CreatePlacedResource` into 16 MiB heap) for TEXTURE1D + small fallback buffers, and + /// (2) double `xg::Texture::new` vs deduplicated single `xg::Texture::new` + `Arc::clone`. + #[test] + #[ignore] + fn bench_fallback_pool_vs_committed_and_xg_dedup() { + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::Common::*; + use windows::Win32::Graphics::Dxgi::*; + unsafe { + let factory: IDXGIFactory6 = CreateDXGIFactory1().expect("DXGI factory"); + let sel = crate::gpu::adapter::Selector::from_env_or("auto"); + let mut dev: Option = None; + for (adapter, _) in crate::gpu::adapter::candidates(&factory, &sel) { + if D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() && dev.is_some() { + break; + } + } + let dev = dev.expect("D3D12 device"); + assert!(tier2_cached(&dev), "requires ResourceHeapTier >= 2"); + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + + let tex1d_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE1D, + Width: 256, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_UNKNOWN, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let buf_desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: 4096, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_NONE, + ..Default::default() + }; + let heap_props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + + // Warm up one heap in DefaultFallbackPools so steady-state placement is measured. + let mut warm = std::ptr::null_mut(); + let _ = place_fallback(dev.as_raw(), &tex1d_desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut warm); + if !warm.is_null() { + drop(ID3D12Resource::from_raw(warm)); + } + + const N: usize = 256; + let t_committed = Instant::now(); + let mut committed_res = Vec::with_capacity(N); + for i in 0..N { + let d = if i % 2 == 0 { &tex1d_desc } else { &buf_desc }; + let mut p = std::ptr::null_mut(); + let hr = super::super::real::dev_create_committed_resource( + dev.as_raw(), + &heap_props as *const _ as usize, + 0, + d as *const _ as usize, + D3D12_RESOURCE_STATE_COMMON.0 as usize, + 0, + riid, + &mut p, + ); + assert!(hr >= 0 && !p.is_null(), "CreateCommittedResource failed: {hr:#x}"); + committed_res.push(ID3D12Resource::from_raw(p)); + } + let committed_us = t_committed.elapsed().as_micros() as f64; + drop(committed_res); + + let t_pooled = Instant::now(); + let mut pooled_res = Vec::with_capacity(N); + for i in 0..N { + let d = if i % 2 == 0 { &tex1d_desc } else { &buf_desc }; + let mut p = std::ptr::null_mut(); + let hr = place_fallback(dev.as_raw(), d, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), riid, &mut p); + assert!(hr.is_some_and(|h| h >= 0) && !p.is_null(), "place_fallback failed: {hr:x?}"); + pooled_res.push(ID3D12Resource::from_raw(p)); + } + let pooled_us = t_pooled.elapsed().as_micros() as f64; + drop(pooled_res); + + let speedup_alloc = committed_us / pooled_us.max(1.0); + println!( + "BENCH Opt B ({N}x mixed TEXTURE1D+Buffer): CreateCommittedResource={:.2} ms ({:.2} us/op) vs place_fallback={:.2} ms ({:.2} us/op) => {:.2}x speedup", + committed_us / 1000.0, committed_us / N as f64, pooled_us / 1000.0, pooled_us / N as f64, speedup_alloc + ); + + // Opt A microbenchmark: 1000x double xg::Texture::new vs single xg::Texture::new + Arc::clone + let mut console = [0u8; 0x38]; + console[0..4].copy_from_slice(&3u32.to_le_bytes()); // Texture2D + console[0x10..0x18].copy_from_slice(&1024u64.to_le_bytes()); + console[0x18..0x1C].copy_from_slice(&1024u32.to_le_bytes()); + console[0x1C..0x1E].copy_from_slice(&1u16.to_le_bytes()); + console[0x1E..0x20].copy_from_slice(&10u16.to_le_bytes()); // 10 mips + console[0x20..0x24].copy_from_slice(&71u32.to_le_bytes()); // BC1_UNORM + console[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); + const M: usize = 2000; + let t_double = Instant::now(); + let mut acc = 0u64; + for _ in 0..M { + let a = crate::hle::xg::Texture::new(&console).unwrap(); + let b = crate::hle::xg::Texture::new(&console).unwrap(); + acc = acc.wrapping_add(a.size() ^ b.size()); + } + let double_us = t_double.elapsed().as_micros() as f64; + + let t_dedup = Instant::now(); + for _ in 0..M { + let a = std::sync::Arc::new(crate::hle::xg::Texture::new(&console).unwrap()); + let b = std::sync::Arc::clone(&a); + acc = acc.wrapping_add(a.size() ^ b.size()); + } + let dedup_us = t_dedup.elapsed().as_micros() as f64; + std::hint::black_box(acc); + + let speedup_xg = double_us / dedup_us.max(1.0); + println!( + "BENCH Opt A ({M}x 1024x1024 10-mip BC1 xg::Texture::new): double={:.2} ms ({:.2} us/op) vs dedup={:.2} ms ({:.2} us/op) => {:.2}x speedup", + double_us / 1000.0, double_us / M as f64, dedup_us / 1000.0, dedup_us / M as f64, speedup_xg + ); + } + } } From 9320dd4281af402fa678c3d7f105d3a3f138c36d Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:19 +0100 Subject: [PATCH 254/258] D3D12.X: report resident memory by allocation owner Sample process pages to distinguish unified, sparse, and other resident memory in the diagnostic report. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/memory_report.rs | 89 +++++++++++++++++++++- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs index 59cc96096f..7cc6d58b48 100644 --- a/crates/xcl/src/hle/d3d12x/memory_report.rs +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -171,15 +171,40 @@ pub fn snapshot() -> Snapshot { Snapshot { commit: process_commit(), local, non_local, parts } } +/// What a committed region is counted as in `walk_line`'s memory in RAM. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Kind2 { + Coherent, + Sparse, + Private, + Mapped, + Image, +} + +/// One page in sixteen of the committed regions is asked about (`QueryWorkingSetEx`): committed +/// memory is what Windows promised, and what a machine runs out of is the memory in RAM – a +/// retail title's world load ended, every time, with 1.5 to 3 GB of RAM free. +const SAMPLE: usize = 0x1_0000; + +/// The bytes each sample stands for that are in RAM: `samples` are (address, bytes it stands +/// for), `valid` says whether the page at an address is in the working set. +fn resident(samples: &[(usize, u64)], valid: impl Fn(usize) -> bool) -> u64 { + samples.iter().enumerate().filter(|(i, _)| valid(*i)).map(|(_, s)| s.1).sum() +} + /// The process's address space, walked (`VirtualQuery`): its committed private memory outside /// the unified-memory block by allocation, the largest ones, and the rest by size; mapped and /// image memory. What `snapshot`'s "other" holds, for finding its owner (the title's heaps, the -/// driver's, XCL's). +/// driver's, XCL's). Then how much of each is in RAM, by a sample (`SAMPLE`), and the private +/// allocations with the most there. pub fn walk_line() -> String { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_IMAGE, MEM_MAPPED, MEM_PRIVATE}; let u = crate::gpu::uma::get(); let t0 = std::time::Instant::now(); let (mut uma, mut mapped, mut image, mut regions) = (0u64, 0u64, 0u64, 0usize); + // (address, bytes it stands for), what it is, its allocation + let mut samples: Vec<(usize, u64)> = Vec::new(); + let mut sample_of: Vec<(Kind2, usize)> = Vec::new(); let mut by_base: std::collections::HashMap = std::collections::HashMap::new(); let mut at = 0x1_0000usize; while at < 0x7FFF_FFFE_0000 { @@ -191,6 +216,22 @@ pub fn walk_line() -> String { let (base, size) = (m.BaseAddress as usize, m.RegionSize); if m.State == MEM_COMMIT { let n = size as u64; + let kind = if u.is_some_and(|u| u.contains(base)) { + if u.is_some_and(|u| u.is_sparse(base)) { Kind2::Sparse } else { Kind2::Coherent } + } else if m.Type == MEM_PRIVATE { + Kind2::Private + } else if m.Type == MEM_MAPPED { + Kind2::Mapped + } else { + Kind2::Image + }; + let mut a = base; + while a < base + size { + let stands_for = SAMPLE.min(base + size - a) as u64; + samples.push((a, stands_for)); + sample_of.push((kind, m.AllocationBase as usize)); + a += SAMPLE; + } if u.is_some_and(|u| u.contains(base)) { uma += n; } else if m.Type == MEM_PRIVATE { @@ -208,6 +249,33 @@ pub fn walk_line() -> String { _ => break, } } + // which of the sampled pages are in RAM + let in_ram = unsafe { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + let mut info: Vec = samples.iter().map(|s| { let mut i: PSAPI_WORKING_SET_EX_INFORMATION = std::mem::zeroed(); i.VirtualAddress = s.0 as *mut _; i }).collect(); + let bytes = (info.len() * std::mem::size_of::()) as u32; + let ok = !info.is_empty() && K32QueryWorkingSetEx(windows_sys::Win32::System::Threading::GetCurrentProcess(), info.as_mut_ptr().cast(), bytes) != 0; + let valid: Vec = info.iter().map(|i| ok && i.VirtualAttributes.Flags & 1 != 0).collect(); + valid + }; + let ram_of = |k: Kind2| resident(&samples, |i| in_ram[i] && sample_of[i].0 == k); + let mut ram_by_base: std::collections::HashMap = std::collections::HashMap::new(); + for (i, s) in samples.iter().enumerate() { + if in_ram[i] && sample_of[i].0 == Kind2::Private { + *ram_by_base.entry(sample_of[i].1).or_default() += s.1; + } + } + let mut ram_top: Vec<(usize, u64)> = ram_by_base.into_iter().collect(); + ram_top.sort_unstable_by(|a, b| b.1.cmp(&a.1)); + let ram_line = format!( + "; in RAM (one page in 16 asked): unified coherent {}, sparse {}; private elsewhere {} – most {}; mapped {}, images {}", + ram_of(Kind2::Coherent) >> 20, + ram_of(Kind2::Sparse) >> 20, + ram_of(Kind2::Private) >> 20, + ram_top.iter().take(10).map(|&(b, n)| format!("{b:#x} {}", n >> 20)).collect::>().join(", "), + ram_of(Kind2::Mapped) >> 20, + ram_of(Kind2::Image) >> 20 + ); let mut all: Vec<(usize, u64, u32, u32)> = by_base.into_iter().map(|(b, (n, r, p))| (b, n, r, p)).collect(); all.sort_unstable_by(|a, b| b.1.cmp(&a.1)); let private: u64 = all.iter().map(|a| a.1).sum(); @@ -243,13 +311,30 @@ pub fn walk_line() -> String { sizes[3].0, mb(mapped), mb(image) - ) + ) + &ram_line } #[cfg(test)] mod tests { use super::*; + /// A sample counts with the bytes it stands for when its page is in RAM; the walk's line + /// names what is there. + #[test] + fn memory_in_ram_is_the_sum_of_the_samples_whose_pages_are_there() { + let samples = [(0x1_0000usize, 0x1_0000u64), (0x2_0000, 0x1_0000), (0x3_0000, 0x4000)]; + assert_eq!(resident(&samples, |_| true), 0x2_4000); + assert_eq!(resident(&samples, |i| i != 1), 0x1_4000); + assert_eq!(resident(&samples, |_| false), 0); + // this process: memory just written is in RAM, and the line says how much is + let block = vec![1u8; 8 << 20]; + let line = walk_line(); + assert!(line.contains("in RAM (one page in 16 asked)") && line.contains("private elsewhere"), "{line}"); + let private: u64 = line.split("; in RAM").nth(1).and_then(|r| r.split("private elsewhere ").nth(1)).and_then(|r| r.split(' ').next()).and_then(|n| n.parse().ok()).expect("a number"); + assert!(private >= 8, "{private} MB of private memory in RAM with 8 MB just written: {line}"); + drop(block); + } + /// The rest of each total is its total less its parts, a part is counted on its side only, /// and the line shows every part, each total against its budget, and the rest. #[test] From 0c4fbf90ea3027e03b8fc9c4a535006428b9093c Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:19 +0100 Subject: [PATCH 255/258] D3D12.X: report the newest GPU work after device loss Track the latest submitted work along with missing completion markers. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/hle/d3d12x/alloc_pool.rs | 1 + crates/xcl/src/hle/d3d12x/culprit.rs | 89 +++++++++++++++++++++++++ 2 files changed, 90 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 914562f9f3..35ddd43aa7 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -313,6 +313,7 @@ pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { super::flight::signaled("title", key, &fence, value); // (how many PC lists that value stands for: 0 is a signal alone) super::flight::event("title lists", key as u64, value, lists.len() as u64); + super::culprit::submitted(key, value, &lists.iter().map(|&l| l as usize).collect::>()); for &l in lists { if let Some(&b) = s.of_list.get(&(l as usize)) { let entry = s.backings.entry(b).or_default(); diff --git a/crates/xcl/src/hle/d3d12x/culprit.rs b/crates/xcl/src/hle/d3d12x/culprit.rs index a24cf9d8ad..af72b4f200 100644 --- a/crates/xcl/src/hle/d3d12x/culprit.rs +++ b/crates/xcl/src/hle/d3d12x/culprit.rs @@ -120,6 +120,7 @@ pub unsafe fn before_dispatch(list: &ID3D12GraphicsCommandList, title_pso: usize }; m.what.insert(id, (key, format!("cs {:016x}, pipeline {pso:#x}, {size}", cs_of(title_pso, pso)))); m.order.push_back(id); + record(&mut RECORDED.lock().unwrap(), key, id); if m.order.len() > REMEMBERED { let old = m.order.pop_front().unwrap(); m.what.remove(&old); @@ -129,6 +130,55 @@ pub unsafe fn before_dispatch(list: &ID3D12GraphicsCommandList, title_pso: usize id } +/// The dispatches numbered on each PC list since its last submit (`submitted` takes them). +static RECORDED: Mutex>>> = Mutex::new(None); +/// The newest submits of title queues: (queue, its value after the submit, each list with the +/// dispatches numbered on it). A stalled queue's first value not done names the lists the GPU +/// is in, and the markers alone do not: a list whose dispatches are all done can still be the +/// one that does not end (a copy, a clear, a barrier that waits for an earlier shader). +static SUBMITS: Mutex)>)>> = Mutex::new(VecDeque::new()); +/// Submits remembered, and the dispatches remembered of one list's recording. +const SUBMITS_KEPT: usize = 128; +const LIST_DISPATCHES_KEPT: usize = 1024; + +fn record(recorded: &mut Option>>, list: usize, id: u32) { + let v = recorded.get_or_insert_with(HashMap::new).entry(list).or_default(); + if v.len() < LIST_DISPATCHES_KEPT { + v.push(id); + } +} + +/// The dispatches numbered on `lists` since their last submit, taken. +fn take_recorded(recorded: &mut Option>>, lists: &[usize]) -> Vec<(usize, Vec)> { + let Some(m) = recorded.as_mut() else { return lists.iter().map(|&l| (l, Vec::new())).collect() }; + lists.iter().map(|&l| (l, m.remove(&l).unwrap_or_default())).collect() +} + +/// A title queue's submit of `lists` (PC lists), after which the queue's fence has `value`. +pub fn submitted(queue: usize, value: u64, lists: &[usize]) { + if !enabled() { + return; + } + let taken = take_recorded(&mut RECORDED.lock().unwrap(), lists); + let mut g = SUBMITS.lock().unwrap(); + g.push_back((queue, value, taken)); + if g.len() > SUBMITS_KEPT { + g.pop_front(); + } +} + +/// What a list's pair of words says of its dispatch `id`: the list's newest number in is at or +/// past it once the work before it has started, its newest number out once it is done. +fn state_of(id: u32, in_: u32, out: u32) -> &'static str { + if out >= id { + "done" + } else if in_ >= id { + "started" + } else { + "not started" + } +} + /// Where in title memory the arguments of the indirect dispatches numbered so are (the newest /// 65 536): a hung one is logged with the group counts there. static ARGS: Mutex>> = Mutex::new(None); @@ -250,12 +300,51 @@ fn report() { crate::xlog_warn!("GPU culprit: #{id}: {s}{}", args_now(*id)); } } + // the newest submits, with what was on their lists (the first report and a device removal) + static SUBMIT_REPORTS: AtomicU32 = AtomicU32::new(0); + if SUBMIT_REPORTS.fetch_add(1, Ordering::Relaxed) >= 2 { + return; + } + let submits = SUBMITS.lock().unwrap(); + crate::xlog_warn!("GPU culprit: the newest {} submits of title queues (queue, value, lists with their dispatches):", submits.len()); + for (queue, value, lists) in submits.iter() { + let total: usize = lists.iter().map(|(_, d)| d.len()).sum(); + crate::xlog_warn!("GPU culprit: queue {queue:#x} value {value}: {} lists, {total} dispatches", lists.len()); + for (list, ids) in lists.iter().filter(|(_, d)| !d.is_empty()) { + // SAFETY: slots index the mapped buffer of SLOTS pairs + let (i, o) = m.slots.get(list).map_or((0, 0), |&s| unsafe { (std::ptr::read_volatile(m.cpu.add(s as usize * 2)), std::ptr::read_volatile(m.cpu.add(s as usize * 2 + 1))) }); + let shown: Vec = ids.iter().take(48).map(|id| format!("#{id} {} ({})", m.what.get(id).map_or("forgotten", |w| w.1.split(',').next().unwrap_or("")), state_of(*id, i, o))).collect(); + crate::xlog_warn!("GPU culprit: list {list:#x} (in #{i}, out #{o}): {}{}", shown.join(", "), if ids.len() > 48 { ", …" } else { "" }); + } + } } #[cfg(test)] mod tests { use super::*; + /// A submit takes the dispatches numbered on its lists since their last submit, and a + /// list's words say which of them the GPU has started and finished. + #[test] + fn a_submit_takes_its_lists_dispatches_and_the_words_give_their_state() { + let mut rec = None; + record(&mut rec, 0x10, 5); + record(&mut rec, 0x20, 6); + record(&mut rec, 0x10, 7); + assert_eq!(take_recorded(&mut rec, &[0x10, 0x30]), vec![(0x10, vec![5, 7]), (0x30, vec![])]); + // taken once: the list's next recording starts empty, the other list keeps its own + assert_eq!(take_recorded(&mut rec, &[0x10, 0x20]), vec![(0x10, vec![]), (0x20, vec![6])]); + assert_eq!(take_recorded(&mut None, &[0x10]), vec![(0x10, vec![])]); + // in #7, out #5: 5 is done, 7 has started, 9 has not + assert_eq!((state_of(5, 7, 5), state_of(7, 7, 5), state_of(9, 7, 5)), ("done", "started", "not started")); + // a recording never holds more than its cap + let mut rec = None; + for id in 0..(LIST_DISPATCHES_KEPT as u32 + 10) { + record(&mut rec, 1, id); + } + assert_eq!(take_recorded(&mut rec, &[1])[0].1.len(), LIST_DISPATCHES_KEPT); + } + /// Only a list whose number in is above its number out has work in flight, and the /// dispatches logged for it are its own, after the out. #[test] From 494f08b2dd2e0de24af250f177d182e1ac840791 Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:47:19 +0100 Subject: [PATCH 256/258] D3D12.X: port GPU timestamp profiling to the AMD branch Port the GPU timestamp profiler from nvidia-dev ea22791d, including submission and pipeline identification hooks. Assisted-by: Codex (exact model identifier unavailable) --- crates/xcl/src/gpu/recomp/pso.rs | 15 + crates/xcl/src/hle/d3d12x/bind.rs | 22 +- crates/xcl/src/hle/d3d12x/console_list.rs | 2 + crates/xcl/src/hle/d3d12x/gpu_profile.rs | 500 ++++++++++++++++++++++ crates/xcl/src/hle/d3d12x/list_x.rs | 1 + crates/xcl/src/hle/d3d12x/mod.rs | 1 + crates/xcl/src/hle/d3d12x/real.rs | 12 +- 7 files changed, 550 insertions(+), 3 deletions(-) create mode 100644 crates/xcl/src/hle/d3d12x/gpu_profile.rs diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index 61c3994621..1b8153ef94 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -988,6 +988,21 @@ pub fn compute_threads(blob: &[u8]) -> Option<[u32; 3]> { } } +/// A console compute shader's thread group size, whether its program is wave64 and the bytes +/// of its RDNA2 code (`XCL_GPU_PROFILE` names a program by them). None: not a console compute +/// shader. +pub fn compute_shape(blob: &[u8]) -> Option<([u32; 3], bool, usize)> { + if let Some(f) = fspx(blob) { + return Some((f.threads, super::detect_wave64(f.code), f.code.len())); + } + let sh = xbox::parse(blob)?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; + let Mode::Compute(cs) = interface(blob, &sh, f)? else { return None }; + let p = f.programs.first()?; + let code = f.data.get(p.offset..p.offset + p.len)?; + Some((cs.threads, super::detect_wave64(code), code.len())) +} + /// The HLSL and profile a console program compiles from at pipeline creation (for /// `xcl shaders --export-hlsl`: compile-time investigations outside a title). pub fn console_hlsl(blob: &[u8], stage: Stage, windows: u32, split_wave64: bool) -> Result<(String, &'static str), String> { diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index f0778abe09..3e92f23567 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -3535,13 +3535,17 @@ pub(super) unsafe extern "system" fn dispatch_mesh(this: *mut c_void, x: u32, y: } bind_two_pass_stage(this, list, pso, &tp, res_va, true)?; let m1 = super::culprit::before_dispatch(list, raw_pso, pso, [n, 1, 1]); + let t1 = super::gpu_profile::begin(this, [raw_pso, pso], super::gpu_profile::Kind::Dispatch, [n, 1, 1]); list.Dispatch(n, 1, 1); + super::gpu_profile::end(this, t1); super::culprit::after_dispatch(list, m1); emit_uav_barrier(list, Some(&res_buf)); bind_two_pass_stage(this, list, pso, &tp, res_va, false)?; // (the mesh pass: what the marker says is its groups; 0x3e2 marks a mesh draw in the log) let m2 = super::culprit::before_dispatch(list, raw_pso, pso, [n * tp.mesh_groups_per_record, 0x3e2, 1]); + let t2 = super::gpu_profile::begin(this, [raw_pso, pso], super::gpu_profile::Kind::Draw, [n * tp.mesh_groups_per_record, 1, 0]); pc_dm(this, n * tp.mesh_groups_per_record, 1, 1); + super::gpu_profile::end(this, t2); super::culprit::after_dispatch(list, m2); emit_uav_barrier(list, Some(&res_buf)); with(this, |s| { @@ -3662,7 +3666,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us bind_two_pass_stage(this, list, pso, &tp, res_va, compute)?; let (s, first) = if compute { (msig.companion_dispatch, at) } else { (sig, at + commands as u64) }; let mark = super::culprit::before_dispatch(list, raw_pso, pso, [0, 0, if compute { 1 } else { 0x3e2 }]); + let t = super::gpu_profile::begin(this, [raw_pso, pso], if compute { super::gpu_profile::Kind::IndirectDispatch } else { super::gpu_profile::Kind::IndirectDraw }, [1, 0, 0]); pc(this, s, 1, scaled.as_raw() as usize, first + k as u64 * msig.byte_stride as u64, 0, 0); + super::gpu_profile::end(this, t); super::culprit::after_dispatch(list, mark); emit_uav_barrier(list, Some(&res_buf)); } @@ -3816,7 +3822,8 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { super::culprit::indirect_args(mark, p); } - match chained_indirect( + let t = super::gpu_profile::begin(this, [raw_pso, pso], super::gpu_profile::Kind::IndirectDispatch, [max, 0, 0]); + let chained = chained_indirect( this, list, pso, @@ -3827,7 +3834,9 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us (count_buf, count_off_title, count_off), preset_io, ei, - ) { + ); + super::gpu_profile::end(this, t); + match chained { Ok(true) => { super::culprit::after_dispatch(list, mark); if super::ambient::has_compute_psos() { @@ -3907,11 +3916,13 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us if let Some((p, _)) = commands_at.filter(|&(_, n)| n >= 12) { super::culprit::indirect_args(mark, p); } + let t = super::gpu_profile::begin(this, [with(this, |s| s.pso), pso], if gfx { super::gpu_profile::Kind::IndirectDraw } else { super::gpu_profile::Kind::IndirectDispatch }, [max, 0, 0]); if guarded.is_some() && count_buf == 0 { pc(this, sig, max, args, args_off, count_buf, count_off); } else { fresh_indirect_arguments(this, || pc(this, sig, max, args, args_off, count_buf, count_off)) } + super::gpu_profile::end(this, t); super::culprit::after_dispatch(list, mark); if compute { if super::ambient::has_compute_psos() { @@ -4180,7 +4191,9 @@ pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: return; } super::list_x::sync_title_buffers(this, None, first_vertex, vertices, if first_instance != 0 { instances.max(2) } else { instances }); + let t = super::gpu_profile::begin(this, [with(this, |s| s.pso), 0], super::gpu_profile::Kind::Draw, [vertices, instances, 0]); list.DrawInstanced(vertices, instances, first_vertex, first_instance); + super::gpu_profile::end(this, t); if super::ambient::has_sky_psos() { let pso = pso_for_draw(with(this, |s| s.pso)); super::ambient::after_draw(this, pso); @@ -4226,7 +4239,10 @@ pub(super) unsafe fn emit_prepared_indexed_draw( base_vertex: i32, first_instance: u32, ) { + let this = list.as_raw(); + let t = super::gpu_profile::begin(this, [with(this, |s| s.pso), 0], super::gpu_profile::Kind::Draw, [indices, instances, 0]); list.DrawIndexedInstanced(indices, instances, first_index, base_vertex, first_instance); + super::gpu_profile::end(this, t); } /// The pipeline a draw (or an ExecuteIndirect) uses now: both graphics and compute pipelines wait @@ -4746,7 +4762,9 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis let (limit, [x, y, z]) = fold(x, y, z); bind_abi(this, list, pso, false, limit, None)?; let mark = super::culprit::before_dispatch(list, with(this, |s| s.pso), pso, [x, y, z]); + let t = super::gpu_profile::begin(this, [with(this, |s| s.pso), pso], super::gpu_profile::Kind::Dispatch, [x, y, z]); let r = super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z]); + super::gpu_profile::end(this, t); super::culprit::after_dispatch(list, mark); if super::ambient::has_compute_psos() { let (layout, args, view_heap) = with(this, |s| (s.layout.clone(), s.args.clone(), s.heaps[0])); diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index ebca17dc6e..32050ff68d 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -1036,7 +1036,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; list.SetPipelineState(pc); let mark = super::culprit::before_dispatch(&list, (*p).pc, real, [x, y, z]); + let t = super::gpu_profile::begin(list.as_raw(), [(*p).pc, real], super::gpu_profile::Kind::Dispatch, [x, y, z]); let r = super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z]); + super::gpu_profile::end(list.as_raw(), t); super::culprit::after_dispatch(&list, mark); r?; out.dispatches += 1; diff --git a/crates/xcl/src/hle/d3d12x/gpu_profile.rs b/crates/xcl/src/hle/d3d12x/gpu_profile.rs new file mode 100644 index 0000000000..85544c7629 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/gpu_profile.rs @@ -0,0 +1,500 @@ +//! `XCL_GPU_PROFILE=1`: the GPU time each console program takes. +//! +//! Each draw, dispatch and ExecuteIndirect of console code gets a timestamp query on its PC +//! list right before it and one right after it, and the pair is resolved into a readback buffer +//! right behind them. The resolve waits on the GPU for the op to finish, so with the profile on +//! a queue runs its ops one after the other. Nothing on the CPU waits for them: a reporter thread looks at the pairs +//! every 100 ms, adds the ones the GPU has written to their program, and every 2 s logs the 15 +//! programs that took the most GPU time in those 2 s (every 20 s: since the start), with their +//! calls, longest call, group counts and, for compute, thread group size, wave size and code size. +//! +//! A pair measures the GPU clock between the two stamps (ticks of a title queue's +//! `GetTimestampFrequency`): the time the op held its queue. Queues run on the GPU at the same +//! time, so the time of ops that overlap is counted for each of them, and the sum over programs +//! can exceed the wall time. The driver decides when a stamp is taken relative to the work +//! around it. Bundles get no stamps (no queries in bundles), and a recording that runs again +//! without a Reset is counted once. + +use std::collections::HashMap; +use std::ffi::c_void; +use std::mem::{offset_of, size_of, transmute}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{LazyLock, Mutex}; +use std::time::{Duration, Instant}; + +use windows::core::{Interface, HRESULT}; +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC; + +use super::real; + +/// begin / end pairs in flight (a ring): two queries and 16 readback bytes each +const PAIRS: usize = 1 << 17; +/// programs a log names +const TOP: usize = 15; +const POLL: Duration = Duration::from_millis(100); +const WINDOW: Duration = Duration::from_secs(2); +/// windows between two logs of the totals since the start +const SINCE_START_EVERY: u32 = 10; + +pub(super) fn on() -> bool { + static ON: LazyLock = LazyLock::new(|| std::env::var("XCL_GPU_PROFILE").is_ok_and(|v| v.trim() == "1")); + *ON +} + +/// The op a pair times. +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(super) enum Kind { + Dispatch, + /// an ExecuteIndirect of dispatches with a translated pipeline + IndirectDispatch, + Draw, + /// an ExecuteIndirect of draws with a translated pipeline + IndirectDraw, + /// an ExecuteIndirect with a PC pipeline + PcIndirect, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::Dispatch => "Dispatch", + Kind::IndirectDispatch => "ExecuteIndirect (dispatches)", + Kind::Draw => "draw", + Kind::IndirectDraw => "ExecuteIndirect (draws)", + Kind::PcIndirect => "ExecuteIndirect with a PC pipeline", + } + } +} + +/// A program: the kind of op and its console shaders, (CS, 0) or (VS, PS); (0, 0): none known. +type Key = (Kind, u64, u64); + +struct Op { + key: Key, + /// a dispatch's groups, a draw's (vertices or indices, instances, 0), an ExecuteIndirect's + /// (max count, 0, 0) + size: [u32; 3], +} + +#[derive(Default, Clone, Debug, PartialEq)] +struct Total { + calls: u64, + ticks: u64, + /// ticks of the longest call, and its size + max: u64, + size: [u32; 3], +} + +/// What a pair of readback words holds. +#[derive(Debug, PartialEq)] +enum Stamps { + /// not both written yet + Pending, + /// the end before the begin: the GPU wrote an earlier op's pair over the slot + Bad, + Span(u64), +} + +fn stamps(begin: u64, end: u64) -> Stamps { + match (begin, end) { + (0, _) | (_, 0) => Stamps::Pending, + (b, e) if e < b => Stamps::Bad, + (b, e) => Stamps::Span(e - b), + } +} + +fn add(totals: &mut HashMap, key: Key, ticks: u64, size: [u32; 3]) { + let t = totals.entry(key).or_default(); + t.calls += 1; + t.ticks += ticks; + if ticks >= t.max { + t.max = ticks; + t.size = size; + } +} + +/// The `n` programs of `totals` with the most ticks, most first. +fn top(totals: &HashMap, n: usize) -> Vec<(Key, Total)> { + let mut v: Vec<(Key, Total)> = totals.iter().map(|(k, t)| (*k, t.clone())).collect(); + v.sort_by(|a, b| b.1.ticks.cmp(&a.1.ticks).then(b.1.calls.cmp(&a.1.calls)).then((a.0 .1, a.0 .2).cmp(&(b.0 .1, b.0 .2)))); + v.truncate(n); + v +} + +/// A console compute program as its pipeline was made. +#[derive(Clone, Copy)] +struct Shape { + threads: [u32; 3], + wave64: bool, + /// run as two 32-lane halves (`docs/wave64-on-wave32.md`) + split: bool, + code: usize, + dxil: usize, +} + +/// console CS hash → its shape +static SHAPES: Mutex>> = Mutex::new(None); + +/// A translated compute pipeline of console shader `blob` (hash `hash`, `dxil` bytes of DXIL) +/// was made, on a device that runs wave64 programs split (`split_device`). +pub(super) fn note_compute(hash: u64, blob: &[u8], dxil: usize, split_device: bool) { + if !on() { + return; + } + let mut g = SHAPES.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + if m.contains_key(&hash) { + return; + } + if let Some((threads, wave64, code)) = crate::gpu::recomp::pso::compute_shape(blob) { + m.insert(hash, Shape { threads, wave64, split: wave64 && split_device, code, dxil }); + } +} + +/// ticks a second of the title queues' timestamps (0: no queue seen yet) +static FREQUENCY: AtomicU64 = AtomicU64::new(0); + +/// `queue` (a title queue) executes lists: its timestamp frequency converts the pairs' ticks. +pub(super) unsafe fn note_queue(queue: *mut c_void) { + if !on() || queue.is_null() || FREQUENCY.load(Ordering::Relaxed) != 0 { + return; + } + const SLOT: usize = offset_of!(ID3D12CommandQueue_Vtbl, GetTimestampFrequency) / size_of::(); + let f: unsafe extern "system" fn(*mut c_void, *mut u64) -> HRESULT = transmute(pc_fn(queue, SLOT)); + let mut hz = 0u64; + if f(queue, &mut hz).is_ok() && hz != 0 && FREQUENCY.swap(hz, Ordering::Relaxed) == 0 { + crate::xlog_info!("D3D12.X: XCL_GPU_PROFILE: GPU timestamps at {hz} Hz"); + } +} + +struct Profile { + _heap: ID3D12QueryHeap, + _buf: ID3D12Resource, + heap: usize, + buf: usize, + /// the readback buffer's mapping: two u64 a pair + words: usize, + next: usize, + ops: Vec>, + in_flight: usize, + window: HashMap, + since_start: HashMap, + /// pairs taken again before the GPU wrote them, and pairs the GPU wrote out of order + lost: u64, + bad: u64, +} + +// SAFETY: the readback mapping lives as long as `_buf`; D3D12 objects are free-threaded. +unsafe impl Send for Profile {} + +static STATE: Mutex> = Mutex::new(None); + +unsafe fn init(dev: &ID3D12Device) -> Option { + let mut heap: Option = None; + let desc = D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: 2 * PAIRS as u32, NodeMask: 0 }; + if let Err(e) = dev.CreateQueryHeap(&desc, &mut heap) { + crate::xlog_warn!("D3D12.X: XCL_GPU_PROFILE: no timestamp query heap ({e})"); + return None; + } + let heap = heap?; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: (PAIRS * 16) as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }; + let props = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let mut buf: Option = None; + if let Err(e) = dev.CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut buf) { + crate::xlog_warn!("D3D12.X: XCL_GPU_PROFILE: no readback buffer ({e})"); + return None; + } + let buf = buf?; + let mut p = std::ptr::null_mut(); + buf.Map(0, None, Some(&mut p)).ok()?; + std::ptr::write_bytes(p.cast::(), 0, PAIRS * 16); + let _ = std::thread::Builder::new().name("xcl-gpu-profile".into()).spawn(|| { + let (mut last, mut windows) = (Instant::now(), 0u32); + loop { + std::thread::sleep(POLL); + poll(); + if last.elapsed() >= WINDOW && report(last.elapsed(), (windows + 1) % SINCE_START_EVERY == 0) { + windows += 1; + last = Instant::now(); + } + } + }); + crate::xlog_info!("D3D12.X: XCL_GPU_PROFILE: draws, dispatches and ExecuteIndirects of console code are timed on the GPU; the programs that take the most GPU time are logged every 2 s"); + Some(Profile { + heap: heap.as_raw() as usize, + buf: buf.as_raw() as usize, + _heap: heap, + _buf: buf, + words: p as usize, + next: 0, + ops: (0..PAIRS).map(|_| None).collect(), + in_flight: 0, + window: HashMap::new(), + since_start: HashMap::new(), + lost: 0, + bad: 0, + }) +} + +/// The profile, made on first use with `dev` (outside the lock: the device calls go through +/// XCL's hooks). +fn with_state(dev: impl FnOnce() -> Option, f: impl FnOnce(&mut Profile) -> R) -> Option { + static INIT: std::sync::Once = std::sync::Once::new(); + if !INIT.is_completed() { + let dev = dev()?; + INIT.call_once(|| { + let s = unsafe { init(&dev) }; + *STATE.lock().unwrap() = s; + }); + } + STATE.lock().unwrap().as_mut().map(f) +} + +impl Profile { + fn word(&self, i: usize) -> &AtomicU64 { + unsafe { &*(self.words as *const AtomicU64).add(i) } + } +} + +/// The PC method in `slot` of `obj` (an adopted object's own, not XCL's console-layout entry). +unsafe fn pc_fn(obj: *mut c_void, slot: usize) -> usize { + if real::is_adopted(obj) { + real::orig_fn(obj, slot) + } else { + *(*(obj as *const *const usize)).add(slot) + } +} + +type EndQueryFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32); +type ResolveFn = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); + +/// The begin stamp of an op on a list: `end` records the end stamp and the resolve. +pub(super) struct Pair { + k: u32, + heap: usize, + buf: usize, + end_query: EndQueryFn, + resolve: ResolveFn, +} + +/// The console shaders of the first of `psos` that has any (each also as the pipeline it +/// stands for while a build is behind it): the title's pointer and the one bound on the PC. +fn shaders_of(psos: [usize; 2]) -> (u64, u64) { + psos.iter().filter(|&&p| p != 0).flat_map(|&p| [p, super::pso_async::resolve(p)]).find_map(real::pso_shaders).unwrap_or((0, 0)) +} + +/// A compute pipeline the title made (`desc`: its description): its console CS, for the log. +pub(super) unsafe fn note_title_compute(pso: usize, desc: *const c_void, split_device: bool) { + if !on() || pso == 0 || !crate::gpu::shader::readable(desc as usize, size_of::()) { + return; + } + let d = std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC); + let (p, n) = (d.CS.pShaderBytecode as usize, d.CS.BytecodeLength); + if p == 0 || n == 0 || !crate::gpu::shader::readable(p, n) { + return; + } + let blob = std::slice::from_raw_parts(p as *const u8, n); + let hash = crate::gpu::shader::fnv64(blob); + real::note_pso_shaders(pso, (hash, 0)); + // (the DXIL's size is not known here: the pipeline may come from the library) + note_compute(hash, blob, 0, split_device); +} + +/// Before the PC call of an op of console code on `list` (`psos`: its pipeline as the title +/// holds it and as bound on the PC list, 0 for one not known). +pub(super) unsafe fn begin(list: *mut c_void, psos: [usize; 2], kind: Kind, size: [u32; 3]) -> Option { + if !on() || list.is_null() { + return None; + } + const GET_TYPE: usize = offset_of!(ID3D12CommandList_Vtbl, GetType) / size_of::(); + const END_QUERY: usize = offset_of!(ID3D12GraphicsCommandList_Vtbl, EndQuery) / size_of::(); + const RESOLVE: usize = offset_of!(ID3D12GraphicsCommandList_Vtbl, ResolveQueryData) / size_of::(); + let get_type: unsafe extern "system" fn(*mut c_void) -> D3D12_COMMAND_LIST_TYPE = transmute(pc_fn(list, GET_TYPE)); + let ty = get_type(list); + if ty != D3D12_COMMAND_LIST_TYPE_DIRECT && ty != D3D12_COMMAND_LIST_TYPE_COMPUTE { + return None; + } + let (a, b) = shaders_of(psos); + let key = (kind, a, b); + let (k, heap, buf) = with_state( + || { + let mut dev: Option = None; + ID3D12GraphicsCommandList::from_raw_borrowed(&list)?.GetDevice(&mut dev).ok()?; + dev + }, + |s| { + let k = s.next; + s.next = (k + 1) % PAIRS; + if s.ops[k].is_some() { + s.lost += 1; + } else { + s.in_flight += 1; + } + s.word(2 * k).store(0, Ordering::Release); + s.word(2 * k + 1).store(0, Ordering::Release); + s.ops[k] = Some(Op { key, size }); + (k as u32, s.heap, s.buf) + }, + )?; + let pair = Pair { k, heap, buf, end_query: transmute(pc_fn(list, END_QUERY)), resolve: transmute(pc_fn(list, RESOLVE)) }; + (pair.end_query)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * k); + Some(pair) +} + +/// After the PC call of the op `begin` gave `pair` for. +pub(super) unsafe fn end(list: *mut c_void, pair: Option) { + let Some(p) = pair else { return }; + (p.end_query)(list, p.heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * p.k + 1); + (p.resolve)(list, p.heap, D3D12_QUERY_TYPE_TIMESTAMP, 2 * p.k, 2, p.buf, 16 * p.k as u64); +} + +/// Add the pairs the GPU has written to their programs. +fn poll() { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + let mut left = s.in_flight; + for k in 0..PAIRS { + if left == 0 { + break; + } + let Some(op) = &s.ops[k] else { continue }; + left -= 1; + let span = match stamps(s.word(2 * k).load(Ordering::Acquire), s.word(2 * k + 1).load(Ordering::Acquire)) { + Stamps::Pending => continue, + Stamps::Bad => None, + Stamps::Span(t) => Some(t), + }; + let (key, size) = (op.key, op.size); + match span { + Some(t) => { + add(&mut s.window, key, t, size); + add(&mut s.since_start, key, t, size); + } + None => s.bad += 1, + } + s.ops[k] = None; + s.in_flight -= 1; + } +} + +fn program(key: Key, shapes: &HashMap) -> String { + let (kind, a, b) = key; + match kind { + Kind::Dispatch | Kind::IndirectDispatch => { + let shape = shapes.get(&a).map_or(String::new(), |s| { + format!( + "; {}x{}x{} threads, {}, {} B code, {} B DXIL", + s.threads[0], + s.threads[1], + s.threads[2], + if s.split { "wave64 split in halves" } else if s.wave64 { "wave64" } else { "wave32" }, + s.code, + s.dxil + ) + }); + format!("CS {a:016x} {}{shape}", kind.name()) + } + Kind::Draw | Kind::IndirectDraw if a != 0 => format!("VS {a:016x} PS {b:016x} {}", kind.name()), + Kind::Draw | Kind::IndirectDraw => format!("{} with no console shader known", kind.name()), + Kind::PcIndirect => kind.name().to_owned(), + } +} + +fn size_text(kind: Kind, size: [u32; 3]) -> String { + match kind { + Kind::Dispatch => format!("{}x{}x{} groups", size[0], size[1], size[2]), + Kind::Draw => format!("{} vertices or indices x {} instances", size[0], size[1]), + Kind::IndirectDispatch | Kind::IndirectDraw | Kind::PcIndirect => format!("max count {} (its counts are the GPU's)", size[0]), + } +} + +/// Calls and ticks of `totals`, summed. +fn sums(totals: &HashMap) -> (u64, u64) { + totals.values().fold((0, 0), |(n, ticks), t| (n + t.calls, ticks + t.ticks)) +} + +/// Log the programs that took the most GPU time in the last `elapsed` (and since the start). +/// False: nothing logged (no queue's timestamp frequency yet); the window goes on. +fn report(elapsed: Duration, since_start: bool) -> bool { + let hz = FREQUENCY.load(Ordering::Relaxed); + if hz == 0 { + return false; + } + let (window, all, in_flight, lost, bad) = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return false }; + let all = since_start.then(|| (top(&s.since_start, TOP), sums(&s.since_start))); + (std::mem::take(&mut s.window), all, s.in_flight, s.lost, s.bad) + }; + let ms = |ticks: u64| ticks as f64 * 1000.0 / hz as f64; + let shapes = SHAPES.lock().unwrap().clone().unwrap_or_default(); + let lines = |what: &str, totals: Vec<(Key, Total)>, (ops, ticks): (u64, u64)| { + crate::xlog_info!( + "D3D12.X: XCL_GPU_PROFILE: {what}: {:.1} ms of GPU time in {ops} op(s) of console code ({in_flight} in flight, {lost} lost, {bad} out of order); the {} that took most:", + ms(ticks), + totals.len() + ); + for (i, ((kind, a, b), t)) in totals.into_iter().enumerate() { + crate::xlog_info!( + "D3D12.X: XCL_GPU_PROFILE: {:>2}. {:>9.1} ms {}: {} call(s), longest {:.1} ms ({})", + i + 1, + ms(t.ticks), + program((kind, a, b), &shapes), + t.calls, + ms(t.max), + size_text(kind, t.size) + ); + } + }; + if !window.is_empty() { + lines(&format!("last {:.1} s", elapsed.as_secs_f64()), top(&window, TOP), sums(&window)); + } + if let Some((all, sum)) = all { + lines("since the start", all, sum); + } + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pair_counts_once_both_stamps_are_written_and_in_order() { + assert_eq!(stamps(0, 0), Stamps::Pending); + // (the resolve's copy can be seen half done) + assert_eq!(stamps(1_000, 0), Stamps::Pending); + assert_eq!(stamps(0, 1_000), Stamps::Pending); + assert_eq!(stamps(2_000, 1_000), Stamps::Bad); + assert_eq!(stamps(1_000, 1_000), Stamps::Span(0)); + assert_eq!(stamps(1_000, 4_500), Stamps::Span(3_500)); + } + + #[test] + fn programs_are_ranked_by_their_total_and_keep_their_longest_call() { + let mut t = HashMap::new(); + let (a, b, c) = ((Kind::Dispatch, 0xA, 0), (Kind::IndirectDispatch, 0xB, 0), (Kind::Draw, 0xC, 0xD)); + add(&mut t, a, 10, [1, 1, 1]); + add(&mut t, a, 30, [8, 4, 1]); + add(&mut t, a, 20, [2, 1, 1]); + add(&mut t, b, 100, [1, 0, 0]); + add(&mut t, c, 5, [3, 1, 0]); + let r = top(&t, 2); + assert_eq!(r.len(), 2); + assert_eq!(r[0], (b, Total { calls: 1, ticks: 100, max: 100, size: [1, 0, 0] })); + assert_eq!(r[1], (a, Total { calls: 3, ticks: 60, max: 30, size: [8, 4, 1] })); + // the same op with the same program under two kinds stays two programs + add(&mut t, (Kind::IndirectDispatch, 0xA, 0), 1, [1, 0, 0]); + assert_eq!(top(&t, 10).len(), 4); + } +} diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 7330c2e324..b33bdc873f 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -4098,6 +4098,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { // (a submit as `ExecuteCommandLists` is, for `prof`: the refresh, the waits and the driver) let _prof = super::prof::span(super::prof::Kind::Submit); super::title_textures::refresh(q_raw); + super::gpu_profile::note_queue(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index ccc7c443dc..5a6c39b3bb 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -22,6 +22,7 @@ mod cpu_writes; pub mod dred; pub mod driver_crash; mod fence_x; +mod gpu_profile; mod format_alias; pub mod frame; pub mod flight; diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index cd587c32f3..e1d953efb2 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -2204,6 +2204,11 @@ pub fn pso_shaders(pso: usize) -> Option<(u64, u64)> { PSO_SHADERS.read().unwrap().as_ref()?.get(&pso).copied() } +/// The console shaders of pipeline `pso` ((CS, 0) or (VS, PS)), for `XCL_GPU_PROFILE`. +pub(super) fn note_pso_shaders(pso: usize, shaders: (u64, u64)) { + PSO_SHADERS.write().unwrap().get_or_insert_with(HashMap::new).insert(pso, shaders); +} + pub fn is_translated_graphics(pso: usize) -> bool { pso != 0 && TRANSLATED_GRAPHICS.read().unwrap().as_ref().is_some_and(|s| s.contains(&pso)) } @@ -6844,7 +6849,7 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); - if super::present::trace_frame() { + if super::present::trace_frame() || super::gpu_profile::on() { PSO_SHADERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps_hash)); } if n < 5 || n % 1000 == 0 { @@ -6946,6 +6951,9 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const super::ambient::note_graphics_pso(*ppv as usize, shader_bytes(&d.PS)); TRANSLATED_GRAPHICS.write().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); note_rect_list_gs(*ppv as usize, ©, rect_gs.is_some()); + if super::gpu_profile::on() && !super::present::trace_frame() { + note_pso_shaders(*ppv as usize, (crate::gpu::shader::fnv64(vs), shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64))); + } if super::present::trace_frame() { let ps = shader_bytes(&d.PS).map_or(0, crate::gpu::shader::fnv64); PSO_SHADERS.write().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (crate::gpu::shader::fnv64(vs), ps)); @@ -7533,6 +7541,7 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const let hr = create_compute_pso(this, desc, riid, ppv); if hr >= 0 && !ppv.is_null() { super::culprit::note_compute(*ppv as usize, desc); + super::gpu_profile::note_title_compute(*ppv as usize, desc, wave32_only(this)); } hr } @@ -9671,6 +9680,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis super::vram::wait_pending_mappings(q); } super::list_x::note_queue_for_lists(this as usize, &mapped); + super::gpu_profile::note_queue(this); super::list_x::execute_with_waits_on(this, &mapped, |chunk| { // a list still on the GPU from its previous submit: that one first (the PC does not take // a list again before then) From 7c795f5eefa0661eaf3f9f696d0cba3a75ce9628 Mon Sep 17 00:00:00 2001 From: ivall Date: Fri, 27 Nov 2026 12:55:49 +0100 Subject: [PATCH 257/258] Docs: relicense XCL to GPL-3.0-or-later (#3002) XCL moves from GPL-2.0-only to GPL-3.0-or-later so that code can move between XCL and GPL-3.0 projects (VIctory and its forks) in both directions. - LICENSE: the GPL-3.0 text from gnu.org; Cargo.toml: GPL-3.0-or-later. - README, CONTRIBUTING, AGENTS, SECURITY: the new licence and the GPL-3.0 compatibility rule for dependencies. - THIRD_PARTY.md: the GPL-3.0-compatible licence list; VIctory is used under its own GPL-3.0; AnyPS5 is listed as a reference only. - AnyPS5 was read as a description of the hardware behaviour (MIMG A16 address layout, 16-bit VALU halves), no code was taken from it: the two comments in recomp/emit.rs that said "ported" now say so. - Headers of the VIctory and FFmpeg ports no longer name GPL-2.0-only. No code change. (cherry picked from commit 06f90c1986f43698d0405eff3c2ab0af230e1ed9) --- AGENTS.md | 2 +- CONTRIBUTING.md | 5 +- Cargo.toml | 2 +- LICENSE | 898 ++++++++++++++++++--------- README.md | 6 +- SECURITY.md | 2 +- THIRD_PARTY.md | 17 +- crates/xcl/src/gpu/recomp/emit.rs | 5 +- crates/xcl/src/hle/bcpack/victory.rs | 3 +- crates/xcl/src/hle/xma2/mod.rs | 2 +- crates/xcl/src/hle/xma2/tables.rs | 2 +- 11 files changed, 641 insertions(+), 303 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 88ef1e71b0..d2a9bddc04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -90,7 +90,7 @@ test counts by hand. - Commit game data, game dumps, console SDK headers or binaries, keys, or anything for getting around DRM. - Port code from WinDurango (LGPL-3.0, reference only) or add a dependency that is not - GPL-2.0-compatible. + GPL-3.0-compatible. - Edit generated files (`*_spec.rs`, generated tables) by hand: change the generator in `scripts/` and rerun it. - Rewrite `HANDOFF.md` or `docs/specs/` as part of a feature change. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dfdd78a9ec..dd79a02cda 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -155,9 +155,10 @@ and pure renames need no test. ## Licence and provenance -XCL is **GPL-2.0-only**. +XCL is **GPL-3.0-or-later**. -- Dependencies must be GPL-2.0-compatible (no Apache-2.0-only, no GPL-3.0). New dependencies need a +- Dependencies must be GPL-3.0-compatible (no GPL-2.0-only, no proprietary licences); the list + is in `THIRD_PARTY.md`. New dependencies need a reason in the PR description; avoid them for a few lines of code. - Code ported or adapted from another project needs a provenance note in the file (project, URL, licence) and an entry in `THIRD_PARTY.md` when it is new. diff --git a/Cargo.toml b/Cargo.toml index 94e3a9a941..04dbd3b62f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/xcl", "tests/testtitle", "tests/testgamedll"] [workspace.package] version = "0.1.0" edition = "2021" -license = "GPL-2.0-only" +license = "GPL-3.0-or-later" # Keep full symbols in optimized alpha builds so release-only crashes can be # resolved to functions, files, and lines without a separate diagnostic build. diff --git a/LICENSE b/LICENSE index a66a55f980..f288702d2f 100644 --- a/LICENSE +++ b/LICENSE @@ -1,281 +1,622 @@ GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + Version 3, 29 June 2007 - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - + Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. END OF TERMS AND CONDITIONS @@ -287,15 +628,15 @@ free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least +state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) - This program is free software; you can redistribute it and/or modify + This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or + the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, @@ -303,36 +644,31 @@ the "copyright" line and a pointer to where the full notice is found. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License along - with this program; if not, see . + You should have received a copy of the GNU General Public License + along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Moe Ghoul, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. \ No newline at end of file +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index cca98fa410..df63c68d6c 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@

Discord: join the server CI - License: GPL-2.0-only + License: GPL-3.0-or-later Windows 10 / 11 x64 Direct3D 12, Shader Model 6.6 Rust @@ -372,8 +372,8 @@ questions and talk to the [Discord server](https://discord.gg/xcl). ## Licenses -**GPL-2.0-only** (`LICENSE`); third-party sources: `THIRD_PARTY.md` (including AMD's -machine-readable ISA, AMD addrlib swizzle patterns, LLVM disassembler tests, AnyPS5, +**GPL-3.0-or-later** (`LICENSE`); third-party sources: `THIRD_PARTY.md` (including AMD's +machine-readable ISA, AMD addrlib swizzle patterns, LLVM disassembler tests, VIctory, FFmpeg, libHttpClient headers). WinDurango serves only as a reference – no code is ported from it. The repository contains no headers or binaries from the console SDK. diff --git a/SECURITY.md b/SECURITY.md index b7486468e7..d649089d77 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -32,5 +32,5 @@ Bugs that only crash the game, or need online services XCL doesn't provide, are ## No warranty -XCL is GPL-2.0 and comes with no warranty (see `LICENSE`). Reports are handled when someone has +XCL is GPL-3.0-or-later and comes with no warranty (see `LICENSE`). Reports are handled when someone has time; there is no fixed response time. diff --git a/THIRD_PARTY.md b/THIRD_PARTY.md index 9868e34549..db38e8a443 100644 --- a/THIRD_PARTY.md +++ b/THIRD_PARTY.md @@ -1,16 +1,16 @@ # XCL third-party sources -XCL is licensed under **GPL-2.0-only** (`LICENSE`). Below is everything that comes from outside, +XCL is licensed under **GPL-3.0-or-later** (`LICENSE`). Below is everything that comes from outside, together with its license and how it is used. Files that contain logic ported from another project -carry a note in their header about its origin and the date of changes (GPL-2.0 §2a requirement). +carry a note in their header about its origin and the date of changes (GPL-3.0 §5a requirement). | Source | License | What in XCL | How | |---|---|---|---| -| [AnyPS5](https://github.com/boykopovar/AnyPS5) | GPL-2.0-only | recompiler (`crates/xcl/src/gpu/recomp/`) – portions of logic marked in the files | port to Rust/HLSL with annotation | +| [AnyPS5](https://github.com/boykopovar/AnyPS5) | GPL-2.0-only | no code; read as a description of RDNA behaviour (descriptor fields, MIMG A16 address layout, 16-bit VALU halves), which the recompiler (`crates/xcl/src/gpu/recomp/`) implements independently | reference only | | [FFmpeg](https://ffmpeg.org/) | LGPL-2.1+ | XMA1/XMA2 decoder and tables (`crates/xcl/src/hle/xma2/`) – after `libavcodec/wmaprodec.c`, `wmaprodata.h`, `wma.c`, `sinewin_tablegen.h`, `libavutil/float_dsp.c`, `tx_template.c` | port to safe Rust with annotation | | [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables | | [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation | -| [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0; used in XCL under GPL-2.0-only with its author's permission (2026-11-24) | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | +| [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables | | [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts | | [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only | | [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification | @@ -19,8 +19,9 @@ carry a note in their header about its origin and the date of changes (GPL-2.0 | Rust crates (`Cargo.lock`) | MIT / BSD-2 / Zlib / Unlicense (or with an MIT alternative) | build dependencies | statically linked | | [libopus](https://opus-codec.org/) (`opus.dll`) | BSD-3-Clause | Opus decoding where Windows has no `MSOpusDecoder.dll` (Wine): loaded at runtime from `%XCL_OPUS_DIR%` / next to xcl.exe (`hle/opus.rs`) | **not** distributed with XCL | | DXC (`dxcompiler.dll`, `dxil.dll`) from the Windows SDK | NCSA (dxcompiler) / Microsoft (dxil) | HLSL → DXIL compilation at runtime | loaded from the user's SDK, **not** distributed with XCL | -| Windows system libraries (d3d12, dxgi, xaudio2_9, mfplat, MSOpusDecoder, ole32 …) | system | target APIs | GPL-2.0 "system library" exception | +| Windows system libraries (d3d12, dxgi, xaudio2_9, mfplat, MSOpusDecoder, ole32 …) | system | target APIs | GPL-3.0 "System Libraries" (§1) | -When adding dependencies: compatible with GPL-2.0-only are MIT, BSD, Zlib, ISC, Unlicense, LGPL-2.1(+), -GPL-2.0(+), MPL-2.0 (via its Secondary License clause). Incompatible: Apache-2.0 without an alternative, -GPL-3.0, LGPL-3.0, AGPL. +When adding dependencies: compatible with GPL-3.0-or-later are MIT, BSD, Zlib, ISC, Unlicense, +Apache-2.0, LGPL-2.1(+), LGPL-3.0(+), GPL-2.0-or-later, GPL-3.0(+), MPL-2.0. Incompatible: GPL-2.0-only, +proprietary licences. AGPL-3.0 can be combined +(§13) but its terms would cover the combination: ask first. diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 379d4e014a..71f0847cde 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -2542,7 +2542,8 @@ impl Em { /// (UAV at +1); FORMAT (word 1 [28:20]) selects the typed view (float/uint/sint). /// Sampler descriptors (S#, 4 dwords) hold the sampler heap index in BORDER_COLOR_PTR /// (word 3 [11:0]). Address layout with A16 (16-bit bias/coordinates/lod, 32-bit offset, - /// compare and gradients) as in AnyPS5's `componentShape` (GPL-2.0, ported 2026-11-20). + /// compare and gradients) as AnyPS5's `componentShape` describes it (read + /// as a reference for the hardware behaviour; no code taken). /// `float3 {t}_o{sfx}`: an MIMG texel offset (`o`, three 6-bit signed fields) in the texture /// coordinates of mip `level` – offset / that level's size (array layers do not move). fn texel_offset(&mut self, t: &str, dim: u64, o: &str, level: &str, sfx: &str) { @@ -3552,7 +3553,7 @@ impl Em { /// 16-bit VALU (f16 / u16 / i16 / b16): sources are the low halves (VOP3 op_sel picks the /// high half per source), results go to the low half (op_sel[3]: high half) and the other - /// half is preserved – AnyPS5 `write16Bits` (GPL-2.0, ported 2026-11-20). + /// half is preserved, as AnyPS5's `write16Bits` describes it (reference only; no code taken). fn valu16(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> { let (outs, ins) = Self::ops(d); let m = Self::mods(d); diff --git a/crates/xcl/src/hle/bcpack/victory.rs b/crates/xcl/src/hle/bcpack/victory.rs index 9886e914d9..91c36d38dc 100644 --- a/crates/xcl/src/hle/bcpack/victory.rs +++ b/crates/xcl/src/hle/bcpack/victory.rs @@ -1,8 +1,7 @@ //! BCPack: lossless packing of BC1-BC7 block streams, as the console's //! DirectStorage hardware unpacks them. Decode only; BC2 is left out (no //! title data uses it). Ported from VIctory's victory-formats/src/bcpack.rs on 2026-11-23 -//! (https://github.com/Marvisak/VIctory, GPL-3.0; used here under GPL-2.0-only with its -//! author's permission, see THIRD_PARTY.md). +//! (https://github.com/Marvisak/VIctory, GPL-3.0, see THIRD_PARTY.md). //! //! A packed stream has no header. It is 12 or 16 interleaved rANS *lanes*; //! each lane is a run of fragments (header byte, length, payload) coded with diff --git a/crates/xcl/src/hle/xma2/mod.rs b/crates/xcl/src/hle/xma2/mod.rs index caf02e172a..ec9ed6b510 100644 --- a/crates/xcl/src/hle/xma2/mod.rs +++ b/crates/xcl/src/hle/xma2/mod.rs @@ -8,7 +8,7 @@ //! `libavcodec/sinewin_tablegen.h`, `libavutil/float_dsp.c`, and `libavutil/tx_template.c` //! (LGPL-2.1+, Copyright (c) 2005-2011 Balatoni Denes, Loren Merritt, Baptiste Coudurier, //! Benjamin Larsson, Ulion, Sascha Sommer, Reimar Döffinger, Lynne), adapted to safe Rust for -//! XCL (GPL-2.0-only) on 2026-11-21. +//! XCL on 2026-11-21. pub mod tables; diff --git a/crates/xcl/src/hle/xma2/tables.rs b/crates/xcl/src/hle/xma2/tables.rs index 04496ae74d..0e8bf93c78 100644 --- a/crates/xcl/src/hle/xma2/tables.rs +++ b/crates/xcl/src/hle/xma2/tables.rs @@ -2,7 +2,7 @@ //! //! Ported from FFmpeg `libavcodec/wmaprodata.h` (LGPL-2.1+, Copyright (c) 2007-2009 //! Baptiste Coudurier, Benjamin Larsson, Ulion, Sascha Sommer), adapted to Rust for XCL -//! (GPL-2.0-only) on 2026-11-21. +//! on 2026-11-21. /// Critical frequencies (Hz) dividing the spectrum into scale factor bands. pub const CRITICAL_FREQ: [u16; 28] = [ From b7fc3b49b276c8495159677d8f86e13a9f3cd63c Mon Sep 17 00:00:00 2001 From: Saksukella <98151720+Saksukella@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:07:38 +0300 Subject: [PATCH 258/258] D3D12.X: coalesce sparse tile-mapping fence signals until execute Avoid signalling the sparse command queue fence after every `ensure_mapped` (`map_tiles`) call. `map_tiles` already marks `mapping_queued = true`, and `before_execute` / `wait_pending_mappings` flush a single `queue.Signal` before the next title submit, matching the batched signalling pattern used for texture page mappings (`XCL_SPARSE_SIGNAL_EACH=1` restores immediate per-commit signalling). Add `commit_range_coalesces_tile_mapping_signals_until_flush` verifying multiple `commit_range` calls coalesce into one fence signal on flush. --- crates/xcl/src/hle/d3d12x/sparse.rs | 67 +++++++++++++++++++++++++---- 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 1681f0ca32..9024c70280 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1244,7 +1244,25 @@ impl State { let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); self.map_tiles(&r, b, &tiles); } - self.signal(); + // Leave `mapping_queued = true` (set by `map_tiles`) so consecutive tile mappings coalesce + // into a single `queue.Signal` in `before_execute` / `wait_pending_mappings` instead of + // breaking every batch with a per-commit fence signal (`XCL_SPARSE_SIGNAL_EACH=1` restores + // immediate per-commit signalling). + static EACH: std::sync::OnceLock = std::sync::OnceLock::new(); + if *EACH.get_or_init(|| std::env::var("XCL_SPARSE_SIGNAL_EACH").is_ok_and(|v| v.trim() == "1")) { + self.signal(); + } + } + + /// Emit a single fence signal covering all queued tile mappings since the last signal. + #[inline] + unsafe fn flush_pending_mappings(&mut self) -> bool { + if self.mapping_queued.load(Ordering::Relaxed) { + self.signal(); + true + } else { + false + } } #[inline] @@ -2888,10 +2906,8 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: } dirty_runs.clear(); s.scratch_runs = dirty_runs; - // the tile mappings of buffers placed since the last signal (`place_buffer`) - if s.mapping_queued.load(Ordering::Relaxed) { - s.signal(); - } + // Flush all batched tile mappings queued since the last signal (`ensure_mapped` / `place_buffer`). + s.flush_pending_mappings(); let q = queue.as_raw() as usize; let waited_before = s.waited.get(&q).copied().unwrap_or(0); if s.value > 0 && waited_before < s.value { @@ -2915,9 +2931,7 @@ pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: pub(super) unsafe fn wait_pending_mappings(queue: &ID3D12CommandQueue) { let mut g = lock_state(); let Some(s) = g.as_mut() else { return }; - if s.mapping_queued.load(Ordering::Relaxed) { - s.signal(); - } + s.flush_pending_mappings(); let q = queue.as_raw() as usize; let waited_before = s.waited.get(&q).copied().unwrap_or(0); if s.value > 0 && waited_before < s.value { @@ -3673,6 +3687,7 @@ mod tests { s.commit_range(base, TILE); let tile = s.mapped[&base].pool; + assert!(s.flush_pending_mappings(), "a new tile is mapped"); let v = s.value; assert!(v > 0, "a new tile is mapped"); @@ -3859,6 +3874,7 @@ mod tests { assert_eq!(VirtualAlloc(base as *const c_void, TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); s.commit_range(base, TILE); + s.flush_pending_mappings(); s.wait_for(s.value); s.sync_sent_range(base, PAGE); let before = *s.mapped[&base].sent[0].as_deref().unwrap(); @@ -3933,6 +3949,7 @@ mod tests { let (base, mut s) = test_state_with_reserved(2); s.commit_range(base, TILE); let tile = s.mapped[&base].pool; + s.flush_pending_mappings(); s.wait_for(s.value); let gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence"); @@ -3971,6 +3988,7 @@ mod tests { s.commit_range(base, TILE); let tile = s.mapped[&base].pool; + s.flush_pending_mappings(); s.wait_for(s.value); let title_gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("title gate fence"); @@ -4019,6 +4037,7 @@ mod tests { let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); let before = com_refcount(&title_q); s.commit_range(base, TILE); + s.flush_pending_mappings(); s.wait_for(s.value); s.decommit_range(base, TILE); assert!(s.flush_parked_for(&[&title_q])); @@ -4044,6 +4063,7 @@ mod tests { let tile_a = s.mapped[&base].pool; s.commit_range(base + TILE, TILE); let tile_b = s.mapped[&(base + TILE)].pool; + s.flush_pending_mappings(); s.wait_for(s.value); s.decommit_range(base, TILE); @@ -4426,6 +4446,7 @@ mod tests { s.commit_range(base, TILE); let tile = s.mapped[&base].pool; + s.flush_pending_mappings(); s.wait_for(s.value); let v_before = s.value; @@ -4669,4 +4690,34 @@ mod tests { assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0); } } + + /// Multiple `commit_range` (`ensure_mapped`) calls leave tile mappings queued without emitting + /// per-commit fence signals; `flush_pending_mappings` (called once by `before_execute` / + /// `wait_pending_mappings`) coalesces them into a single `queue.Signal`. + #[test] + fn commit_range_coalesces_tile_mapping_signals_until_flush() { + if std::env::var("XCL_SPARSE_SIGNAL_EACH").is_ok_and(|v| v.trim() == "1") { + return; + } + unsafe { + let (base, mut s) = test_state_with_reserved(4); + let v0 = s.value; + s.commit_range(base, TILE); + s.commit_range(base + TILE, TILE); + s.commit_range(base + 2 * TILE, TILE); + assert_eq!(s.value, v0, "consecutive commit_range calls must not emit per-commit fence signals"); + assert!(s.mapping_queued.load(Ordering::Relaxed), "tile mappings must stay marked queued"); + + assert!(s.flush_pending_mappings(), "flush_pending_mappings must emit one coalesced signal"); + assert_eq!(s.value, v0 + 1, "three commit_range calls must coalesce into exactly 1 fence signal"); + assert_eq!(s.mapped_value, v0 + 1, "mapped_value must track the coalesced fence value"); + assert!(!s.mapping_queued.load(Ordering::Relaxed)); + assert!(!s.flush_pending_mappings(), "second flush with no new mappings must be a no-op"); + assert_eq!(s.value, v0 + 1); + + assert!(s.wait_for(v0 + 1), "coalesced sparse mapping fence must complete on the GPU"); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, windows_sys::Win32::System::Memory::MEM_RELEASE), 0); + } + } }