diff --git a/README.md b/README.md index 722483312f..ad07d53e7f 100644 --- a/README.md +++ b/README.md @@ -126,6 +126,9 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - **The game folder is never modified** – writes go to the overlay. - Translated shaders are reused across XCL rebuilds when the translator sources and DXC toolchain are unchanged; `XCL_TRANSLATED_CACHE=0` disables that disk cache. +- `XCL_WRITE_WATCH_GAP_MIB` optionally tunes the maximum gap merged into a write-watch scan + (integer 1 through 64; default 64, including invalid values). Smaller values may reduce scan + cost for fragmented allocations but increase calls on other layouts. Set before launching XCL. - 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/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index ada439cbaa..0e02f2fbc9 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -634,7 +634,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()); - let computed = Arc::new(watch_ranges(®ions, wanted)); + let computed = Arc::new(watch_ranges(®ions, wanted, watch_gap())); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); computed } @@ -1017,15 +1017,32 @@ unsafe fn upload_queue(dev: &ID3D12Device, device: usize) -> Result usize { + static GAP: std::sync::OnceLock = std::sync::OnceLock::new(); + *GAP.get_or_init(|| { + let Ok(value) = std::env::var("XCL_WRITE_WATCH_GAP_MIB") else { return WATCH_GAP }; + let gap = parse_watch_gap(&value); + crate::xlog_info!("write-watch merge gap: {} MiB (requested {:?})", gap >> 20, value); + gap + }) +} + +fn parse_watch_gap(value: &str) -> usize { + value.trim().parse::().ok().filter(|n| (1..=64).contains(n)) + .map_or(WATCH_GAP, |n| n << 20) +} + /// The parts of `wanted` (start, end) inside `regions` (base, size), merged (gaps under -/// `WATCH_GAP` too) and sorted, as (base, size) – each within one region (a write-watch call +/// `gap` too) and sorted, as (base, size) – each within one region (a write-watch call /// covers one allocation). -fn watch_ranges(regions: &[(usize, usize)], mut wanted: Vec<(usize, usize)>) -> Vec<(usize, usize)> { +fn watch_ranges(regions: &[(usize, usize)], mut wanted: Vec<(usize, usize)>, gap: usize) -> Vec<(usize, usize)> { wanted.sort_unstable(); let mut merged: Vec<(usize, usize)> = Vec::new(); for (a, b) in wanted { match merged.last_mut() { - Some(last) if a <= last.1.saturating_add(WATCH_GAP) => last.1 = last.1.max(b), + Some(last) if a <= last.1.saturating_add(gap) => last.1 = last.1.max(b), _ => merged.push((a, b)), } } @@ -1544,16 +1561,84 @@ mod tests { fn watch_ranges_clip_and_merge() { let regions = [(0x10000, 0x10000), (0x40000, 0x10000), (0x1000_0000, 0x1000_0000)]; let wanted = vec![(0x12000, 0x13000), (0x11000, 0x12800), (0x1F000, 0x41000), (0x60000, 0x61000)]; - assert_eq!(watch_ranges(®ions, wanted), vec![(0x11000, 0xF000), (0x40000, 0x10000)]); + assert_eq!(watch_ranges(®ions, wanted, WATCH_GAP), vec![(0x11000, 0xF000), (0x40000, 0x10000)]); // ranges a gap of under WATCH_GAP apart: one scan; further apart: two let wanted = vec![(0x1000_0000, 0x1000_1000), (0x1008_0000, 0x1008_1000), (0x1100_0000, 0x1100_1000), (0x1800_0000, 0x1800_1000)]; - assert_eq!(watch_ranges(®ions, wanted), vec![(0x1000_0000, 0x100_1000), (0x1800_0000, 0x1000)]); + assert_eq!(watch_ranges(®ions, wanted, WATCH_GAP), vec![(0x1000_0000, 0x100_1000), (0x1800_0000, 0x1000)]); // a merged range over two regions: a piece in each, whatever order the regions come in let regions = [(0x40000, 0x10000), (0x10000, 0x10000)]; - assert_eq!(watch_ranges(®ions, vec![(0x18000, 0x48000)]), vec![(0x18000, 0x8000), (0x40000, 0x8000)]); + assert_eq!(watch_ranges(®ions, vec![(0x18000, 0x48000)], WATCH_GAP), vec![(0x18000, 0x8000), (0x40000, 0x8000)]); // a region between two merged ranges, and one past them all let regions = [(0x2000_0000, 0x10_0000), (0x9000_0000, 0x1000)]; - assert_eq!(watch_ranges(®ions, vec![(0x1000_0000, 0x1000_1000), (0x2008_0000, 0x2009_0000)]), vec![(0x2008_0000, 0x1_0000)]); + assert_eq!(watch_ranges(®ions, vec![(0x1000_0000, 0x1000_1000), (0x2008_0000, 0x2009_0000)], WATCH_GAP), vec![(0x2008_0000, 0x1_0000)]); + } + + #[test] + fn watch_gap_option_defaults_and_bounds() { + assert_eq!(parse_watch_gap("8"), 8 << 20); + assert_eq!(parse_watch_gap(" 1 "), 1 << 20); + assert_eq!(parse_watch_gap("64"), WATCH_GAP); + for invalid in ["", "0", "65", "-1", "abc", "18446744073709551616"] { + assert_eq!(parse_watch_gap(invalid), WATCH_GAP); + } + } + + #[test] + fn watch_ranges_narrow_gap_keeps_all_wanted_pages() { + const M: usize = 1 << 20; + let regions = [(32 * M, 32 * M), (0, 32 * M)]; + let wanted = vec![(48 * M, 49 * M), (31 * M, 33 * M), (16 * M, 17 * M), (0, M)]; + let wide = watch_ranges(®ions, wanted.clone(), WATCH_GAP); + let narrow = watch_ranges(®ions, wanted.clone(), 8 * M); + assert_eq!(wide, vec![(0, 32 * M), (32 * M, 17 * M)]); + assert_eq!(narrow, vec![(0, M), (16 * M, M), (31 * M, M), (32 * M, M), (48 * M, M)]); + for (a, b) in wanted { + for page in (a..b).step_by(0x1000) { + assert!(narrow.iter().any(|&(base, size)| base <= page && page < base + size)); + } + } + } + + /// Exercise the real atomic-reset API on separated active ranges, then make a previously + /// unwatched page wanted. Its earlier CPU write must still be visible to write-watch. + #[test] + fn watch_ranges_narrow_gap_preserves_dirty_pages() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; + const SIZE: usize = 32 << 20; + const PAGE: usize = 0x1000; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + struct Reservation(usize); + impl Drop for Reservation { + fn drop(&mut self) { unsafe { VirtualFree(self.0 as *mut c_void, 0, MEM_RELEASE); } } + } + unsafe { + let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) as usize; + assert_ne!(base, 0); + let _reservation = Reservation(base); + let regions = [(base, SIZE)]; + let a = base; + let gap_page = base + (8 << 20); + let b = base + (16 << 20); + let wanted = vec![(a, a + PAGE), (b, b + PAGE)]; + let ranges = watch_ranges(®ions, wanted.clone(), 8 << 20); + assert_eq!(ranges, vec![(a, PAGE), (b, PAGE)]); + let mut buf = vec![std::ptr::null_mut::(); 64]; + let (mut dirty, mut page) = (Vec::new(), PAGE as u32); + take_written(base, SIZE, &mut buf, &mut dirty, &mut page); + dirty.clear(); + for addr in [a, gap_page, b] { (addr as *mut u8).write_volatile(1); } + for &(start, len) in &ranges { take_written(start, len, &mut buf, &mut dirty, &mut page); } + assert_eq!(dirty, vec![a, b]); + dirty.clear(); + for &(start, len) in &ranges { take_written(start, len, &mut buf, &mut dirty, &mut page); } + assert!(dirty.is_empty(), "atomic reset cleared the active pages"); + let mut expanded = wanted; + expanded.push((gap_page, gap_page + PAGE)); + for (start, len) in watch_ranges(®ions, expanded, 8 << 20) { + take_written(start, len, &mut buf, &mut dirty, &mut page); + } + assert_eq!(dirty, vec![gap_page], "newly watched page retains its earlier write"); + } } /// The textures of a batch detiled on several threads come back as on one: complete and in diff --git a/crates/xcl/tests/e2e.rs b/crates/xcl/tests/e2e.rs index 3c541449cf..6613921d31 100644 --- a/crates/xcl/tests/e2e.rs +++ b/crates/xcl/tests/e2e.rs @@ -105,12 +105,19 @@ fn test_title_runs_and_game_folder_is_untouched() { std::fs::copy(&title, game.join("xcl_testtitle.exe")).unwrap(); std::fs::copy(&dll, game.join("testgame_mw.dll")).unwrap(); let before = snapshot(&game); + let fragmented = std::env::var("XCL_TEST_FRAGMENTED_WATCH").as_deref() == Ok("1"); + let layout = std::env::var("XCL_TEST_FRAGMENTED_LAYOUT").unwrap_or_else(|_| "gap15".to_owned()); + if fragmented { + assert!(matches!(layout.as_str(), "packed" | "gap3" | "gap9" | "gap15" | "gap79"), "unknown fragmented watch layout: {layout}"); + } let out = Command::new(&xcl) .arg("run") .arg(&game) .arg("--") .arg("--hello") + .args(fragmented.then_some("--fragmented-watch")) + .args(fragmented.then(|| format!("--fragmented-watch-layout={layout}"))) .env("XCL_DATA_ROOT", &data) // the shader dumps and their translation, which the report's shader counts come from .env("XCL_DUMP_SHADERS", "1") @@ -132,6 +139,11 @@ fn test_title_runs_and_game_folder_is_untouched() { assert!(fails.is_empty(), "failed checks in the test title:\n{}", fails.join("\n")); 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()); + if fragmented { + assert!(stdout.contains(&format!("WATCH-BENCH begin: layout={layout} ")), "wrong fragmented fixture layout"); + assert!(stdout.contains("[PASS] D3D12.X: fragmented write-watch stress"), "fragmented fixture did not run"); + assert!(stdout.contains("WATCH-BENCH end: submits=2048 verified_pairs=28672"), "fragmented fixture did not finish"); + } // (2) the game folder is untouched assert_eq!(snapshot(&game), before, "GAME FOLDER WAS MODIFIED"); diff --git a/tests/testtitle/src/gpu.rs b/tests/testtitle/src/gpu.rs index d84d465d99..fbd14606b2 100644 --- a/tests/testtitle/src/gpu.rs +++ b/tests/testtitle/src/gpu.rs @@ -1735,6 +1735,133 @@ pub fn sparse_async_ring_upload_stress() -> Result<(), String> { } } +/// Opt-in performance fixture: vary the spacing of 1 MiB graphics regions while +/// keeping the dirty-page workload and GPU readback validation fixed within each A/B pair. +pub fn fragmented_write_watch_stress() -> Result<(), String> { + const MIB: usize = 1 << 20; + let layout = std::env::args() + .find_map(|arg| arg.strip_prefix("--fragmented-watch-layout=").map(str::to_owned)) + .unwrap_or_else(|| "gap15".to_owned()); + // Each reservation stays at or below 2 GiB; the number of islands varies + // for the near-threshold and wide cases, but never between thresholds. + let (islands, stride_mib): (usize, usize) = match layout.as_str() { + "packed" => (128, 1), + "gap3" => (128, 4), + "gap9" => (192, 10), + "gap15" => (128, 16), + "gap79" => (24, 80), + _ => return Err(format!("unknown fragmented watch layout: {layout}")), + }; + let stride = stride_mib * MIB; + let span = islands * stride; + const PAGE: usize = 4096; + const PAGES_PER_ISLAND: usize = MIB / PAGE; + const DIRTY: usize = 14; + const SUBMITS: usize = 2048; + const CANARY: u32 = 0xC15A_0042; + struct Reservation(*mut c_void); + impl Drop for Reservation { + fn drop(&mut self) { unsafe { crate::VirtualFree(self.0, 0, 0x8000); } } + } + struct Event(windows::Win32::Foundation::HANDLE); + impl Drop for Event { + fn drop(&mut self) { unsafe { let _ = windows::Win32::Foundation::CloseHandle(self.0); } } + } + type PlacedX = unsafe extern "system" fn(*mut c_void, u64, *const D3D12_RESOURCE_DESC, u32, *const c_void, *const windows::core::GUID, *mut *mut c_void) -> HRESULT; + unsafe { + let dev = device()?; + let reservation = crate::XMemVirtualAlloc(std::ptr::null(), span, 0x2000, 1u64 << 29, 4); + ensure!(!reservation.is_null(), "fragmented graphics reservation failed"); + let reservation = Reservation(reservation); + let base = reservation.0 as usize; + let desc = |bytes: usize| D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes 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 placed: PlacedX = std::mem::transmute(*(*(dev.as_raw() as *const *const usize)).add(44)); + let mut buffers = Vec::with_capacity(islands); + for i in 0..islands { + let addr = base + i * stride; + let p = crate::XMemVirtualAlloc(addr as *const c_void, MIB, 0x1000, 1u64 << 29, 4); + ensure!(p as usize == addr, "commit of island {i} failed"); + let mut raw = std::ptr::null_mut(); + let hr = placed(dev.as_raw(), addr as u64, &desc(MIB), D3D12_RESOURCE_STATE_COMMON.0 as u32, + std::ptr::null(), &ID3D12Resource::IID, &mut raw); + ensure!(hr >= 0 && !raw.is_null(), "placed island {i}: hr={hr:#x}"); + let buf = ID3D12Resource::from_raw(raw); + ensure!(buf.GetGPUVirtualAddress() == addr as u64, "island {i} VA mismatch"); + for off in (0..MIB).step_by(PAGE) { + ((addr + off + 4) as *mut u32).write_volatile(CANARY); + } + buffers.push(buf); + } + let mut rb: Option = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &desc(DIRTY * 8), D3D12_RESOURCE_STATE_COPY_DEST, None, &mut rb, + ).map_err(e)?; + let rb = rb.ok_or("fragmented readback buffer")?; + let mut p_rb = std::ptr::null_mut(); + rb.Map(0, None, Some(&mut p_rb)).map_err(e)?; + ensure!(!p_rb.is_null(), "fragmented readback map returned null"); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).map_err(e)?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(e)?; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(e)?; + let ev = CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()); + ensure!(!ev.is_null(), "fragmented fixture event creation failed"); + let event = Event(windows::Win32::Foundation::HANDLE(ev)); + let command: ID3D12CommandList = list.cast().map_err(e)?; + let finish = |value: u64| -> Result<(), String> { + queue.Signal(&fence, value).map_err(e)?; + fence.SetEventOnCompletion(value, event.0).map_err(e)?; + ensure!(WaitForSingleObject(ev, 5000) == 0, "fragmented fence {value} timed out"); + let completed = fence.GetCompletedValue(); + ensure!(completed != u64::MAX && completed >= value, "fragmented fence failed: {completed}"); + Ok(()) + }; + // Warm-up submits all initial canaries and pending tile clears before timing. + list.Close().map_err(e)?; + queue.ExecuteCommandLists(&[Some(command.clone())]); + finish(1)?; + println!("WATCH-BENCH begin: layout={layout} span_mib={} committed_mib={islands} islands={islands} gap_mib={} dirty_per_submit={DIRTY} submits={SUBMITS}", span / MIB, stride_mib - 1); + let started = std::time::Instant::now(); + let mut submit_us = 0u128; + for s in 0..SUBMITS { + alloc.Reset().map_err(e)?; + list.Reset(&alloc, None).map_err(e)?; + for i in 0..DIRTY { + let page = (i * islands * PAGES_PER_ISLAND / DIRTY + s * 17) % (islands * PAGES_PER_ISLAND); + let island = page / PAGES_PER_ISLAND; + let offset = (page % PAGES_PER_ISLAND) * PAGE; + let tag = 0xA000_0000 | ((s as u32) << 8) | i as u32; + ((base + island * stride + offset) as *mut u32).write_volatile(tag); + list.CopyBufferRegion(&rb, (i * 8) as u64, &buffers[island], offset as u64, 8); + } + list.Close().map_err(e)?; + let t = std::time::Instant::now(); + queue.ExecuteCommandLists(&[Some(command.clone())]); + submit_us += t.elapsed().as_micros(); + finish(s as u64 + 2)?; + for i in 0..DIRTY { + let tag = 0xA000_0000 | ((s as u32) << 8) | i as u32; + let got = (p_rb as *const u32).add(i * 2).read_volatile(); + let canary = (p_rb as *const u32).add(i * 2 + 1).read_volatile(); + ensure!(got == tag && canary == CANARY, "fragmented submit {s} word {i}: got {got:#x}/{canary:#x}, expected {tag:#x}/{CANARY:#x}"); + } + } + println!("WATCH-BENCH end: submits={SUBMITS} verified_pairs={} execute_us={submit_us} elapsed_us={}", SUBMITS * DIRTY, started.elapsed().as_micros()); + rb.Unmap(0, None); + Ok(()) + } +} + /// A graphics reservation larger than the two upper sparse windows (8 GiB + 4 MiB, the first /// thing one retail title does) goes across window 0 – and the console descriptor heaps made /// after it still get window 0's descriptor range: their start handle (in rax, the console's diff --git a/tests/testtitle/src/main.rs b/tests/testtitle/src/main.rs index d5ae267a44..e5f2f76c64 100644 --- a/tests/testtitle/src/main.rs +++ b/tests/testtitle/src/main.rs @@ -698,6 +698,10 @@ fn main() { check("MFPlat: MFResetDXGIDeviceManagerX resets IMFDXGIDeviceManager with the d3d12_xs device", gpu::mfplat_reset_dxgi_device_manager); check("XAudio2: console flags/device, XMA2 & Opus voices decoded, PCM passes, callbacks", audio::xaudio2_console_voices); + if std::env::args().any(|a| a == "--fragmented-watch") { + check("D3D12.X: fragmented write-watch stress", gpu::fragmented_write_watch_stress); + } + let failures = FAILURES.load(Ordering::SeqCst); println!("xcl_testtitle: done, failures: {failures}"); std::process::exit(failures as i32);