diff --git a/README.md b/README.md index e35903a1cf..5f40b90192 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder ones with `record HASH`, the console record's hash that `--measure-pso` and `--export-hlsl --record-hash` take), with whether it was gated and how long it waited; `XCL_PSO_TRACE=1` logs every driver compile. +- `XCL_DEFER_PRIVATE_HOME_TILES=1` keeps sparse physical pages used only for storage I/O + in CPU memory. When the title maps those pages at their home address, XCL allocates their + GPU tiles and uploads the stored data before the next GPU submission. Off by default. - 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. diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index 0731890bfc..4f993d0f37 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -1604,6 +1604,65 @@ pub fn forget_buffer(res: usize) { mod tests { use super::*; + #[test] + fn private_physical_pages_reach_the_gpu_on_mapping() { + // The option, device and sparse windows are process-wide. + const CHILD: &str = "XCL_TEST_PRIVATE_PHYSICAL_PAGES"; + if std::env::var_os(CHILD).is_none() { + let status = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping", "--nocapture"]) + .env(CHILD, "1") + .env("XCL_DEFER_PRIVATE_HOME_TILES", "1") + .status().unwrap(); + assert!(status.success()); + return; + } + use crate::hle::kernelx::{AllocateTitlePhysicalPages, FreeTitlePhysicalPages, MapTitlePhysicalPages, write_physical_pages}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe { + let mut device = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut device).is_err() { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + let device: ID3D12Device = device.unwrap(); + let windows = init(&device); + if windows.is_empty() { + crate::gpu::recomp::runner::skip_test("no sparse windows"); + return; + } + for (_, raw, _) in windows { drop(ID3D12Resource::from_raw(raw as *mut c_void)); } + let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let mut pages = [0usize; 3]; + let mut n = pages.len(); + let null = std::ptr::null_mut(); + assert_eq!(AllocateTitlePhysicalPages(null, 0, &mut n, pages.as_mut_ptr()), 1); + let first = vec![0xa7; TILE]; + let last = vec![0x38; TILE]; + let before = mapped_ranges(); + assert!(write_physical_pages(&pages[..1], 0, &first)); + assert!(write_physical_pages(&pages[2..], 0, &last)); + assert_eq!(mapped_ranges(), before, "storage writes allocated GPU tiles"); + + // Expose one fully CPU-backed page first, then a mixed span of all three. + let first_home = MapTitlePhysicalPages(null, 1, 0, 4, pages.as_mut_ptr()); + assert!(!first_home.is_null()); + let home = MapTitlePhysicalPages(null, n, 0, 4, pages.as_mut_ptr()) as usize; + assert_eq!(home, first_home as usize); + assert!(mapped_ranges().iter().any(|&(a, b)| a <= home && home + n * TILE <= b)); + // A prior write-watch scan may have consumed the writes before the first submit. + assert_eq!(windows_sys::Win32::System::Memory::ResetWriteWatch(home as *const c_void, n * TILE), 0); + super::super::title_textures::refresh(queue.as_raw()); + std::ptr::write_bytes(home as *mut u8, 0xdd, n * TILE); + readback_after_execute(&queue, &[(home, n * TILE)]); + let result = std::slice::from_raw_parts(home as *const u8, n * TILE); + assert_eq!(&result[..TILE], &first); + assert!(result[TILE..2 * TILE].iter().all(|&b| b == 0)); + assert_eq!(&result[2 * TILE..], &last); + assert_eq!(FreeTitlePhysicalPages(null, n, pages.as_mut_ptr()), 1); + } + } + /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`). diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ada439cbaa..492cdf493f 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -683,6 +683,12 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: } } +static INITIAL_CPU_RANGES: Mutex> = Mutex::new(Vec::new()); + +pub(crate) fn rescan_cpu_backing(start: usize, bytes: usize) { + INITIAL_CPU_RANGES.lock().unwrap().push((start, bytes)); +} + unsafe fn refresh_once(queue: *mut c_void) { let Some(u) = crate::gpu::uma::get() else { return }; let sparse = u.has_sparse(); @@ -705,7 +711,17 @@ unsafe fn refresh_once(queue: *mut c_void) { take_written(base, size, &mut buf, &mut dirty, &mut page); } }); + let watched = dirty.len(); + if *crate::hle::kernelx::DEFER_PRIVATE_HOME_TILES { + let mut initial = INITIAL_CPU_RANGES.lock().unwrap(); + for (start, size) in initial.drain(..) { + dirty.extend((start..start + size).step_by(page as usize)); + } + } dirty.sort_unstable(); + if dirty.len() > watched { + dirty.dedup(); + } dirty.len() }); super::sparse::note_watch(watch_t0.elapsed(), dirty_len); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index c0b8c236ac..b172736efc 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -803,9 +803,14 @@ static PHYS_BLOCKS: std::sync::Mutex, at: std::collections::BTreeMap, page: std::collections::HashMap, /// homes in a sparse window whose pages went away in this call, given back at its end in @@ -864,7 +869,7 @@ fn lazy_home(home: usize) -> bool { /// Resolve the live virtual addresses of the physical pages covering `offset..offset+len`. /// Caller must hold `AWAY`. -unsafe fn resolve_physical_pages(away: Option<&Away>, pages: &[usize], offset: usize, len: usize) -> Option> { +unsafe fn resolve_physical_pages(away: &mut Away, pages: &[usize], offset: usize, len: usize) -> Option> { if offset >= PHYS_PAGE { return None; } @@ -876,9 +881,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] { let home = page_home(p)?; - let addr = match away.and_then(|a| a.page.get(&p).copied()) { + let addr = match away.page.get(&p).copied() { Some(at) => at, - None => home_again(home)?, + None => home_again(home, p, away)?, }; addrs.push(addr); } @@ -892,8 +897,8 @@ pub unsafe fn read_physical_pages(pages: &[usize], offset: usize, dst: &mut [u8] if dst.is_empty() { return offset < PHYS_PAGE; } - let g = AWAY.lock().unwrap(); - let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, dst.len()) else { return false }; + let mut g = AWAY.lock().unwrap(); + let Some(addrs) = resolve_physical_pages(g.get_or_insert_with(Away::default), pages, offset, dst.len()) else { return false }; let mut done = 0; let mut page_off = offset; for addr in addrs { @@ -911,8 +916,8 @@ pub unsafe fn write_physical_pages(pages: &[usize], offset: usize, src: &[u8]) - if src.is_empty() { return offset < PHYS_PAGE; } - let g = AWAY.lock().unwrap(); - let Some(addrs) = resolve_physical_pages(g.as_ref(), pages, offset, src.len()) else { return false }; + let mut g = AWAY.lock().unwrap(); + let Some(addrs) = resolve_physical_pages(g.get_or_insert_with(Away::default), pages, offset, src.len()) else { return false }; let mut done = 0; let mut page_off = offset; for addr in addrs { @@ -961,36 +966,60 @@ unsafe fn give_back_homes(away: &mut Away) { } } +pub(crate) static DEFER_PRIVATE_HOME_TILES: std::sync::LazyLock = + std::sync::LazyLock::new(|| std::env::var("XCL_DEFER_PRIVATE_HOME_TILES").is_ok_and(|v| v == "1")); + /// The page's home, committed again if `move_home_away` gave it back (None: it could not be). -unsafe fn home_again(home: usize) -> Option { +unsafe fn home_again(home: usize, page: usize, away: &mut Away) -> Option { if lazy_home(home) && !committed_page(home) { if mem::VirtualAlloc(home as *const c_void, PHYS_PAGE, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical page: its home {home:#x} could not be committed again"); return None; } if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(home)) { - crate::hle::d3d12x::sparse::committed(home, PHYS_PAGE); + if *DEFER_PRIVATE_HOME_TILES && away.sparse_homes.get(&page) != Some(&SparseHome::Exposed) { + away.sparse_homes.insert(page, SparseHome::CpuOnly); + } else { + crate::hle::d3d12x::sparse::committed(home, PHYS_PAGE); + } } } Some(home) } /// `n` pages from `home` committed (a sparse home is only reserved until it is used). -unsafe fn commit_homes(home: usize, n: usize) -> bool { +unsafe fn commit_homes(home: usize, pages: &[usize], away: &mut Away) -> bool { + let n = pages.len(); let Some(u) = crate::gpu::uma::get() else { return false }; if !lazy_home(home) { return true; } let len = n * PHYS_PAGE; - if committed_range(home, len) { - return true; - } - if mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { + let ready = committed_range(home, len); + if !ready && mem::VirtualAlloc(home as *const c_void, len, mem::MEM_COMMIT, mem::PAGE_READWRITE).is_null() { crate::xlog_warn!("physical pages: {n} at their home {home:#x} could not be committed"); return false; } if u.is_sparse(home) { - crate::hle::d3d12x::sparse::committed(home, len); + let private = |page: &usize| away.sparse_homes.get(page) == Some(&SparseHome::CpuOnly); + let has_private = *DEFER_PRIVATE_HOME_TILES && pages.iter().any(private); + if !ready || has_private { + crate::hle::d3d12x::sparse::committed(home, len); + } + if has_private { + // A write-watch scan can consume a storage write before its GPU tile exists. + let mut addr = home; + for run in pages.chunk_by(|a, b| private(a) == private(b)) { + let bytes = run.len() * PHYS_PAGE; + if private(&run[0]) { + crate::hle::d3d12x::title_textures::rescan_cpu_backing(addr, bytes); + } + addr += bytes; + } + } + if *DEFER_PRIVATE_HOME_TILES { + away.sparse_homes.extend(pages.iter().map(|&p| (p, SparseHome::Exposed))); + } } true } @@ -1069,7 +1098,7 @@ unsafe fn unmap_away(away: &mut Away, at: usize, committed: &std::ops::Range