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 d809b1c2a2..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; @@ -1502,10 +1531,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 +1577,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); @@ -2114,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) { @@ -2121,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; @@ -2128,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); @@ -2159,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, @@ -2794,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() @@ -4858,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 @@ -5000,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. @@ -5636,6 +5814,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; @@ -6696,6 +6938,7 @@ pub(super) mod tests { known: Default::default(), whole, again: texture_upload::Change::None, + recheck: Vec::new(), target: false, pages: None, generation, @@ -6809,6 +7052,7 @@ pub(super) mod tests { known: Default::default(), whole, again: texture_upload::Change::None, + recheck: Vec::new(), target: false, pages: None, generation,