From c6562a0c87c0d4ad30886dacd397499b9a2b8c08 Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:07:59 +0000 Subject: [PATCH 1/5] D3D12.X: XCL_ACTIVITY counts and times the per-draw buffer mirror sync Once any buffer mirror exists, sync_title_buffers runs on every draw and nothing reported what it costs. With XCL_ACTIVITY=1 it now logs, every 2 s in which it ran: draws synced and those with a mirror, copies (whole buffers), bytes copied, indices scanned for the vertex range, readable() calls (those over 16 pages, which can take the VirtualQuery walk), the time in readable() and its slowest call, and the time in the function. A row is logged whenever any of these moved, also with no draw synced: the counters of a sync still running at the sample (or stalled for over 2 s) land before its draw is counted, and its slowest readable() would otherwise be dropped with the skipped row. The slowest readable() is not in #2391's list: measuring on #2389 found single calls of 16 pages or fewer taking 1-9 ms, which the other counters average away. The counters cost nothing without XCL_ACTIVITY: host_main turns them on (enable_sync_activity) before it starts the activity thread, and until then sync_title_buffers, sync_readable() and sync_count() check one relaxed bool and take no time stamps and touch no shared counter. No change in behaviour: the old body is sync_mirrors, unchanged apart from the counters, and sync_title_buffers still returns first when no mirror exists. Fixes #2391. Part of #2389. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/list_x.rs | 123 +++++++++++++++++++++++++++- crates/xcl/src/host.rs | 16 ++++ 2 files changed, 137 insertions(+), 2 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 0210c522f1..173187d0ed 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5827,12 +5827,90 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { Some(p + (va - start) as usize) } +/// `XCL_ACTIVITY`: what `sync_title_buffers` did so far (the `SYNC_*` indices) +static SYNC_COUNTS: [AtomicU64; 9] = [const { AtomicU64::new(0) }; 9]; +const SYNC_DRAWS: usize = 0; +const SYNC_MIRRORED: usize = 1; +const SYNC_COPIES: usize = 2; +const SYNC_WHOLE: usize = 3; +const SYNC_BYTES: usize = 4; +const SYNC_INDICES: usize = 5; +const SYNC_READABLE: usize = 6; +const SYNC_READABLE_LARGE: usize = 7; +const SYNC_READABLE_NS: usize = 8; +/// ns of the whole function so far, and of its slowest `readable()` since `take_sync_slowest` +static SYNC_NS: AtomicU64 = AtomicU64::new(0); +static SYNC_READABLE_MAX_NS: AtomicU64 = AtomicU64::new(0); +/// whether the mirror sync counts and times at all: only with `XCL_ACTIVITY` (`enable_sync_activity`) +static SYNC_ON: AtomicBool = AtomicBool::new(false); + +/// `XCL_ACTIVITY`: from now on the mirror sync counts and times what it does +pub fn enable_sync_activity() { + SYNC_ON.store(true, Ordering::Relaxed); +} + +/// `XCL_ACTIVITY`: draws through the mirror sync, of those with a mirror, copies, whole-buffer +/// copies, bytes copied, indices scanned, `readable()` calls, of those over 16 pages (the +/// `VirtualQuery` walk), ns in `readable()`, ns in the sync – all so far +pub fn sync_activity() -> [u64; 10] { + let mut out = [0; 10]; + for (o, c) in out.iter_mut().zip(&SYNC_COUNTS) { + *o = c.load(Ordering::Relaxed); + } + out[9] = SYNC_NS.load(Ordering::Relaxed); + out +} + +/// ns of the slowest `readable()` of the mirror sync since the last call +pub fn take_sync_slowest() -> u64 { + SYNC_READABLE_MAX_NS.swap(0, Ordering::Relaxed) +} + +/// Whether `XCL_ACTIVITY` logs a row for these `sync_activity` deltas and slowest `readable()`: +/// when anything moved, also with no draw synced (a sync still running at the sample, or stalled) +pub fn sync_row_due(delta: &[u64], slowest: u64) -> bool { + slowest > 0 || delta.iter().any(|&v| v > 0) +} + +fn sync_count(k: usize, n: u64) { + if SYNC_ON.load(Ordering::Relaxed) { + SYNC_COUNTS[k].fetch_add(n, Ordering::Relaxed); + } +} + +/// `readable()`, counted and timed for `XCL_ACTIVITY` +fn sync_readable(p: usize, len: usize) -> bool { + if !SYNC_ON.load(Ordering::Relaxed) { + return crate::gpu::shader::readable(p, len); + } + let t = Instant::now(); + let r = crate::gpu::shader::readable(p, len); + let ns = t.elapsed().as_nanos() as u64; + sync_count(SYNC_READABLE, 1); + if len > 0 && ((p + len - 1) >> 12) - (p >> 12) + 1 > 16 { + sync_count(SYNC_READABLE_LARGE, 1); + } + sync_count(SYNC_READABLE_NS, ns); + SYNC_READABLE_MAX_NS.fetch_max(ns, Ordering::Relaxed); + r +} + /// Before a draw on `list`: the parts of mirrored buffers it reads are copied from the title's /// memory. `indexed`: (first index, index count, base vertex); else `first_vertex`, `vertices`. pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, u32, i32)>, first_vertex: u32, vertices: u32, instances: u32) { if MIRROR_BYTES.load(Ordering::Relaxed) == 0 { return; } + if !SYNC_ON.load(Ordering::Relaxed) { + return sync_mirrors(list, indexed, first_vertex, vertices, instances); + } + let t = Instant::now(); + sync_mirrors(list, indexed, first_vertex, vertices, instances); + sync_count(SYNC_DRAWS, 1); + SYNC_NS.fetch_add(t.elapsed().as_nanos() as u64, Ordering::Relaxed); +} + +unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, first_vertex: u32, vertices: u32, instances: u32) { let (vbs, ib) = { let g = LISTS.lock().unwrap(); let Some(b) = g.as_ref().and_then(|m| m.get(&(list as usize))).map(|s| &s.bindings) else { return }; @@ -5846,11 +5924,14 @@ pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, } v }; + sync_count(SYNC_MIRRORED, 1); 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) { + if len > 0 && sync_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); + sync_count(SYNC_COPIES, 1); + sync_count(SYNC_BYTES, len as u64); } }; // the vertices read: [lo, hi) @@ -5862,9 +5943,10 @@ pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, 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) { + if n == 0 || !sync_readable((va + from) as usize, n * size as usize) { (0, u64::MAX) } else { + sync_count(SYNC_INDICES, n as u64); let at = (va + from) as *const u8; let (mut lo, mut hi) = (u32::MAX, 0u32); for k in 0..n { @@ -5888,6 +5970,7 @@ pub(super) unsafe fn sync_title_buffers(list: *mut c_void, indexed: Option<(u32, // a buffer stepped by instance is not told apart: with instances (callers pass more // than 1 for a first instance other than 0 too), all of it if instances > 1 || hi == u64::MAX || stride == 0 || hi.saturating_mul(stride as u64) > bytes as u64 { + sync_count(SYNC_WHOLE, 1); copy(va, m, bytes, 0, bytes as u64); } else { copy(va, m, bytes, lo * stride as u64, (hi - lo) * stride as u64); @@ -11729,4 +11812,40 @@ mod tests { assert!(got.iter().all(|&v| v == 0xDEAD_BEEF), "the UAV was not cleared: {:x?}", &got[..4]); } } + + /// Without `XCL_ACTIVITY` the mirror sync counts and times nothing; once it is enabled it does. + #[test] + fn the_mirror_sync_counts_only_once_xcl_activity_enables_it() { + let buf = vec![0u8; 17 << 12]; // over 16 pages + let (p, len) = (buf.as_ptr() as usize, buf.len()); + assert!(!SYNC_ON.load(Ordering::Relaxed), "only this test enables the counters"); + let before = sync_activity(); + assert!(sync_readable(p, len)); + sync_count(SYNC_COPIES, 1); + assert_eq!(sync_activity(), before); + assert_eq!(take_sync_slowest(), 0); + + enable_sync_activity(); + assert!(sync_readable(p, len)); + sync_count(SYNC_COPIES, 1); + let after = sync_activity(); + // (other tests' draws may count too once it is on: at least ours) + assert!(after[SYNC_READABLE] > before[SYNC_READABLE]); + assert!(after[SYNC_READABLE_LARGE] > before[SYNC_READABLE_LARGE]); + assert!(after[SYNC_COPIES] > before[SYNC_COPIES]); + } + + /// A 2 s row with `readable()` work but no draw synced yet is logged, not dropped with its slowest call. + #[test] + fn a_mirror_sync_row_with_no_finished_draw_is_still_logged() { + let mut d = [0u64; 10]; + assert!(!sync_row_due(&d, 0)); + d[SYNC_READABLE] = 1; + d[SYNC_READABLE_NS] = 5_000_000; + assert!(sync_row_due(&d, 5_000_000)); + assert!(sync_row_due(&[0; 10], 5_000_000)); + d = [0; 10]; + d[SYNC_DRAWS] = 1; + assert!(sync_row_due(&d, 0)); + } } diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index f76e9a7a8d..dfebd69da3 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -100,6 +100,9 @@ pub fn host_main(boot_path: &Path) -> i32 { // mode queries only adapter-local usage; it does not enable the activity hot-path probes. let activity = crate::hle::d3d12x::memory_report::enabled(); let pressure = crate::hle::d3d12x::pso_async::pressure_sampling_enabled(); + if activity { + crate::hle::d3d12x::list_x::enable_sync_activity(); + } if activity || pressure { let name = if activity { "xcl-activity" } else { "xcl-pso-pressure" }; let sampler = std::thread::Builder::new().name(name.into()).spawn(move || { @@ -118,6 +121,7 @@ pub fn host_main(boot_path: &Path) -> i32 { let mut views = crate::hle::d3d12x::view_want::totals(); let mut tile_calls = crate::hle::d3d12x::sparse::tile_calls(); let mut last_tick = std::time::Instant::now(); + let mut last_sync = crate::hle::d3d12x::list_x::sync_activity(); loop { std::thread::sleep(std::time::Duration::from_secs(2)); let window_ms = last_tick.elapsed().as_millis() as u64; @@ -171,6 +175,18 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::xlog_info!("tile mappings (2 s): {line}"); } tile_calls = mappings; + // the per-draw sync of buffer mirrors (only once a mirror exists) + let sync = crate::hle::d3d12x::list_x::sync_activity(); + let s: Vec = sync.iter().zip(last_sync).map(|(a, b)| a - b).collect(); + let slowest = crate::hle::d3d12x::list_x::take_sync_slowest(); + if crate::hle::d3d12x::list_x::sync_row_due(&s, slowest) { + let ms = |ns: u64| ns as f64 / 1e6; + crate::xlog_info!( + "buffer mirrors (2 s): {} draws synced, {} with a mirror; {} copies ({} whole buffers), {} KB; {} indices scanned; {} readable() calls ({} over 16 pages), {:.2} ms, slowest {:.2} ms; {:.2} ms in all", + s[0], s[1], s[2], s[3], s[4] >> 10, s[5], s[6], s[7], ms(s[8]), ms(slowest), ms(s[9]) + ); + } + last_sync = sync; // where the memory is: the process's commit, video memory, and XCL's parts of it let owner = owner.unwrap(); let private = owner.commit.unwrap_or(0); From 1de6652ef26f357f7831e3dd6525a0cbe04c6f57 Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:44:59 +0000 Subject: [PATCH 2/5] D3D12.X: the per-draw mirror sync copies without asking readable() sync_title_buffers checked every copy's source, and the indices it scans, with gpu::shader::readable. For a range with a page that is not resident, or over 16 pages, that walks the region with VirtualQuery. Measured on the render thread inside a draw. The copy now uses title_textures::copy_committed_region (ReadProcessMemory, which cannot fault), so a page the title freed or protected since keeps what the mirror had. The indices are scanned from the index buffer's mirror once copied there; an index buffer without a mirror is still checked. reprotects memory. kernelx does not see HeapFree, which releases large heap blocks inside ntdll, so that still needed a copy that cannot fault, and with one the check has nothing left to protect. Fixes #2392. Part of #2389. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/list_x.rs | 127 ++++++++++++++++++-- crates/xcl/src/hle/d3d12x/title_textures.rs | 24 +++- 2 files changed, 138 insertions(+), 13 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 173187d0ed..77c7c8825c 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5925,11 +5925,14 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs v }; sync_count(SYNC_MIRRORED, 1); + // (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 && sync_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_pages((va + from) as usize, (mirror + from as usize) as *mut u8, len); sync_count(SYNC_COPIES, 1); sync_count(SYNC_BYTES, len as u64); } @@ -5939,15 +5942,21 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs (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 || !sync_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 && sync_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 { sync_count(SYNC_INDICES, n as u64); - 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 }; @@ -11644,6 +11653,110 @@ mod tests { assert_eq!(u.view_release(g), Some(SIZE)); } + /// 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) + } + } + + /// The other paths of the per-draw sync, with a page of the mirrored vertex buffer made + /// unreadable: an index buffer without a mirror gives the vertex range when it is readable, + /// and when it is not, or the draw has instances, the whole buffer is copied around that page. + #[test] + fn the_mirror_sync_copies_whole_buffers_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_2437usize as *mut c_void; + assert_ne!(gpu_va(list, vb as u64, vb_bytes as usize, "test vertex buffer", true), vb as u64); + assert!(mirrored(ib as u64, 6).is_none(), "the index buffer has no mirror"); + 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)); + }); + let mut old = 0u32; + let title_writes = |v: u8| { + std::ptr::write_bytes(vb, v, 0x1000); + std::ptr::write_bytes(vb.add(0x2000), v, 0x1000); + }; + std::ptr::write_bytes(vb, 0x22, vb_bytes as usize); + assert_ne!(VirtualProtect(vb.add(0x1000) as *const _, 0x1000, PAGE_NOACCESS, &mut old), 0); + + // indices 0..=2 read from the title's index buffer: only those three vertices + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 1); + assert!((0..48).all(|k| *vm.add(k) == 0x22), "the vertices the indices reach are copied"); + assert!((48..0x1000).chain(0x2000..0x3000).all(|k| *vm.add(k) == 0x11), "the rest is not"); + + // with instances: the whole buffer, around the unreadable page + title_writes(0x33); + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 2); + assert!((0..0x1000).chain(0x2000..0x3000).all(|k| *vm.add(k) == 0x33), "the whole buffer is copied"); + assert!((0x1000..0x2000).all(|k| *vm.add(k) == 0x11), "the unreadable page keeps the mirror's bytes"); + + // an unreadable index buffer without a mirror: the whole buffer + title_writes(0x44); + assert_ne!(VirtualProtect(ib as *const _, 0x1000, PAGE_NOACCESS, &mut old), 0); + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 1); + assert!((0..0x1000).chain(0x2000..0x3000).all(|k| *vm.add(k) == 0x44), "the whole buffer is copied"); + assert!((0x1000..0x2000).all(|k| *vm.add(k) == 0x11), "the unreadable page keeps the mirror's bytes"); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + } + } + #[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 2fe0c9e12e..3c8ad1b23c 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -3229,12 +3229,22 @@ fn watch_ranges(regions: &[(usize, usize)], mut wanted: Vec<(usize, usize)>) -> /// `0`. Because Windows may return `read == 0` when a fault occurs later in the span, binary-split /// failed multi-page ranges at 4 KiB boundaries so all still-committed pages are copied in O(log N) /// calls and only unreadable pages are zeroed. -unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { +pub(super) unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { + copy_committed(src, dst, len, true) +} + +/// `copy_committed_region`, but a page that cannot be read keeps what `dst` holds (the per-draw +/// mirror sync compares it with the mirror's bytes: a page the title freed keeps the mirror's). +pub(super) unsafe fn copy_committed_pages(src: usize, dst: *mut u8, len: usize) { + copy_committed(src, dst, len, false) +} + +unsafe fn copy_committed(src: usize, dst: *mut u8, len: usize, zero: bool) { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; const PAGE: usize = 0x1000; - unsafe fn copy_rec(proc: *mut c_void, src: usize, dst: *mut u8, len: usize) { + unsafe fn copy_rec(proc: *mut c_void, src: usize, dst: *mut u8, len: usize, zero: bool) { if len == 0 { return; } @@ -3248,16 +3258,18 @@ unsafe fn copy_committed_region(src: usize, dst: *mut u8, len: usize) { let len = len - read; let page_end = (src & !(PAGE - 1)).saturating_add(PAGE).min(src + len); if page_end == src + len { - std::ptr::write_bytes(dst, 0, len); + if zero { + std::ptr::write_bytes(dst, 0, len); + } return; } let mid = ((src + len / 2) & !(PAGE - 1)).max(page_end); let left = mid - src; - copy_rec(proc, src, dst, left); - copy_rec(proc, mid, dst.add(left), len - left); + copy_rec(proc, src, dst, left, zero); + copy_rec(proc, mid, dst.add(left), len - left, zero); } - copy_rec(GetCurrentProcess(), src, dst, len); + copy_rec(GetCurrentProcess(), src, dst, len, zero); } /// The bytes at `at` into `to` in one read, all zeros when it fails: for memory committed whole From 647167cde63cd8a78d7711f5345ea7e285c8d80a Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:16:06 +0000 Subject: [PATCH 3/5] D3D12.X: the per-draw mirror sync writes only mirror pages whose bytes differ `sync_title_buffers` copied the drawn range of every mirrored buffer at every draw and scanned every index again. The retail game measured in write-watch sees them written (#2478 found no saving that way) while their content does not change. Each copy now reads the title's bytes into a per-thread scratch buffer (64 KiB chunks, `ReadProcessMemory`) and writes only the 4 KiB pages that differ from the mirror's. A chunk with a page the title freed or protected is copied with `copy_committed_region` as before (#2392). Unchanged pages are no longer written into the mirror, so the sparse look no longer sees them dirty. An indexed draw whose indices are in a mirror keeps the vertex range it scanned, per thread, keyed by (index buffer, bytes, format, first, count, base vertex), and scans again only after any mirror was written (`MIRROR_WRITES`). Each mirror has a lock, held while the sync writes into it and bumps `MIRROR_WRITES`. For the index buffer it is held from the copy through the range lookup or scan: otherwise another list that has written new indices but not yet bumped the count is seen as "nothing differs", and the old range is reused. Vertex copies take it too, since a vertex view and the index view can share a mirror. `XCL_ACTIVITY` reports the bytes written next to the bytes compared. Part of #2393. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015csBcd63KUE2T1kW2P15nC --- crates/xcl/src/hle/d3d12x/list_x.rs | 342 +++++++++++++++++++++++++--- crates/xcl/src/host.rs | 4 +- 2 files changed, 313 insertions(+), 33 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 77c7c8825c..81577f39a8 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5746,8 +5746,9 @@ unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: b /// Ranges of the title's memory with a mirror in unified memory: (start, bytes, mirror). A /// 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()); +/// inside a mirrored range uses that mirror at its offset. Each has a lock that is held while +/// the sync writes into it (`update_mirror`). +static MIRRORS: Mutex)>> = Mutex::new(Vec::new()); /// bytes of mirrors made (never freed) static MIRROR_BYTES: AtomicU64 = AtomicU64::new(0); /// Append generation. Incremented while `MIRRORS` is locked, before publishing a new range, so a @@ -5776,6 +5777,11 @@ fn cached_mirror( mirror_in(&cache.1, va, bytes) } +/// Where `[va, va + bytes)` is in a mirror, if it is in one, and that mirror's lock. +fn mirror_entry(va: u64, bytes: usize) -> Option<(usize, &'static Mutex<()>)> { + MIRRORS.lock().unwrap().iter().find(|&&(s, l, _, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m, lock)| (m + (va - s) as usize, lock)) +} + /// Where `[va, va + bytes)` is in a mirror, if it is in one. fn mirrored(va: u64, bytes: usize) -> Option { let generation = MIRROR_GENERATION.load(Ordering::Acquire); @@ -5783,7 +5789,7 @@ fn mirrored(va: u64, bytes: usize) -> Option { return None; } MIRROR_LOOKUP.with(|cache| { - cached_mirror(&mut cache.borrow_mut(), generation, va, bytes, || MIRRORS.lock().unwrap().clone()) + cached_mirror(&mut cache.borrow_mut(), generation, va, bytes, || MIRRORS.lock().unwrap().iter().map(|&(s, l, m, _)| (s, l, m)).collect()) }) } @@ -5796,7 +5802,7 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { let mut g = MIRRORS.lock().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) { + if let Some(&(s, _, m, _)) = g.iter().find(|&&(s, l, _, _)| va >= s && va + bytes as u64 <= s + l as u64) { return Some(m + (va - s) as usize); } let start = va & !0xffff; @@ -5819,7 +5825,8 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { // Invalidate cached misses before publishing while still holding the lock. A lookup that sees // the new generation blocks on `g` until this range is present in the refreshed snapshot. MIRROR_GENERATION.fetch_add(1, Ordering::Release); - g.push((start, len, p)); + g.push((start, len, p, Box::leak(Box::new(Mutex::new(()))))); + MIRROR_WRITES.fetch_add(1, Ordering::Release); let total = MIRROR_BYTES.fetch_add(len as u64, Ordering::Relaxed) + len as u64; if g.len() <= 8 || g.len().is_power_of_two() { crate::xlog_warn!("D3D12.X: {what} at {va:#x} ({bytes} bytes) is outside unified memory – {start:#x}..{:#x} mirrored at {p:#x}, each draw copies what it reads ({} mirrors, {} MB)", start + len as u64, g.len(), total >> 20); @@ -5827,8 +5834,85 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { Some(p + (va - start) as usize) } +/// Bumped after each write into a mirror: an index range scanned at one value is the same at +/// the next draw while it has not changed. +static MIRROR_WRITES: AtomicU64 = AtomicU64::new(0); + +thread_local! { + // the title's bytes of one chunk, read to be compared with the mirror's + static SYNC_SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + // the vertex range of an indexed draw whose indices are in a mirror: (index va, bytes, + // format, first, count, base vertex) → (lo, hi, `MIRROR_WRITES` when scanned) + static INDEX_RANGES: std::cell::RefCell> = std::cell::RefCell::new(HashMap::new()); +} + +/// Brings `len` bytes of a mirror at `mirror` up to the title's at `src`, writing only the pages +/// whose bytes differ (#2393: a title that rewrites a buffer with the same bytes every frame +/// otherwise has every page of the mirror written at every draw, and the sparse look uploads +/// each one again). A chunk the title freed or protected a page of is copied around that page +/// (#2392). Returns the bytes written. The sync calls it with the mirror's lock held, so another +/// thread does not see the bytes written before `MIRROR_WRITES` says so. +unsafe fn update_mirror(src: usize, mirror: *mut u8, len: usize) -> usize { + use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + const CHUNK: usize = 0x1_0000; + let wrote = SYNC_SCRATCH.with_borrow_mut(|buf| { + buf.resize(CHUNK, 0); + let mut wrote = 0; + let mut off = 0; + while off < len { + let n = (len - off).min(CHUNK); + let mut read = 0usize; + if ReadProcessMemory(GetCurrentProcess(), (src + off) as *const c_void, buf.as_mut_ptr().cast(), n, &mut read) == 0 { + super::title_textures::copy_committed_pages(src + off, mirror.add(off), n); + wrote += n; + } else { + // page by page of the title's memory + let mut p = 0; + while p < n { + let e = ((((src + off + p) & !0xfff) + 0x1000) - (src + off)).min(n); + let to = std::slice::from_raw_parts_mut(mirror.add(off + p), e - p); + if to != &buf[p..e] { + to.copy_from_slice(&buf[p..e]); + wrote += e - p; + } + p = e; + } + } + off += n; + } + wrote + }); + #[cfg(test)] + if wrote > 0 { + tests::BEFORE_MIRROR_WRITES.with_borrow_mut(|f| f.as_mut().map(|f| f())); + } + if wrote > 0 { + MIRROR_WRITES.fetch_add(1, Ordering::Release); + } + wrote +} + +/// The vertex range `scan` gives for `key`, scanned again only when a mirror was written since +/// the last scan of `key` on this thread (`writes`: `MIRROR_WRITES` now). +fn cached_vertex_range(key: (u64, u32, i32, u32, u32, i32), writes: u64, scan: impl FnOnce() -> (u64, u64)) -> (u64, u64) { + INDEX_RANGES.with_borrow_mut(|m| { + if let Some(&(lo, hi, w)) = m.get(&key) { + if w == writes { + return (lo, hi); + } + } + let (lo, hi) = scan(); + if m.len() >= 4096 { + m.clear(); + } + m.insert(key, (lo, hi, writes)); + (lo, hi) + }) +} + /// `XCL_ACTIVITY`: what `sync_title_buffers` did so far (the `SYNC_*` indices) -static SYNC_COUNTS: [AtomicU64; 9] = [const { AtomicU64::new(0) }; 9]; +static SYNC_COUNTS: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10]; const SYNC_DRAWS: usize = 0; const SYNC_MIRRORED: usize = 1; const SYNC_COPIES: usize = 2; @@ -5838,6 +5922,7 @@ const SYNC_INDICES: usize = 5; const SYNC_READABLE: usize = 6; const SYNC_READABLE_LARGE: usize = 7; const SYNC_READABLE_NS: usize = 8; +const SYNC_WRITTEN: usize = 9; /// ns of the whole function so far, and of its slowest `readable()` since `take_sync_slowest` static SYNC_NS: AtomicU64 = AtomicU64::new(0); static SYNC_READABLE_MAX_NS: AtomicU64 = AtomicU64::new(0); @@ -5850,14 +5935,15 @@ pub fn enable_sync_activity() { } /// `XCL_ACTIVITY`: draws through the mirror sync, of those with a mirror, copies, whole-buffer -/// copies, bytes copied, indices scanned, `readable()` calls, of those over 16 pages (the -/// `VirtualQuery` walk), ns in `readable()`, ns in the sync – all so far -pub fn sync_activity() -> [u64; 10] { - let mut out = [0; 10]; +/// copies, bytes copied (read and compared), indices scanned, `readable()` calls, of those over +/// 16 pages (the `VirtualQuery` walk), ns in `readable()`, bytes written into mirrors, ns in the +/// sync – all so far +pub fn sync_activity() -> [u64; 11] { + let mut out = [0; 11]; for (o, c) in out.iter_mut().zip(&SYNC_COUNTS) { *o = c.load(Ordering::Relaxed); } - out[9] = SYNC_NS.load(Ordering::Relaxed); + out[10] = SYNC_NS.load(Ordering::Relaxed); out } @@ -5916,9 +6002,9 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs let Some(b) = g.as_ref().and_then(|m| m.get(&(list as usize))).map(|s| &s.bindings) else { return }; (b.vertex_titles.values().copied().collect::>(), b.index_title) }; - let mirrors: Vec> = { - let mut v: Vec> = vbs.iter().map(|&(va, bytes, _)| mirrored(va, bytes as usize)).collect(); - v.push(ib.and_then(|(va, bytes, _)| mirrored(va, bytes as usize))); + let mirrors: Vec)>> = { + let mut v: Vec<_> = vbs.iter().map(|&(va, bytes, _)| mirror_entry(va, bytes as usize)).collect(); + v.push(ib.and_then(|(va, bytes, _)| mirror_entry(va, bytes as usize))); if v.iter().all(Option::is_none) { return; } @@ -5927,14 +6013,16 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs sync_count(SYNC_MIRRORED, 1); // (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) + // page the title freed or protected since keeps what the mirror had); the caller holds the + // mirror's lock 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_pages((va + from) as usize, (mirror + from as usize) as *mut u8, len); + let wrote = update_mirror((va + from) as usize, (mirror + from as usize) as *mut u8, len); sync_count(SYNC_COPIES, 1); sync_count(SYNC_BYTES, len as u64); + sync_count(SYNC_WRITTEN, wrote as u64); } }; // the vertices read: [lo, hi) @@ -5944,9 +6032,12 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs let (from, len) = (first as u64 * size, count as u64 * size); let n = (len.min((bytes as u64).saturating_sub(from)) / 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 + // the title did to its memory; an index buffer without a mirror is checked. The + // mirror's lock is held from the copy to the range: another list's copy of new + // indices into it is not seen as "nothing differs" before its write is counted + let _lock = mirrors[vbs.len()].map(|(_, lock)| lock.lock().unwrap()); let at = match mirrors[vbs.len()] { - Some(m) => { + Some((m, _)) => { copy(va, m, bytes, from, len); Some(m + from as usize) } @@ -5955,27 +6046,34 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs if n == 0 || at.is_none() { (0, u64::MAX) } else { - sync_count(SYNC_INDICES, n as u64); 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 }; - // (a strip's cut value counts as an index: whether 0xffff is one is the - // topology's to say, and a range too wide only copies more) - lo = lo.min(i); - hi = hi.max(i); - } - if lo > hi { - return; + let scan = || { + sync_count(SYNC_INDICES, n as u64); + 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 }; + // (a strip's cut value counts as an index: whether 0xffff is one is the + // topology's to say, and a range too wide only copies more) + lo = lo.min(i); + hi = hi.max(i); + } + ((lo as i64 + base as i64).max(0) as u64, (hi as i64 + base as i64 + 1).max(0) as u64) + }; + // indices read from a mirror no draw has written since are scanned once (#2393); + // an index buffer without a mirror is scanned at every draw + if mirrors[vbs.len()].is_some() { + cached_vertex_range((va, bytes, format, first, count, base), MIRROR_WRITES.load(Ordering::Acquire), scan) + } else { + scan() } - ((lo as i64 + base as i64).max(0) as u64, (hi as i64 + base as i64 + 1).max(0) as u64) } } (Some(_), None) => (0, u64::MAX), (None, _) => (first_vertex as u64, first_vertex as u64 + vertices as u64), }; for (k, &(va, bytes, stride)) in vbs.iter().enumerate() { - let Some(m) = mirrors[k] else { continue }; + let Some((m, lock)) = mirrors[k] else { continue }; + let _lock = lock.lock().unwrap(); // a buffer stepped by instance is not told apart: with instances (callers pass more // than 1 for a first instance other than 0 too), all of it if instances > 1 || hi == u64::MAX || stride == 0 || hi.saturating_mul(stride as u64) > bytes as u64 { @@ -7542,6 +7640,12 @@ mod tests { } use std::sync::Arc; + thread_local! { + /// run by `update_mirror` on this thread after it wrote into a mirror and before it bumps + /// `MIRROR_WRITES` + pub(super) static BEFORE_MIRROR_WRITES: std::cell::RefCell>> = std::cell::RefCell::new(None); + } + /// An internal wait shows in the watchdog's summary while its fence is short of the value, /// and is gone from it once the fence gets there. #[test] @@ -11757,6 +11861,182 @@ mod tests { } } + /// A mirror is written only on the pages whose bytes differ from the title's (#2393): with + /// the same bytes on three of four pages, the write-watch on the mirror sees one page + /// written. A page the title made unreadable keeps the mirror's bytes, and the pages around + /// it are brought up to date. + #[test] + fn a_mirror_is_written_only_where_the_title_bytes_differ() { + use windows_sys::Win32::System::Memory::{GetWriteWatch, VirtualAlloc, VirtualProtect, MEM_COMMIT, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + const MEM_WRITE_WATCH: u32 = 0x20_0000; + unsafe { + let len = 0x4000usize; + let src = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + let mirror = VirtualAlloc(std::ptr::null(), len, MEM_COMMIT | MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) as *mut u8; + assert!(!src.is_null() && !mirror.is_null()); + std::ptr::write_bytes(src, 0x11, len); + std::ptr::write_bytes(mirror, 0x11, len); + let written = || { + let mut pages = [std::ptr::null_mut::(); 8]; + let (mut n, mut gran) = (pages.len(), 0u32); + assert_eq!(GetWriteWatch(1, mirror as *const c_void, len, pages.as_mut_ptr(), &mut n, &mut gran), 0); + pages[..n].iter().map(|&p| (p as usize - mirror as usize) / 0x1000).collect::>() + }; + written(); + // the title rewrites every page, with new bytes on page 2 only + std::ptr::write_bytes(src, 0x11, len); + std::ptr::write_bytes(src.add(0x2000), 0x22, 0x1000); + assert_eq!(update_mirror(src as usize + 0x10, mirror.add(0x10), len - 0x20), 0x1000); + assert_eq!(written(), vec![2], "only the page that differs is written"); + assert!((0x2000..0x3000).all(|k| *mirror.add(k) == 0x22)); + assert_eq!(update_mirror(src as usize, mirror, len), 0, "nothing differs"); + assert_eq!(written(), Vec::::new()); + // new bytes on pages 0 and 3, page 1 unreadable + std::ptr::write_bytes(src, 0x33, len); + let mut old = 0u32; + assert_ne!(VirtualProtect(src.add(0x1000) as *const _, 0x1000, PAGE_NOACCESS, &mut old), 0); + update_mirror(src as usize, mirror, len); + assert!((0..0x1000).all(|k| *mirror.add(k) == 0x33), "the first page is copied"); + assert!((0x1000..0x2000).all(|k| *mirror.add(k) == 0x11), "the unreadable page keeps the mirror's bytes"); + assert!((0x2000..0x4000).all(|k| *mirror.add(k) == 0x33), "the pages after it are copied"); + } + } + + /// An indexed draw's vertex range is scanned again only after a mirror was written. + #[test] + fn a_vertex_range_is_scanned_again_only_after_a_mirror_write() { + let key = (0x7e57_0000_2393u64, 6, DXGI_FORMAT_R16_UINT.0, 0, 3, 0); + let mut scans = 0; + let mut range = |writes, r| { + cached_vertex_range(key, writes, || { + scans += 1; + r + }) + }; + assert_eq!(range(5, (0, 3)), (0, 3)); + assert_eq!(range(5, (7, 9)), (0, 3), "no write since: the range scanned before"); + assert_eq!(range(6, (7, 9)), (7, 9), "a write since: scanned again"); + assert_eq!(scans, 2); + } + + /// Through the per-draw sync: an indexed draw with unchanged indices copies the range they + /// reach, and once the title changes the indices, the vertices they now reach are copied. + #[test] + fn the_mirror_sync_follows_changed_indices() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, 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); + let last = vb_bytes / stride - 1; + 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_0001_2393usize 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)); + }); + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 1); + std::ptr::write_bytes(vb, 0x22, vb_bytes as usize); + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 1); + assert!((0..3 * stride as usize).all(|k| *vm.add(k) == 0x22), "the vertices the indices reach are copied"); + assert_eq!(*vm.add((last * stride) as usize), 0x11, "the ones they do not reach are not"); + *ib.add(2) = last as u16; + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 1); + assert!((0..stride as usize).all(|k| *vm.add((last * stride) as usize + k) == 0x22), "the vertex the changed index reaches is copied"); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + } + } + + /// Two lists share an index mirror. List B copies the title's changed indices into it and + /// pauses before `MIRROR_WRITES` counts the write. List A then finds nothing that differs, + /// and must not reuse the range it scanned before the change: it waits on the mirror's lock + /// and copies the vertex the changed index reaches. + #[test] + fn a_vertex_range_is_not_reused_while_another_list_writes_the_indices() { + use std::sync::mpsc::channel; + use std::time::Duration; + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, 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); + let last = vb_bytes / stride - 1; + std::ptr::write_bytes(vb, 0x11, vb_bytes as usize); + for (k, i) in [0u16, 1, 2].into_iter().enumerate() { + *ib.add(k) = i; + } + // list A draws with both buffers, list B only binds the indices (it copies no vertices) + let (list_a, list_b) = (0x7e57_0002_2533usize, 0x7e57_0003_2533usize); + assert_ne!(gpu_va(list_a as *mut c_void, vb as u64, vb_bytes as usize, "test vertex buffer", true), vb as u64); + assert_ne!(gpu_va(list_a as *mut c_void, ib as u64, 6, "test index buffer", true), ib as u64); + let vm = mirrored(vb as u64, vb_bytes as usize).unwrap() as usize; + with_bindings(list_a as *mut c_void, |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)); + }); + with_bindings(list_b as *mut c_void, |b| b.index_title = Some((ib as u64, 6, DXGI_FORMAT_R16_UINT.0))); + + let (go_a, a_waits) = channel::<()>(); + let (a_scanned, a_has_scanned) = channel::<()>(); + let (a_done, a_finished) = channel::<()>(); + // A scans indices 0..=2 on its own thread (the range is kept per thread) + let a = std::thread::spawn(move || { + sync_title_buffers(list_a as *mut c_void, Some((0, 3, 0)), 0, 0, 1); + a_scanned.send(()).unwrap(); + a_waits.recv().unwrap(); + sync_title_buffers(list_a as *mut c_void, Some((0, 3, 0)), 0, 0, 1); + a_done.send(()).unwrap(); + }); + a_has_scanned.recv().unwrap(); + // the title writes new vertices and an index that reaches the last one + std::ptr::write_bytes(vb, 0x22, vb_bytes as usize); + *ib.add(2) = last as u16; + + let (b_paused, b_is_paused) = channel::<()>(); + let (release_b, b_waits) = channel::<()>(); + let b = std::thread::spawn(move || { + let (paused, waits) = (b_paused, b_waits); + BEFORE_MIRROR_WRITES.with_borrow_mut(|f| { + *f = Some(Box::new(move || { + paused.send(()).unwrap(); + waits.recv().unwrap(); + })) + }); + sync_title_buffers(list_b as *mut c_void, Some((0, 3, 0)), 0, 0, 1); + }); + b_is_paused.recv().unwrap(); + go_a.send(()).unwrap(); + // A has the time to finish its draw (it may not: it waits for B's lock) + let _ = a_finished.recv_timeout(Duration::from_millis(300)); + release_b.send(()).unwrap(); + b.join().unwrap(); + a.join().unwrap(); + let vm = vm as *const u8; + assert!((0..stride as usize).all(|k| *vm.add((last * stride) as usize + k) == 0x22), "list A copies the vertex the changed index reaches"); + let mut g = LISTS.lock().unwrap(); + g.as_mut().unwrap().remove(&list_a); + g.as_mut().unwrap().remove(&list_b); + } + } + #[test] fn occlusion_tracks_dropped_draws_and_active_counter() { let mut occ = Occlusion::default(); diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index dfebd69da3..e1c9fc0b1a 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -182,8 +182,8 @@ pub fn host_main(boot_path: &Path) -> i32 { if crate::hle::d3d12x::list_x::sync_row_due(&s, slowest) { let ms = |ns: u64| ns as f64 / 1e6; crate::xlog_info!( - "buffer mirrors (2 s): {} draws synced, {} with a mirror; {} copies ({} whole buffers), {} KB; {} indices scanned; {} readable() calls ({} over 16 pages), {:.2} ms, slowest {:.2} ms; {:.2} ms in all", - s[0], s[1], s[2], s[3], s[4] >> 10, s[5], s[6], s[7], ms(s[8]), ms(slowest), ms(s[9]) + "buffer mirrors (2 s): {} draws synced, {} with a mirror; {} copies ({} whole buffers), {} KB compared, {} KB written; {} indices scanned; {} readable() calls ({} over 16 pages), {:.2} ms, slowest {:.2} ms; {:.2} ms in all", + s[0], s[1], s[2], s[3], s[4] >> 10, s[9] >> 10, s[5], s[6], s[7], ms(s[8]), ms(slowest), ms(s[10]) ); } last_sync = sync; From 5ae230042b11a998cc86163268510dba242718a9 Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:16:19 +0000 Subject: [PATCH 4/5] D3D12.X: a mirror chunk with an unreadable page is compared, not rewritten When `ReadProcessMemory` failed for a 64 KiB chunk (the title freed or protected a page of it, #2392), `update_mirror` copied the chunk straight into the mirror with `copy_committed_region` and counted all of it as written. From then on every draw reading that range rewrote the whole chunk, the sparse look uploaded it again and `MIRROR_WRITES` threw away the cached index ranges: the per-draw rewrite #2393 removes elsewhere. The chunk is now read into the scratch buffer, filled first with the mirror's bytes so that the unreadable page compares equal, and goes through the same page-by-page compare as a readable chunk. Part of #2393. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015csBcd63KUE2T1kW2P15nC --- crates/xcl/src/hle/d3d12x/list_x.rs | 37 ++++++++++++++++------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index 81577f39a8..fd06d99430 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5849,8 +5849,8 @@ thread_local! { /// Brings `len` bytes of a mirror at `mirror` up to the title's at `src`, writing only the pages /// whose bytes differ (#2393: a title that rewrites a buffer with the same bytes every frame /// otherwise has every page of the mirror written at every draw, and the sparse look uploads -/// each one again). A chunk the title freed or protected a page of is copied around that page -/// (#2392). Returns the bytes written. The sync calls it with the mirror's lock held, so another +/// each one again). A chunk the title freed or protected a page of is read around that page +/// (#2392), which keeps the mirror's bytes. Returns the bytes written. The sync calls it with the mirror's lock held, so another /// thread does not see the bytes written before `MIRROR_WRITES` says so. unsafe fn update_mirror(src: usize, mirror: *mut u8, len: usize) -> usize { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; @@ -5864,20 +5864,21 @@ unsafe fn update_mirror(src: usize, mirror: *mut u8, len: usize) -> usize { let n = (len - off).min(CHUNK); let mut read = 0usize; if ReadProcessMemory(GetCurrentProcess(), (src + off) as *const c_void, buf.as_mut_ptr().cast(), n, &mut read) == 0 { - super::title_textures::copy_committed_pages(src + off, mirror.add(off), n); - wrote += n; - } else { - // page by page of the title's memory - let mut p = 0; - while p < n { - let e = ((((src + off + p) & !0xfff) + 0x1000) - (src + off)).min(n); - let to = std::slice::from_raw_parts_mut(mirror.add(off + p), e - p); - if to != &buf[p..e] { - to.copy_from_slice(&buf[p..e]); - wrote += e - p; - } - p = e; + // around the page the title freed or protected, which keeps the mirror's bytes + // and so compares equal + buf[..n].copy_from_slice(std::slice::from_raw_parts(mirror.add(off), n)); + super::title_textures::copy_committed_pages(src + off, buf.as_mut_ptr(), n); + } + // page by page of the title's memory + let mut p = 0; + while p < n { + let e = ((((src + off + p) & !0xfff) + 0x1000) - (src + off)).min(n); + let to = std::slice::from_raw_parts_mut(mirror.add(off + p), e - p); + if to != &buf[p..e] { + to.copy_from_slice(&buf[p..e]); + wrote += e - p; } + p = e; } off += n; } @@ -11895,10 +11896,14 @@ mod tests { std::ptr::write_bytes(src, 0x33, len); let mut old = 0u32; assert_ne!(VirtualProtect(src.add(0x1000) as *const _, 0x1000, PAGE_NOACCESS, &mut old), 0); - update_mirror(src as usize, mirror, len); + assert_eq!(update_mirror(src as usize, mirror, len), 0x3000); + assert_eq!(written(), vec![0, 2, 3]); assert!((0..0x1000).all(|k| *mirror.add(k) == 0x33), "the first page is copied"); assert!((0x1000..0x2000).all(|k| *mirror.add(k) == 0x11), "the unreadable page keeps the mirror's bytes"); assert!((0x2000..0x4000).all(|k| *mirror.add(k) == 0x33), "the pages after it are copied"); + // with the page still unreadable and nothing new, the chunk around it is not written again + assert_eq!(update_mirror(src as usize, mirror, len), 0, "nothing differs around the unreadable page"); + assert_eq!(written(), Vec::::new()); } } From 509709e747cd70d43cb77a1890ec0571c086520a Mon Sep 17 00:00:00 2001 From: KOLESNiii <102358205+KOLESNiii@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:19:39 +0000 Subject: [PATCH 5/5] D3D12.X: a cached index range is checked against its own mirror's writes The vertex range of an indexed draw was scanned again after a write into any mirror (`MIRROR_WRITES`, one count for all of them). A title that writes new vertices before its draws (a ring it fills through the frame) writes the vertex mirror at nearly every draw, so its unchanged indices were scanned again at nearly every draw. Each mirror now keeps its own count of the sync's writes, in the lock the sync already holds while it writes into that mirror, and a cached range is checked against the count of the mirror its indices are in. `MIRROR_WRITES` is gone. Part of #2393. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015csBcd63KUE2T1kW2P15nC --- crates/xcl/src/hle/d3d12x/list_x.rs | 138 ++++++++++++++++++---------- 1 file changed, 89 insertions(+), 49 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index fd06d99430..1ced48c786 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -5746,9 +5746,10 @@ unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: b /// Ranges of the title's memory with a mirror in unified memory: (start, bytes, mirror). A /// 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. Each has a lock that is held while -/// the sync writes into it (`update_mirror`). -static MIRRORS: Mutex)>> = Mutex::new(Vec::new()); +/// inside a mirrored range uses that mirror at its offset. Each has the count of the sync's +/// writes into it, locked while the sync writes into it (`update_mirror`): an index range +/// scanned at one count is the same at the next draw while the count has not changed. +static MIRRORS: Mutex)>> = Mutex::new(Vec::new()); /// bytes of mirrors made (never freed) static MIRROR_BYTES: AtomicU64 = AtomicU64::new(0); /// Append generation. Incremented while `MIRRORS` is locked, before publishing a new range, so a @@ -5777,8 +5778,8 @@ fn cached_mirror( mirror_in(&cache.1, va, bytes) } -/// Where `[va, va + bytes)` is in a mirror, if it is in one, and that mirror's lock. -fn mirror_entry(va: u64, bytes: usize) -> Option<(usize, &'static Mutex<()>)> { +/// Where `[va, va + bytes)` is in a mirror, if it is in one, and that mirror's count of writes. +fn mirror_entry(va: u64, bytes: usize) -> Option<(usize, &'static Mutex)> { MIRRORS.lock().unwrap().iter().find(|&&(s, l, _, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m, lock)| (m + (va - s) as usize, lock)) } @@ -5825,8 +5826,7 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { // Invalidate cached misses before publishing while still holding the lock. A lookup that sees // the new generation blocks on `g` until this range is present in the refreshed snapshot. MIRROR_GENERATION.fetch_add(1, Ordering::Release); - g.push((start, len, p, Box::leak(Box::new(Mutex::new(()))))); - MIRROR_WRITES.fetch_add(1, Ordering::Release); + g.push((start, len, p, Box::leak(Box::new(Mutex::new(0))))); let total = MIRROR_BYTES.fetch_add(len as u64, Ordering::Relaxed) + len as u64; if g.len() <= 8 || g.len().is_power_of_two() { crate::xlog_warn!("D3D12.X: {what} at {va:#x} ({bytes} bytes) is outside unified memory – {start:#x}..{:#x} mirrored at {p:#x}, each draw copies what it reads ({} mirrors, {} MB)", start + len as u64, g.len(), total >> 20); @@ -5834,15 +5834,11 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { Some(p + (va - start) as usize) } -/// Bumped after each write into a mirror: an index range scanned at one value is the same at -/// the next draw while it has not changed. -static MIRROR_WRITES: AtomicU64 = AtomicU64::new(0); - thread_local! { // the title's bytes of one chunk, read to be compared with the mirror's static SYNC_SCRATCH: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; // the vertex range of an indexed draw whose indices are in a mirror: (index va, bytes, - // format, first, count, base vertex) → (lo, hi, `MIRROR_WRITES` when scanned) + // format, first, count, base vertex) → (lo, hi, the index mirror's writes when scanned) static INDEX_RANGES: std::cell::RefCell> = std::cell::RefCell::new(HashMap::new()); } @@ -5850,13 +5846,14 @@ thread_local! { /// whose bytes differ (#2393: a title that rewrites a buffer with the same bytes every frame /// otherwise has every page of the mirror written at every draw, and the sparse look uploads /// each one again). A chunk the title freed or protected a page of is read around that page -/// (#2392), which keeps the mirror's bytes. Returns the bytes written. The sync calls it with the mirror's lock held, so another -/// thread does not see the bytes written before `MIRROR_WRITES` says so. +/// (#2392), which keeps the mirror's bytes. Returns the bytes written. The sync calls it with +/// the mirror's count of writes locked, and counts a write before unlocking it, so another +/// thread does not see the bytes written before the count says so. unsafe fn update_mirror(src: usize, mirror: *mut u8, len: usize) -> usize { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; const CHUNK: usize = 0x1_0000; - let wrote = SYNC_SCRATCH.with_borrow_mut(|buf| { + SYNC_SCRATCH.with_borrow_mut(|buf| { buf.resize(CHUNK, 0); let mut wrote = 0; let mut off = 0; @@ -5883,19 +5880,11 @@ unsafe fn update_mirror(src: usize, mirror: *mut u8, len: usize) -> usize { off += n; } wrote - }); - #[cfg(test)] - if wrote > 0 { - tests::BEFORE_MIRROR_WRITES.with_borrow_mut(|f| f.as_mut().map(|f| f())); - } - if wrote > 0 { - MIRROR_WRITES.fetch_add(1, Ordering::Release); - } - wrote + }) } -/// The vertex range `scan` gives for `key`, scanned again only when a mirror was written since -/// the last scan of `key` on this thread (`writes`: `MIRROR_WRITES` now). +/// The vertex range `scan` gives for `key`, scanned again only when its index mirror was +/// written since the last scan of `key` on this thread (`writes`: that mirror's count now). fn cached_vertex_range(key: (u64, u32, i32, u32, u32, i32), writes: u64, scan: impl FnOnce() -> (u64, u64)) -> (u64, u64) { INDEX_RANGES.with_borrow_mut(|m| { if let Some(&(lo, hi, w)) = m.get(&key) { @@ -6003,7 +5992,7 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs let Some(b) = g.as_ref().and_then(|m| m.get(&(list as usize))).map(|s| &s.bindings) else { return }; (b.vertex_titles.values().copied().collect::>(), b.index_title) }; - let mirrors: Vec)>> = { + let mirrors: Vec)>> = { let mut v: Vec<_> = vbs.iter().map(|&(va, bytes, _)| mirror_entry(va, bytes as usize)).collect(); v.push(ib.and_then(|(va, bytes, _)| mirror_entry(va, bytes as usize))); if v.iter().all(Option::is_none) { @@ -6014,13 +6003,18 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs sync_count(SYNC_MIRRORED, 1); // (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); the caller holds the - // mirror's lock - let copy = |va: u64, mirror: usize, bytes: u32, from: u64, len: u64| { + // page the title freed or protected since keeps what the mirror had); `writes`: the mirror's + // count of writes, locked by the caller + let copy = |va: u64, mirror: usize, bytes: u32, from: u64, len: u64, writes: &mut u64| { let from = from.min(bytes as u64); let len = len.min(bytes as u64 - from) as usize; if len > 0 { let wrote = update_mirror((va + from) as usize, (mirror + from as usize) as *mut u8, len); + if wrote > 0 { + #[cfg(test)] + tests::BEFORE_MIRROR_WRITES.with_borrow_mut(|f| f.as_mut().map(|f| f())); + *writes += 1; + } sync_count(SYNC_COPIES, 1); sync_count(SYNC_BYTES, len as u64); sync_count(SYNC_WRITTEN, wrote as u64); @@ -6034,15 +6028,15 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs let n = (len.min((bytes as u64).saturating_sub(from)) / 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. The - // mirror's lock is held from the copy to the range: another list's copy of new + // mirror's count is locked from the copy to the range: another list's copy of new // indices into it is not seen as "nothing differs" before its write is counted - let _lock = mirrors[vbs.len()].map(|(_, lock)| lock.lock().unwrap()); - let at = match mirrors[vbs.len()] { - Some((m, _)) => { - copy(va, m, bytes, from, len); + let mut writes = mirrors[vbs.len()].map(|(_, w)| w.lock().unwrap()); + let at = match (mirrors[vbs.len()], writes.as_deref_mut()) { + (Some((m, _)), Some(writes)) => { + copy(va, m, bytes, from, len, writes); Some(m + from as usize) } - None => (n > 0 && sync_readable((va + from) as usize, n * size as usize)).then_some((va + from) as usize), + _ => (n > 0 && sync_readable((va + from) as usize, n * size as usize)).then_some((va + from) as usize), }; if n == 0 || at.is_none() { (0, u64::MAX) @@ -6050,6 +6044,8 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs let at = at.unwrap() as *const u8; let scan = || { sync_count(SYNC_INDICES, n as u64); + #[cfg(test)] + tests::INDEX_SCANS.set(tests::INDEX_SCANS.get() + 1); 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 }; @@ -6062,10 +6058,9 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs }; // indices read from a mirror no draw has written since are scanned once (#2393); // an index buffer without a mirror is scanned at every draw - if mirrors[vbs.len()].is_some() { - cached_vertex_range((va, bytes, format, first, count, base), MIRROR_WRITES.load(Ordering::Acquire), scan) - } else { - scan() + match writes { + Some(writes) => cached_vertex_range((va, bytes, format, first, count, base), *writes, scan), + None => scan(), } } } @@ -6073,15 +6068,15 @@ unsafe fn sync_mirrors(list: *mut c_void, indexed: Option<(u32, u32, i32)>, firs (None, _) => (first_vertex as u64, first_vertex as u64 + vertices as u64), }; for (k, &(va, bytes, stride)) in vbs.iter().enumerate() { - let Some((m, lock)) = mirrors[k] else { continue }; - let _lock = lock.lock().unwrap(); + let Some((m, writes)) = mirrors[k] else { continue }; + let mut writes = writes.lock().unwrap(); // a buffer stepped by instance is not told apart: with instances (callers pass more // than 1 for a first instance other than 0 too), all of it if instances > 1 || hi == u64::MAX || stride == 0 || hi.saturating_mul(stride as u64) > bytes as u64 { sync_count(SYNC_WHOLE, 1); - copy(va, m, bytes, 0, bytes as u64); + copy(va, m, bytes, 0, bytes as u64, &mut writes); } else { - copy(va, m, bytes, lo * stride as u64, (hi - lo) * stride as u64); + copy(va, m, bytes, lo * stride as u64, (hi - lo) * stride as u64, &mut writes); } } } @@ -7642,9 +7637,11 @@ mod tests { use std::sync::Arc; thread_local! { - /// run by `update_mirror` on this thread after it wrote into a mirror and before it bumps - /// `MIRROR_WRITES` + /// run by the mirror sync on this thread after it wrote into a mirror and before it counts + /// the write pub(super) static BEFORE_MIRROR_WRITES: std::cell::RefCell>> = std::cell::RefCell::new(None); + /// index scans of the mirror sync on this thread + pub(super) static INDEX_SCANS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// An internal wait shows in the watchdog's summary while its fence is short of the value, @@ -11964,10 +11961,53 @@ mod tests { } } + /// An indexed draw whose indices did not change keeps its vertex range while other mirrors + /// are written: the title writes new vertices before each draw, which writes the vertex + /// mirror, and the indices are scanned again only once they change. Before, one count of + /// writes for all mirrors made every draw after a vertex write scan its indices again. + #[test] + fn a_vertex_range_is_kept_while_only_other_mirrors_are_written() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, 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_0004_2533usize 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)); + }); + let scans = INDEX_SCANS.get(); + for v in [0x22u8, 0x33, 0x44] { + std::ptr::write_bytes(vb, v, vb_bytes as usize); + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 1); + assert!((0..3 * stride as usize).all(|k| *vm.add(k) == v), "the vertices the indices reach are copied"); + } + assert_eq!(INDEX_SCANS.get() - scans, 1, "the unchanged indices are scanned once"); + *ib.add(2) = 9; + sync_title_buffers(list, Some((0, 3, 0)), 0, 0, 1); + assert_eq!(INDEX_SCANS.get() - scans, 2, "changed indices are scanned again"); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + } + } + /// Two lists share an index mirror. List B copies the title's changed indices into it and - /// pauses before `MIRROR_WRITES` counts the write. List A then finds nothing that differs, - /// and must not reuse the range it scanned before the change: it waits on the mirror's lock - /// and copies the vertex the changed index reaches. + /// pauses before the mirror's count of writes counts it. List A then finds nothing that + /// differs, and must not reuse the range it scanned before the change: it waits on the + /// mirror's lock and copies the vertex the changed index reaches. #[test] fn a_vertex_range_is_not_reused_while_another_list_writes_the_indices() { use std::sync::mpsc::channel;