From d8c75c5c135a368f4ea46efe026dad572d3abe74 Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:51:23 +0100 Subject: [PATCH 1/3] D3D12.X: a look finds the blocks new to the watched ranges by their change MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `hot_runs` makes a block new to the watched ranges hot. To find those it kept a set of all blocks (2 MiB) of the ranges of the last look and, each time the ranges changed, made the set again over every block of every range while holding `HOT` (the walk thread takes it too). The ranges are made again whenever a tile is mapped, a texture is placed, a GPU-view page is shown: in a retail title's world that is ~3.5 GB in 16 ranges, ~1,800 blocks, and the ranges change between many of the submits. Now `new_blocks` compares the ranges with the last look's (both sorted and apart, as `watch_ranges` makes them): a range found among the old ones as it is has no new block, and a block of a changed range is new when no old range meets it, which is what the set said. 16 ranges with one changed: 4 µs against 1.4 ms for a set of all their blocks (debug build, the test's own timing; not measured in a release build or a game). Test: new_blocks_are_those_no_old_range_meets (against a set of all the old blocks: ranges grown, shifted, merged, new, gone, in part of a block). Ported from amd-dev without its reasons for a hot block (`HOT_NEW`, `look_stats::HOT_WHY`), which main does not have: a new block is put in with its time only, as before. (cherry picked from commit 5b660277a9460246eca668b144872fe4c66c1594) (cherry picked from commit 5ff2b66338097c8d02657d79b524592c453a11a1) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 108 +++++++++++++++++--- 1 file changed, 93 insertions(+), 15 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..30311bc238 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -1502,10 +1502,33 @@ fn hot_for() -> std::time::Duration { struct HotBlocks { /// block -> when a look or the walk last found a written page in it hot: BTreeMap, - /// the ranges `known` was made for + /// the ranges of the last look (a block new to the ranges starts hot: `new_blocks`) ranges: Option>>, - /// the blocks of those ranges (a block new to the ranges starts hot) - known: std::collections::HashSet, +} + +/// The `HOT_BLOCK`s of `ranges` that no range of `old` meets (both sorted and apart, as `watch_ranges` +/// makes them): a range found in `old` as it is has none, so the ranges changed by a mapping are +/// gone over and not all blocks of all of them. (Before, a set of all the blocks was made again +/// at each change of the ranges: ~1,800 blocks, 3.5 GB, in a retail title's world.) +fn new_blocks(old: &[(usize, usize)], ranges: &[(usize, usize)]) -> Vec { + let met = |lo: usize, hi: usize| { + let i = old.partition_point(|&(a, n)| a + n <= lo); + old.get(i).is_some_and(|&(a, _)| a < hi) + }; + let mut out = Vec::new(); + for &(base, size) in ranges { + if old.binary_search(&(base, size)).is_ok() { + continue; + } + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + if !met(b, b + HOT_BLOCK) { + out.push(b); + } + b += HOT_BLOCK; + } + } + out } static HOT: Mutex> = Mutex::new(None); @@ -1525,19 +1548,10 @@ fn hot_runs(ranges: &Arc>, now: std::time::Instant) -> (Vec< let h = g.get_or_insert_with(HotBlocks::default); // a block new to the ranges starts hot: memory just mapped is often written and used at once if !h.ranges.as_ref().is_some_and(|r| Arc::ptr_eq(r, ranges)) { - let mut known = std::collections::HashSet::with_capacity(h.known.len()); - for &(base, size) in ranges.iter() { - let mut b = base & !(HOT_BLOCK - 1); - while b < base + size { - if !h.known.contains(&b) { - h.hot.insert(b, now); - } - known.insert(b); - b += HOT_BLOCK; - } + let old = h.ranges.replace(Arc::clone(ranges)); + for b in new_blocks(old.as_deref().map_or(&[], |v| &v[..]), ranges) { + h.hot.insert(b, now); } - h.known = known; - h.ranges = Some(Arc::clone(ranges)); } let keep = hot_for(); h.hot.retain(|_, t| now.saturating_duration_since(*t) < keep); @@ -5636,6 +5650,70 @@ pub(super) mod tests { assert_eq!(watch_ranges(®ions, vec![(0x1000_0000, 0x1000_1000), (0x2008_0000, 0x2009_0000)]), vec![(0x2008_0000, 0x1_0000)]); } + /// `new_blocks` finds the blocks a set of all the old ranges' blocks did not have (what + /// `hot_runs` made before), going over the changed ranges only. + #[test] + fn new_blocks_are_those_no_old_range_meets() { + let blocks_of = |ranges: &[(usize, usize)]| -> std::collections::BTreeSet { + let mut out = std::collections::BTreeSet::new(); + for &(base, size) in ranges { + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + out.insert(b); + b += HOT_BLOCK; + } + } + out + }; + let reference = |old: &[(usize, usize)], new: &[(usize, usize)]| -> Vec { + let known = blocks_of(old); + let mut v: Vec = Vec::new(); + for &(base, size) in new { + let mut b = base & !(HOT_BLOCK - 1); + while b < base + size { + if !known.contains(&b) { + v.push(b); + } + b += HOT_BLOCK; + } + } + v + }; + let g = 0x4000_0000usize; + let m = 1usize << 20; + let old = vec![(g, 8 * m), (g + 64 * m, 3 * m), (g + 70 * m + 0x1000, 0x1000), (g + 200 * m, 64 * m)]; + let cases: Vec> = vec![ + old.clone(), + vec![], + // one grown at its end, one shifted inside its blocks, one new, one gone + vec![(g, 13 * m), (g + 64 * m + 0x1000, 3 * m), (g + 100 * m, 5 * m), (g + 200 * m, 64 * m)], + // a range now over what two were + vec![(g, 80 * m)], + // pieces of blocks the old ranges met only in part + vec![(g + 67 * m - 0x1000, 0x2000), (g + 71 * m, 0x1000), (g + 264 * m, 0x1000)], + ]; + for new in &cases { + assert_eq!(new_blocks(&old, new), reference(&old, new), "{new:x?}"); + assert_eq!(new_blocks(&[], new), reference(&[], new)); + } + assert!(new_blocks(&old, &old).is_empty()); + assert_eq!(new_blocks(&old, &cases[2]), vec![g + 8 * m, g + 10 * m, g + 12 * m, g + 100 * m, g + 102 * m, g + 104 * m]); + // (the measured case: ~1,800 blocks in 16 ranges, one of them changed) + let big: Vec<(usize, usize)> = (0..16).map(|k| (g + k * (256 * m), 224 * m)).collect(); + let mut changed = big.clone(); + changed[7].1 += 2 * m; + let t = std::time::Instant::now(); + for _ in 0..100 { + assert_eq!(new_blocks(&big, &changed), vec![changed[7].0 + 224 * m]); + } + let ours = t.elapsed(); + let t = std::time::Instant::now(); + for _ in 0..100 { + assert_eq!(reference(&big, &changed), vec![changed[7].0 + 224 * m]); + } + println!("new blocks of 16 ranges, one changed: {:?} a time, a set of all blocks {:?}", ours / 100, t.elapsed() / 100); + } + #[test] fn watch_ranges_merge_at_the_gap_limit_and_split_past_it() { let base = 0x1000_0000usize; From 2b0ef63e5286e1b3f519940456cc096d36ff636c Mon Sep 17 00:00:00 2001 From: raylitebull <287713799+raylitebull@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:33:43 +0100 Subject: [PATCH 2/3] D3D12.X: compare the pages a mapping changed under a texture before upload When CopyPageMappingsBatchX changed the pages under a texture read through its pages, those 64 KiB pages went up again with no comparison: no write watch fires for a clean pool page newly mapped. In a retail title's open world (RX 9070 XT) about 4400 textures per 1024 submits were read again that way ("25294 read again for a mapping changed under them" by 127 s), next to 7903 uploads of 2082 MB that took 1890 ms of the 1024 submits. The changed parts are now compared, page by page, with the hashes of what the PC texture got at its last upload (the same comparison CPU- written pages get; a page whose hash is not known differs), and only pages that differ go up. A page mapped again with the bytes the texture has (the same page after an unmap, a page moved in its pool) costs a hash instead of an upload. A render target or UAV texture, and one the GPU wrote that gives way, still sends its pages with no comparison. VIctory-Neo does the same: a remapped slot is digested again and only uploaded when its bytes differ. XCL_TEXTURE_REMAP_COMPARE=0 restores the old behaviour; on by default. A line every 1024 submits that upload says what went up and for what: whole textures, CPU-written pages, remapped pages, parts sent again behind another queue (count and MB each), how many remapped textures were compared and left out, and the GPU writes kept by XCL_GPU_WRITE_STAYS. It gives the breakdown the 2 GB could only be estimated from before. Tests: new title_textures::tests::remapped_pages_are_compared_with_what_ they_held. cargo test -p xcl --lib -- title_textures texture_upload: 53 passed, 0 failed (RX 9070 XT). Not measured on the title. Port onto main: amd-dev's XCL_GPU_WRITE_STAYS (c06cf419) is not on main, so its early return in mapping_changed and its test are left out; main's own GPU-write tracking decides instead: a texture whose gpu_written mark gives way to the mapping still sends its pages with no comparison. main clears gpu_written once the GPU's bytes are copied back (publish_download) but kept the hashes of the upload before the GPU's write, so a page mapped again with those old bytes would have looked the same and the PC texture kept the GPU's texels: a published GPU write now makes what the texture's pages held unknown (texture_upload::unknown), and the next comparison sends all of it. As a side effect a CPU write to such a texture after the copy-back sends it whole instead of in parts. The selection follows main's texture_needs_upload (pages to compare count like parts to send again) and main's Due (no displaced textures). The upload breakdown line described above is not in this commit: it is the next one, on its own. New test title_textures::tests::a_remapped_page_of_a_texture_the_gpu_ wrote_is_not_taken_for_what_it_held (fails without the unknown() call; remapped_pages_are_compared_with_what_they_held fails without the comparison). cargo +stable-x86_64-pc-windows-msvc test -p xcl --lib -- title_textures texture_upload: 77 passed, 0 failed, 1 ignored, no SKIPPED (Windows 11, Ryzen 7 7800X3D with Radeon iGPU, RTX 5070 Ti). Not measured on a title. (cherry picked from commit 01ec624f32b33c2f4115f677781432b498471111) (cherry picked from commit 02ceae6499f27b8614ceb7ff3dc28bb8ea0446f2) Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/texture_upload.rs | 26 +++ crates/xcl/src/hle/d3d12x/title_textures.rs | 184 +++++++++++++++++++- 2 files changed, 201 insertions(+), 9 deletions(-) diff --git a/crates/xcl/src/hle/d3d12x/texture_upload.rs b/crates/xcl/src/hle/d3d12x/texture_upload.rs index dfc1b7fce4..0cdb23c2cb 100644 --- a/crates/xcl/src/hle/d3d12x/texture_upload.rs +++ b/crates/xcl/src/hle/d3d12x/texture_upload.rs @@ -78,6 +78,9 @@ pub(super) struct Pages { last: Vec, /// what goes up again, and the uploads it has to come behind (`sent`) again: Option<(Change, Vec)>, + /// parts (from, to) a mapping changed under since they were last looked at: compared with + /// what they held at its next upload, as written pages are (`recheck`) + recheck: Vec<(usize, usize)>, } /// Where an upload went: the queue, the fence of that queue's uploads and the value behind it. @@ -113,6 +116,7 @@ pub(super) fn all_sent(known: &Known, src: usize, size: usize) { k.hashes.clear(); k.hashes.resize(pages_of(src, size), 0); k.again = None; + k.recheck.clear(); } /// Nothing is known about what the PC texture holds: its next upload is of all of it. @@ -144,6 +148,28 @@ pub(super) fn stale(known: &Known, parts: Vec<(usize, usize)>) { }); } +/// `parts` of a texture (from, to) show other pages now (a mapping changed under them): its next +/// upload compares their bytes with what its pages held when they last went up, as for written +/// pages (`take_recheck`), and sends only those that differ. A page whose hash is not known (0) +/// differs; what is known of a page is what the PC texture got (`Hashes::note`), so equal bytes +/// are what it holds there. +pub(super) fn recheck(known: &Known, parts: Vec<(usize, usize)>) { + known.lock().unwrap().recheck.extend(parts); +} + +/// The pages of a texture at `src` to compare at this upload (`recheck`): their addresses, sorted. +pub(super) fn take_recheck(known: &Known, src: usize) -> Vec { + let parts = std::mem::take(&mut known.lock().unwrap().recheck); + let mut out: Vec = parts + .into_iter() + .filter(|r| r.0 < r.1) + .flat_map(|(from, to)| ((src + from) / PAGE * PAGE..src + to).step_by(PAGE)) + .collect(); + out.sort_unstable(); + out.dedup(); + out +} + /// `changed` of a texture (None: all of it) went up on `to`. An older upload of the texture on /// another queue that has not run yet (and that `to`'s queue has not waited for: `waited`) can land /// over it: it goes up again, behind that one (`take_again`). True when there is such a thing. diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 30311bc238..73307774c3 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -52,6 +52,8 @@ struct Due { whole: bool, /// what of it goes up again (`texture_upload::sent`) again: texture_upload::Change, + /// the pages a mapping changed under it, to be compared (`texture_upload::recheck`) + recheck: Vec, /// (`Entry::target`) target: bool, /// where its pages are read (`Entry::paged`) @@ -865,25 +867,48 @@ fn recheck_gpu_view_sources() { } /// The queue's page mappings changed `parts` (from, to) of `e` by call `call`. A texture read -/// through its pages sends them again with its next upload, as known changes with no comparison -/// (a clean pool page newly mapped holds bytes the PC texture never had): true, and it goes into -/// AGAIN. A shadowed one goes up whole once it is uncovered, as on a change of its source. The -/// GPU's write of a list submitted at or after that call stays; an older one gives way. +/// through its pages compares them with what they held at its next upload (`remap_compare`; no +/// write watch fires for a clean pool page newly mapped, whose bytes the PC texture may never have +/// had), or sends them again with no comparison: true, and it goes into AGAIN. A shadowed one goes +/// up whole once it is uncovered, as on a change of its source. The GPU's write of a list submitted +/// at or after that call stays; an older one gives way. fn mapping_changed(e: &mut Entry, call: u64, parts: Vec<(usize, usize)>, active: bool) -> bool { if !e.paged || e.pending || (e.gpu_written && e.written_call >= call) { return false; } - e.gpu_written = false; + let was_gpu_written = std::mem::take(&mut e.gpu_written); REREAD.fetch_add(1, Ordering::Relaxed); if !active { e.pending = true; PENDING.fetch_add(1, Ordering::Relaxed); return false; } - texture_upload::stale(&e.known, parts); + // (a render target or UAV the GPU may have written: no comparison with what the CPU's bytes + // were; nor one the GPU wrote, whose pages' hashes are not what it holds) + if remap_compare() && !e.target && !was_gpu_written { + texture_upload::recheck(&e.known, parts); + } else { + texture_upload::stale(&e.known, parts); + } true } +/// `XCL_TEXTURE_REMAP_COMPARE=0`: the pages a mapping changed under a texture go up again with no +/// comparison. On (the default), they are compared with what they held when they last went up, +/// as written pages are, and only those that differ go up. A title's streaming can map pages with +/// the bytes a texture already has (the same page again after an unmap, a page moved within its +/// pool); in a retail title's open world about 4400 textures a 1024 submits were read again for a +/// mapping changed under them, next to 7903 uploads of 2 GB in all. VIctory-Neo does the same: a +/// remapped slot is digested again and uploaded only when its bytes differ. +fn remap_compare() -> bool { + #[cfg(test)] + if let Some(v) = tests::REMAP_COMPARE.with(|s| s.get()) { + return v; + } + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_TEXTURE_REMAP_COMPARE").map_or(true, |v| v.trim() != "0")) +} + /// `e`'s source again (a texture in a GPU view): when it changed, `e` reads the new one and is /// uploaded at the next submit. Whether it changed. fn recheck_source(e: &mut Entry) -> bool { @@ -949,6 +974,10 @@ pub(super) fn publish_submission_effects(queue: Option, writes: & let epoch = NEXT_GPU_EPOCH.fetch_add(1, Ordering::Relaxed) + 1; let writer = GpuWriter { epoch, queue }; apply_gpu_writer(&mut e.gpu_writers, n, write.subresource, writer); + // (what its pages held at its last upload is no longer what the PC texture holds, + // also once the GPU's bytes are copied back: a page mapped again with the old + // bytes must not look the same, `mapping_changed`) + texture_upload::unknown(&e.known); if let Some(call) = call { // (`Entry::written_call`: a mapping changed by a later call is newer than this write) e.written_call = call; @@ -2128,6 +2157,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut visited += 1; } let mut again = texture_upload::Change::None; + let mut recheck = Vec::new(); if waiting.contains(&res) && e.cpu_backed && !e.gpu_written { let (queue, waited) = target.on(e.device); match texture_upload::take_again(&e.known, queue, waited) { @@ -2135,6 +2165,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut texture_upload::Again::NotYet => drop(later.insert(res)), texture_upload::Again::Nothing => {} } + recheck = texture_upload::take_recheck(&e.known, e.src); } if measure_selection && e.cpu_backed && !e.pending && !e.gpu_written { dirty_tests += 1; @@ -2142,7 +2173,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut // (a GPU-owned texture is never uploaded: `texture_needs_upload`) let wanted = texture_needs_upload( e.cpu_backed, - e.pending || again != texture_upload::Change::None, + e.pending || again != texture_upload::Change::None || !recheck.is_empty(), e.gpu_written, || { let i = dirty.partition_point(|&p| p + page as usize <= e.src); @@ -2173,6 +2204,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut known: Arc::clone(&e.known), whole, again, + recheck, target: e.target, pages, generation: e.generation, @@ -2808,10 +2840,11 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option // it would go up in part as it was and in part as it is; not for one read through // its pages, whose own address is not watched) let also = if mine.is_empty() || d.pages.is_some() || all_hot(d.src, size) { Vec::new() } else { written_pages(d.src, size) }; - if also.iter().all(|p| mine.binary_search(p).is_ok()) { + if d.recheck.is_empty() && also.iter().all(|p| mine.binary_search(p).is_ok()) { return mine.into(); } - let mut all = [mine, &also].concat(); + // (and the pages a mapping changed under it) + let mut all = [mine, &also, &d.recheck].concat(); all.sort_unstable(); all.dedup(); all.into() @@ -4872,6 +4905,8 @@ pub(super) mod tests { thread_local! { /// the VirtualQuery calls `mirror_source` made on this thread pub(super) static QUERIES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// `remap_compare` on this thread (None: as the environment says) + pub(super) static REMAP_COMPARE: std::cell::Cell> = const { std::cell::Cell::new(None) }; } /// One call of the queue's page-mapping method: `ranges` (kind, start, count) from GPU-view @@ -5014,6 +5049,135 @@ pub(super) mod tests { } } + /// The pages a mapping changed under a texture read through its pages are compared with what + /// they held at its last upload (`remap_compare`): a page with the same bytes sends nothing, + /// other bytes and an unmapped page go up. With the comparison off, and for a render target, + /// they go up as they are. + #[test] + fn remapped_pages_are_compared_with_what_they_held() { + use crate::hle::kernelx::mirrors::PAGE; + use texture_upload::{Again, Change}; + let _guard = TEST_LOCK.lock().unwrap(); + // (no submit looks while a texture of no resource is in the table) + let _refresh = REFRESH.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(185 * PAGE, 3); + // pool pages 0 and 1 hold the same bytes, page 2 others + std::ptr::write_bytes(home as *mut u8, 0x3C, 2 * PAGE); + std::ptr::write_bytes((home + 2 * PAGE) as *mut u8, 0x4D, PAGE); + map_pages(gpu, &[[0, 0, 1]], home, 3); + map_pages(gpu + PAGE, &[[0, 0, 1]], home, 3); + recheck_gpu_view_sources(); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + assert_eq!(tex.size() as usize, PAGE); + // keys of no resource, never dereferenced: a texture, a render target + let (res, rt) = (0x7E57_0000_B000usize, 0x7E57_0000_C000usize); + let known: texture_upload::Known = Default::default(); + let rt_known: texture_upload::Known = Default::default(); + for (r, at, k, target) in [(res, gpu, &known, false), (rt, gpu + PAGE, &rt_known, true)] { + texture_upload::all_sent(k, at, PAGE); + let e = Entry { device: 0, va: at, src: at, in_gpu_view: true, paged: true, tex: Arc::clone(&tex), states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, placed: false, unmapped: false, generation: 0, known: Arc::clone(k), target, committed_bytes: 0, gpu_writers: Vec::new(), cpu_backed: true }; + TEXTURES.lock().unwrap().insert(r, e); + TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); + } + let all: Vec = (gpu..gpu + PAGE).step_by(0x1000).collect(); + // what an upload compares (and remembers) + let look = |dirty: &[usize]| { + let m = page_map(gpu, PAGE, false).unwrap(); + texture_upload::changed(&[texture_upload::Written { src: gpu, size: PAGE, dirty, known: &known, pages: Some(&m) }], true).0.remove(0) + }; + let whole = Change::Parts(vec![(0, PAGE)]); + assert_eq!(look(&all), whole, "nothing known of it yet: all of it differs"); + REMAP_COMPARE.with(|c| c.set(Some(true))); + let remap = |ranges: &[[u32; 3]]| { + map_pages(gpu, ranges, home, 3); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&res), "due at the next upload"); + assert_eq!(texture_upload::take_again(&known, 0, 0), Again::Nothing, "nothing sent with no comparison"); + let pages = texture_upload::take_recheck(&known, gpu); + assert_eq!(pages, all, "its pages under the mapping, to compare"); + look(&pages) + }; + assert_eq!(remap(&[[0, 1, 1]]), Change::None, "a page with the same bytes: nothing goes up"); + assert_eq!(remap(&[[0, 2, 1]]), whole, "other bytes go up"); + assert_eq!(remap(&[[2, 0, 1]]), whole, "unmapped: zeros"); + // a render target goes up as it is + map_pages(gpu + PAGE, &[[0, 1, 1]], home, 3); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&rt)); + assert_eq!(texture_upload::take_again(&rt_known, 0, 0), Again::Now(whole.clone()), "a render target: with no comparison"); + assert!(texture_upload::take_recheck(&rt_known, gpu + PAGE).is_empty()); + // and so does everything with the comparison off + REMAP_COMPARE.with(|c| c.set(Some(false))); + map_pages(gpu, &[[0, 0, 1]], home, 3); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&res)); + assert_eq!(texture_upload::take_again(&known, 0, 0), Again::Now(whole), "off: with no comparison"); + assert!(texture_upload::take_recheck(&known, gpu).is_empty()); + REMAP_COMPARE.with(|c| c.set(None)); + forget(res); + forget(rt); + drop_paged_views(cpu, gpu, pages); + } + } + + /// The GPU wrote a texture after its last upload, and its bytes were copied back (it is no + /// longer `gpu_written`): what its pages held at that upload is not what the PC texture holds, + /// so a page mapped under it again with those bytes still goes up. + #[test] + fn a_remapped_page_of_a_texture_the_gpu_wrote_is_not_taken_for_what_it_held() { + use crate::hle::kernelx::mirrors::PAGE; + use texture_upload::Change; + let _guard = TEST_LOCK.lock().unwrap(); + // (no submit looks while a texture of no resource is in the table) + let _refresh = REFRESH.lock().unwrap(); + unsafe { + let Some(_) = crate::gpu::uma::get() else { return crate::gpu::recomp::runner::skip_test("no unified memory") }; + let (cpu, gpu, pages, home) = paged_views(187 * PAGE, 2); + // pool pages 0 and 1 hold the same bytes + std::ptr::write_bytes(home as *mut u8, 0x5E, 2 * PAGE); + map_pages(gpu, &[[0, 0, 1]], home, 2); + recheck_gpu_view_sources(); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 128, 128, 1, 1, 28, 0x105)).unwrap()); + assert_eq!(tex.size() as usize, PAGE); + // a key of no resource, never dereferenced + let res = 0x7E57_0000_D000usize; + let known: texture_upload::Known = Default::default(); + texture_upload::all_sent(&known, gpu, PAGE); + let e = Entry { device: 0, va: gpu, src: gpu, in_gpu_view: true, paged: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, written_call: 0, placed: false, unmapped: false, generation: 0, known: Arc::clone(&known), target: false, committed_bytes: 0, gpu_writers: Vec::new(), cpu_backed: true }; + TEXTURES.lock().unwrap().insert(res, e); + TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); + let all: Vec = (gpu..gpu + PAGE).step_by(0x1000).collect(); + let look = |dirty: &[usize]| { + let m = page_map(gpu, PAGE, false).unwrap(); + texture_upload::changed(&[texture_upload::Written { src: gpu, size: PAGE, dirty, known: &known, pages: Some(&m) }], true).0.remove(0) + }; + REMAP_COMPARE.with(|c| c.set(Some(true))); + assert_eq!(look(&all), Change::Parts(vec![(0, PAGE)]), "its first upload"); + // the GPU writes it, and its bytes are copied back (`publish_download`) + let queue = WriterQueueId { raw: 0x7E57_0000_E000, generation: 1 }; + publish_gpu_writes(queue, &[capture_gpu_write(res, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES).unwrap()]); + { + let mut t = TEXTURES.lock().unwrap(); + let e = t.by_res.get_mut(&res).unwrap(); + assert!(e.gpu_written); + e.gpu_writers.clear(); + e.gpu_written = false; + } + // a page with the bytes it held at that upload is mapped under it + map_pages(gpu, &[[0, 1, 1]], home, 2); + recheck_gpu_view_sources(); + assert!(AGAIN.lock().unwrap().remove(&res), "due at the next upload"); + let compared = texture_upload::take_recheck(&known, gpu); + assert_eq!(compared, all, "compared"); + assert_eq!(look(&compared), Change::All, "not what the PC texture holds: it goes up"); + REMAP_COMPARE.with(|c| c.set(None)); + forget(res); + drop_paged_views(cpu, gpu, pages); + } + } + /// A texture read through its pages finds its written pages through the GPU-view pages a /// write reaches: a write where a mapped page is kept, and one in the CPU view under a page /// the queue's page mappings never named; those that differ from what went up are sent. @@ -6774,6 +6938,7 @@ pub(super) mod tests { known: Default::default(), whole, again: texture_upload::Change::None, + recheck: Vec::new(), target: false, pages: None, generation, @@ -6887,6 +7052,7 @@ pub(super) mod tests { known: Default::default(), whole, again: texture_upload::Change::None, + recheck: Vec::new(), target: false, pages: None, generation, From efc10d4316ed25a92c755e2fa158e570cc467e20 Mon Sep 17 00:00:00 2001 From: Foniass <107039406+Foniass@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:29 +0100 Subject: [PATCH 3/3] D3D12.X: log what title texture uploads were for every 1024 submits A line every 1024 submits that upload says what went up and for what: whole textures, CPU-written pages, remapped pages, parts sent again behind another queue (count and MB each), and how many remapped textures were compared and left out. It gives the breakdown of the upload volume that could only be estimated before (in a retail title's open world, 7903 uploads of 2082 MB per 1024 submits on amd-dev), and shows what the comparison of remapped pages (XCL_TEXTURE_REMAP_COMPARE) saves. Split out of amd-dev's 02ceae64 ("compare the pages a mapping changed under a texture before upload"), which carried this line with the behaviour change. Port onto main: the line leaves out amd-dev's count of GPU writes kept by XCL_GPU_WRITE_STAYS (c06cf419), which main does not have. Whether a texture had a CPU-written page is worked out only for the textures that go up, after main's texture_needs_upload has picked them, so the selection itself does no more work. Logging only; no test. cargo +stable-x86_64-pc-windows-msvc test -p xcl --lib -- title_textures texture_upload: 77 passed, 0 failed, 1 ignored, no SKIPPED (Windows 11, Ryzen 7 7800X3D with Radeon iGPU, RTX 5070 Ti). The line was not seen in a title run. Co-Authored-By: Claude Opus 5.5 --- crates/xcl/src/hle/d3d12x/title_textures.rs | 63 +++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 73307774c3..cd3d58ada6 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -54,6 +54,8 @@ struct Due { again: texture_upload::Change, /// the pages a mapping changed under it, to be compared (`texture_upload::recheck`) recheck: Vec, + /// the CPU wrote one of its pages since its last upload + written: bool, /// (`Entry::target`) target: bool, /// where its pages are read (`Entry::paged`) @@ -2187,6 +2189,11 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut matches += 1; } let whole = e.pending; + // (for `UPLOADS_FOR`: only of what goes up) + let written = !e.gpu_written && { + let i = dirty.partition_point(|&p| p + page as usize <= e.src); + dirty.get(i).is_some_and(|&p| p < e.src + e.tex.size() as usize) + }; if e.pending { e.pending = false; PENDING.fetch_sub(1, Ordering::Relaxed); @@ -2205,6 +2212,7 @@ unsafe fn refresh_parts(queue: *mut c_void, look: bool, mut sample: Option<&mut whole, again, recheck, + written, target: e.target, pages, generation: e.generation, @@ -2330,6 +2338,42 @@ impl TextureSelectionBench { static UNCHANGED: AtomicU64 = AtomicU64::new(0); +/// What an upload is for (`UPLOADS_FOR`). +#[derive(Clone, Copy)] +enum Why { + /// all of it: a new texture, a source changed, one uncovered or tried again + Whole, + /// pages the CPU wrote that differ + Written, + /// pages a mapping changed under it that differ (`remap_compare`), or sent with no comparison + Remapped, + /// parts sent again behind another queue's upload (`texture_upload::sent`) + Again, +} + +/// [textures, bytes] that went up for each `Why` since the last `upload_line_now` +static UPLOADS_FOR: [[AtomicU64; 2]; 4] = [const { [AtomicU64::new(0), AtomicU64::new(0)] }; 4]; +/// textures whose remapped pages were compared, and those of them (with no CPU-written page) +/// found holding what they held +static REMAPS_COMPARED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; +/// `upload_all` calls with something to upload +static UPLOAD_CALLS: AtomicU64 = AtomicU64::new(0); + +/// Every 1024 submits that upload: what went up, and for what. +fn upload_line_now() { + if UPLOAD_CALLS.fetch_add(1, Ordering::Relaxed) % 1024 != 1023 { + return; + } + let take = |c: &AtomicU64| c.swap(0, Ordering::Relaxed); + let [whole, written, remapped, again] = UPLOADS_FOR.each_ref().map(|w| (take(&w[0]), take(&w[1]) as f64 / (1u64 << 20) as f64)); + let held = take(&REMAPS_COMPARED[1]); + let compared = take(&REMAPS_COMPARED[0]) + held; + crate::xlog_info!( + "title texture uploads in the last 1024 submits that uploaded: {} whole ({:.1} MB: new textures, sources changed, uncovered); {} for CPU-written pages ({:.1} MB); {} for pages a mapping changed under them ({:.1} MB); {} sent again behind another queue ({:.1} MB); textures remapped: {compared} compared, {held} of them held what they held (left out)", + whole.0, whole.1, written.0, written.1, remapped.0, remapped.1, again.0, again.1 + ); +} + /// `XCL_TEXTURE_PARTS=0`: a texture that changed goes up as a whole. fn upload_parts() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -2827,6 +2871,7 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option // The written pages that hold what they held at their texture's last upload are nothing to do: // the write watch is per page and a title writes next to its textures (and rewrites what it // wrote). + let any = !todo.is_empty(); let t = std::time::Instant::now(); let mut changes: std::collections::VecDeque = { let pages: Vec> = todo @@ -2867,6 +2912,17 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option }; let mut todo = todo.into_iter().filter_map(|d| { let change = if d.whole { texture_upload::Change::All } else { changes.pop_front()? }; + let found = change != texture_upload::Change::None; + let why = match () { + _ if d.whole => Why::Whole, + _ if d.written && found => Why::Written, + _ if !d.recheck.is_empty() && found => Why::Remapped, + _ => Why::Again, + }; + if !d.whole && !d.recheck.is_empty() { + // (the pages of one with no CPU-written ones held what they held: none of them goes up) + REMAPS_COMPARED[usize::from(!d.written && !found)].fetch_add(1, Ordering::Relaxed); + } let changed = match texture_upload::join(change, d.again.clone()) { texture_upload::Change::None => return None, texture_upload::Change::All => None, @@ -2879,6 +2935,8 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option let volume = d.tex.texels().is_some_and(|s| s.depth > 0); let parts = changed.as_ref().filter(|_| !volume); let bytes = parts.map_or(size, |p| p.iter().map(|r| (r.1.div_ceil(BLOCK) - r.0 / BLOCK) * BLOCK).sum::().min(size)); + UPLOADS_FOR[why as usize][0].fetch_add(1, Ordering::Relaxed); + UPLOADS_FOR[why as usize][1].fetch_add(bytes as u64, Ordering::Relaxed); Some((d, changed, bytes)) }).peekable(); while todo.peek().is_some() { @@ -2963,6 +3021,9 @@ unsafe fn upload_all(todo: Vec, dirty: &[usize], page: usize, title: Option } } } + if any { + upload_line_now(); + } } /// textures of batches that could not be uploaded, with their registration generation, and when @@ -6939,6 +7000,7 @@ pub(super) mod tests { whole, again: texture_upload::Change::None, recheck: Vec::new(), + written: false, target: false, pages: None, generation, @@ -7053,6 +7115,7 @@ pub(super) mod tests { whole, again: texture_upload::Change::None, recheck: Vec::new(), + written: false, target: false, pages: None, generation,