diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index d809b1c2a2..b2b7a54293 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -2302,6 +2302,55 @@ fn unchanged_skip() -> bool { const STREAM_RECHECK_MILESTONES: [u64; 5] = [4, 12, 40, 120, 400]; /// Per-slice sample size (start, mid, end -> at most 48 KiB hashed per due texture). const STREAM_SAMPLE_SLICE: usize = 16 * 1024; +/// A small render target / UAV texture (`Entry::target`, e.g. a glyph cache the CPU fills as it +/// needs letters) can be written at any time, not only while it streams in: after its first +/// milestone it is checked again every `STREAM_RECHECK_STEADY` frames for as long as it lives, +/// instead of retiring after the last milestone. +const STREAM_RECHECK_STEADY: u64 = 16; +/// up to this size a steady target is kept on the steady schedule ... +const STREAM_STEADY_MAX: usize = 4 << 20; +/// ... and up to this size its whole contents are hashed, not three slices (a new glyph can land +/// anywhere in the atlas) +const STREAM_STEADY_WHOLE_MAX: usize = 512 << 10; + +/// Whether an unwatched texture of `size` bytes stays on the steady schedule (`STREAM_RECHECK_STEADY`). +fn stream_recheck_steady(target: bool, size: usize) -> bool { + target && size <= STREAM_STEADY_MAX +} + +/// Bytes the steady re-checks of one frame read at most (the check that falls over it waits for the +/// next frame; the first one of a frame is always made). +const STREAM_STEADY_BUDGET: usize = 4 << 20; + +/// Frames (0..`STREAM_RECHECK_STEADY`) by which a texture's first steady check is moved, from its +/// address, so those seeded on the same frame spread over the interval. +fn steady_offset(res: usize) -> u64 { + ((res as u64 >> 4).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 60) % STREAM_RECHECK_STEADY +} + +/// Of the due steady checks `(res, due frame, bytes)` keeps the oldest-due ones that fit +/// `STREAM_STEADY_BUDGET` (at least one) in `due`, and returns the `res` of the others. +fn steady_checks_over_budget(due: &mut Vec<(usize, u64, usize)>) -> Vec { + due.sort_by_key(|&(res, due_at, _)| (due_at, res)); + let mut used = 0usize; + let mut keep = 0usize; + for &(_, _, cost) in due.iter() { + if keep > 0 && used.saturating_add(cost) > STREAM_STEADY_BUDGET { + break; + } + used = used.saturating_add(cost); + keep += 1; + } + due.split_off(keep).into_iter().map(|d| d.0).collect() +} + +/// The fingerprint the recheck compares: all of a small steady target, else `sample_fingerprint`. +unsafe fn stream_fingerprint(src: usize, size: usize, target: bool) -> u64 { + if stream_recheck_steady(target, size) && size <= STREAM_STEADY_WHOLE_MAX { + return texture_upload::content_hash(&read_committed(src, size)); + } + sample_fingerprint(src, size) +} #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct StreamRecheck { @@ -2396,7 +2445,7 @@ unsafe fn seed_stream_recheck(todo: &[Due], watched: &[(usize, usize)], frame: u unsent.push(d.res.as_raw() as usize); continue; } - let fp = sample_fingerprint(d.src, size); + let fp = stream_fingerprint(d.src, size, d.target); seeded.push((d.res.as_raw() as usize, StreamRecheck { base_frame: frame, stage: 0, last_fp: Some(fp) })); } if !seeded.is_empty() || !unsent.is_empty() { @@ -2424,15 +2473,18 @@ unsafe fn recheck_streamed_unwatched(watched: &[(usize, usize)], frame: u64) { /// Re-fingerprint due unwatched textures at `frame`, re-queuing changed entries and resetting /// their milestone schedule so subsequent higher-resolution mip streams are also caught. unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) { - let due: Vec<(usize, Option)> = { + // (res, baseline, frame it fell due, on the steady schedule) + let due: Vec<(usize, Option, u64, bool)> = { let g = STREAM_RECHECK.lock().unwrap(); if g.is_empty() { return; } g.iter() .filter_map(|(&res, st)| { - let target = *STREAM_RECHECK_MILESTONES.get(st.stage as usize)?; - (frame.saturating_sub(st.base_frame) >= target).then_some((res, st.last_fp)) + // (only a steady target is still here past the last milestone) + let steady = st.stage as usize >= STREAM_RECHECK_MILESTONES.len(); + let target = STREAM_RECHECK_MILESTONES.get(st.stage as usize).copied().unwrap_or(STREAM_RECHECK_STEADY); + (frame.saturating_sub(st.base_frame) >= target).then_some((res, st.last_fp, st.base_frame.saturating_add(target), steady)) }) .collect() }; @@ -2441,10 +2493,12 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) } let mut check = Vec::with_capacity(due.len()); + // steady checks, `(res, due frame, bytes read)`, kept to `STREAM_STEADY_BUDGET` bytes a frame + let mut steady_due: Vec<(usize, u64, usize)> = Vec::new(); let mut prune = Vec::new(); { let t = TEXTURES.lock().unwrap(); - for (res, prev_fp) in due { + for (res, prev_fp, due_at, steady_stage) in due { match t.by_res.get(&res) { Some(e) if e.gpu_written => prune.push(res), Some(e) if e.pending => {} @@ -2453,7 +2507,11 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) if e.paged || range_is_fully_watched(e.src, size, watched) { prune.push(res); } else { - check.push((res, e.src, size, prev_fp)); + if steady_stage { + let cost = if size <= STREAM_STEADY_WHOLE_MAX { size } else { 3 * STREAM_SAMPLE_SLICE }; + steady_due.push((res, due_at, cost)); + } + check.push((res, e.src, size, e.target, prev_fp)); } } None => { @@ -2470,19 +2528,26 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) g.remove(&res); } } + // steady checks over the budget wait for the next frame (they stay due, and go first then) + if !steady_due.is_empty() { + let skipped = steady_checks_over_budget(&mut steady_due); + if !skipped.is_empty() { + check.retain(|c| !skipped.contains(&c.0)); + } + } if check.is_empty() { return; } - let results: Vec<(usize, Option, u64)> = check + let results: Vec<(usize, Option, u64, bool)> = check .into_iter() - .map(|(res, src, size, prev_fp)| (res, prev_fp, sample_fingerprint(src, size))) + .map(|(res, src, size, target, prev_fp)| (res, prev_fp, stream_fingerprint(src, size, target), stream_recheck_steady(target, size))) .collect(); let mut changed = Vec::new(); { let mut g = STREAM_RECHECK.lock().unwrap(); - for (res, prev_fp, cur_fp) in results { + for (res, prev_fp, cur_fp, steady) in results { let Some(st) = g.get_mut(&res) else { continue; }; @@ -2490,6 +2555,16 @@ unsafe fn recheck_streamed_unwatched_at(watched: &[(usize, usize)], frame: u64) if prev_fp != Some(cur_fp) { *st = StreamRecheck { base_frame: frame, stage: 0, last_fp: Some(cur_fp) }; changed.push(res); + } else if steady { + // never retired: the next check is `STREAM_RECHECK_STEADY` frames from now; the + // first one is moved by `steady_offset`, so textures seeded on one frame do not + // stay due on the same frame + st.base_frame = if (st.stage as usize) < STREAM_RECHECK_MILESTONES.len() { + frame.saturating_add(steady_offset(res)) + } else { + frame + }; + st.stage = STREAM_RECHECK_MILESTONES.len() as u8; } else { st.stage = st.stage.saturating_add(1); if st.stage as usize >= STREAM_RECHECK_MILESTONES.len() { @@ -6617,6 +6692,123 @@ pub(super) mod tests { forget(gpu_res_id); } + /// A small CPU-filled target in unwatched memory (a glyph cache) is never retired from the + /// recheck, and a glyph written anywhere in it is seen, not only in the three sampled slices. + #[test] + fn stream_recheck_keeps_checking_small_targets_and_hashes_all_of_them() { + let _guard = TEST_LOCK.lock().unwrap(); + let desc = console_desc(3, 256, 256, 1, 1, 28, 0x109); // 256 KiB RGBA8 + let tex = Arc::new(xg::Texture::new(&desc).expect("layout")); + let size = tex.size() as usize; + assert!(size > 3 * STREAM_SAMPLE_SLICE && size <= STREAM_STEADY_WHOLE_MAX); + let mut backing = vec![0u8; size]; + let va = backing.as_ptr() as usize; + let res_id = 0x7410_0011usize; + let e = Entry { + device: 0, + committed_bytes: 0, + va, + src: va, + in_gpu_view: false, + paged: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: false, + written_call: 0, + gpu_writers: Vec::new(), + cpu_backed: true, + placed: false, + unmapped: false, + generation: 0, + known: Default::default(), + target: true, + }; + { + let mut t = TEXTURES.lock().unwrap(); + let (d, _) = t.insert(res_id, e); + adjust_pending(d); + } + let fp0 = unsafe { stream_fingerprint(va, size, true) }; + STREAM_RECHECK.lock().unwrap().insert(res_id, StreamRecheck { base_frame: 100, stage: 0, last_fp: Some(fp0) }); + + // Unchanged for well past the last milestone (+400): it stays scheduled and is not queued. + let mut f = 104; + while f <= 1000 { + unsafe { recheck_streamed_unwatched_at(&[], f) }; + assert!(!TEXTURES.lock().unwrap().by_res.get(&res_id).unwrap().pending, "unchanged target must not re-queue at frame {f}"); + f += 4; + } + assert!(STREAM_RECHECK.lock().unwrap().contains_key(&res_id), "a small target must not retire from the recheck"); + + // A glyph lands outside the start / middle / end slices, long after the last milestone. + let off = STREAM_SAMPLE_SLICE + 0x100; + assert!(off + 16 < (size - STREAM_SAMPLE_SLICE) / 2); + backing[off] = 0xEE; + unsafe { recheck_streamed_unwatched_at(&[], f + STREAM_RECHECK_STEADY) }; + { + let mut t = TEXTURES.lock().unwrap(); + let e = t.by_res.get_mut(&res_id).unwrap(); + assert!(e.pending, "a late write outside the sampled slices must queue the target"); + e.pending = false; + PENDING.fetch_sub(1, Ordering::Relaxed); + } + + forget(res_id); + } + + #[test] + fn steady_recheck_is_only_for_small_targets() { + assert!(stream_recheck_steady(true, 256 << 10)); + assert!(!stream_recheck_steady(false, 256 << 10), "streamed textures keep their milestones"); + assert!(!stream_recheck_steady(true, STREAM_STEADY_MAX + 1)); + } + + /// 300 steady targets of 256 KiB seeded on one frame: no frame reads more than the budget, and + /// each is checked again within a bounded number of frames (oldest due first). + #[test] + fn steady_rechecks_are_staggered_and_kept_to_a_byte_budget() { + assert_eq!(STREAM_RECHECK_STEADY, 16); + const SIZE: usize = 256 << 10; + let texs: Vec = (0..300).map(|i| 0x1_0000_0000usize + i * 0x1_0000).collect(); + let offs: std::collections::BTreeSet = texs.iter().map(|&r| steady_offset(r)).collect(); + assert!(offs.iter().all(|&o| o < STREAM_RECHECK_STEADY)); + assert!(offs.len() >= 12, "the offsets must spread over the interval, got {}", offs.len()); + + // every texture was seeded at frame 0 and passed its first milestone at frame 4 + let mut base: Vec = texs.iter().map(|&r| 4 + steady_offset(r)).collect(); + let mut last_check = vec![4u64; texs.len()]; + let mut max_gap = 0u64; + let mut max_bytes = 0usize; + let mut checks = 0usize; + for frame in 5..400u64 { + let mut due: Vec<(usize, u64, usize)> = (0..texs.len()) + .filter(|&i| frame >= base[i] + STREAM_RECHECK_STEADY) + .map(|i| (i, base[i] + STREAM_RECHECK_STEADY, SIZE)) + .collect(); + let skipped = steady_checks_over_budget(&mut due); + let bytes: usize = due.iter().map(|d| d.2).sum(); + max_bytes = max_bytes.max(bytes); + assert!(bytes <= STREAM_STEADY_BUDGET, "frame {frame} reads {bytes} bytes"); + let _ = skipped; + for &(i, _, _) in &due { + max_gap = max_gap.max(frame - last_check[i]); + last_check[i] = frame; + base[i] = frame; + checks += 1; + } + } + assert!(max_bytes > 0 && checks > 300); + // 75 MiB a cycle at 4 MiB a frame: about 19 frames, never starved + assert!(max_gap <= 40, "a texture waited {max_gap} frames"); + assert!(last_check.iter().all(|&f| f >= 400 - 40)); + + // a check larger than the budget is still made, alone + let mut one = vec![(1usize, 5u64, STREAM_STEADY_BUDGET + 1), (2, 6, 1)]; + assert_eq!(steady_checks_over_budget(&mut one), vec![2]); + assert_eq!(one.len(), 1); + } + /// A partial upload does not replace the baseline of the last whole upload: an unwatched write /// it did not send is still caught at the milestone. #[test]