diff --git a/d3d12/crates/leonida-gpu/src/lib.rs b/d3d12/crates/leonida-gpu/src/lib.rs index f800cb40f6..cbc06fcdfe 100644 --- a/d3d12/crates/leonida-gpu/src/lib.rs +++ b/d3d12/crates/leonida-gpu/src/lib.rs @@ -154,7 +154,10 @@ pub fn frame_phase() -> u32 { #[cfg(windows)] pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] -pub use shadow::{title_memory_gpu_read_only, title_memory_write_combined}; +pub use shadow::{ + title_memory_gpu_read_only, title_memory_is_gpu_read_only, title_memory_is_write_combined, + title_memory_write_combined, +}; #[cfg(windows)] pub use watch::{ kernel_writing, remap_boost, title_memory_allocated, title_memory_freed, title_memory_reading, title_memory_remapped, diff --git a/d3d12/crates/leonida-gpu/src/shadow.rs b/d3d12/crates/leonida-gpu/src/shadow.rs index 75791e2190..32f1442995 100644 --- a/d3d12/crates/leonida-gpu/src/shadow.rs +++ b/d3d12/crates/leonida-gpu/src/shadow.rs @@ -390,8 +390,9 @@ pub(crate) struct Shadow { elide: AtomicU8, /// What the watching has seen of uploads and fetches. elide_track: Mutex, - /// Whether its title memory is write-combined ([`Shadow::write_combined`], - /// `LEONIDA_WC_NO_BACK`): 0 not known yet, 1 no, 2 yes. + /// Whether its title memory is write-combined ([`Shadow::wc_kind`], + /// `LEONIDA_WC_NO_BACK` / `LEONIDA_WC_SUBRANGE_NO_BACK`): + /// 0 not known yet, 1 none, 2 whole copy, 3 partial (mixed copy with qualifying sub-ranges). wc: AtomicU8, /// A window in card memory the CPU maps ([`window_mapped_for`]). mapped: bool, @@ -2794,6 +2795,8 @@ pub(crate) static ECHO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; /// Title memory the title asked for write-combined (the console's 0x400 /// protection bit), as `[start, end)` ([`title_memory_write_combined`]). static WRITE_COMBINED: RwLock> = RwLock::new(Vec::new()); +/// Whether [`WRITE_COMBINED`] holds anything (looked at before its lock). +static ANY_WRITE_COMBINED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// The title asked for `[at, at + len)` write-combined: its CPU writes the /// memory and does not read it (reads of such memory are uncached on the @@ -2803,21 +2806,30 @@ pub fn title_memory_write_combined(at: usize, len: usize) { return; } let mut all = WRITE_COMBINED.write().unwrap_or_else(|e| e.into_inner()); - all.push((at as u64, (at + len) as u64)); + all.push((at as u64, (at as u64).saturating_add(len as u64))); + all.sort_unstable(); + all.dedup(); + ANY_WRITE_COMBINED.store(true, Ordering::Relaxed); } /// The title let go of `[at, at + len)` (`len` 0: of the allocation at `at`): /// write-combined and GPU read-only regions in it are forgotten. pub(crate) fn write_combined_freed(at: usize, len: usize) { - let (at, end) = (at as u64, at.saturating_add(len) as u64); - for list in [&WRITE_COMBINED, &GPU_READ_ONLY] { + let (at, end) = (at as u64, (at as u64).saturating_add(len as u64)); + for (list, any) in [(&WRITE_COMBINED, &ANY_WRITE_COMBINED), (&GPU_READ_ONLY, &ANY_GPU_READ_ONLY)] { let mut all = list.write().unwrap_or_else(|e| e.into_inner()); if all.is_empty() { + any.store(false, Ordering::Relaxed); continue; } all.retain(|&(from, to)| if len == 0 { from != at } else { to <= at || from >= end }); + any.store(!all.is_empty(), Ordering::Relaxed); } - ANY_GPU_READ_ONLY.store(!GPU_READ_ONLY.read().unwrap_or_else(|e| e.into_inner()).is_empty(), Ordering::Relaxed); +} + +/// Whether any write-combined or GPU read-only regions are currently registered. +pub(crate) fn has_memory_classes() -> bool { + ANY_WRITE_COMBINED.load(Ordering::Relaxed) || ANY_GPU_READ_ONLY.load(Ordering::Relaxed) } // Leonida: title memory the console has the GPU read only. @@ -2837,18 +2849,109 @@ pub fn title_memory_gpu_read_only(at: usize, len: usize) { return; } let mut all = GPU_READ_ONLY.write().unwrap_or_else(|e| e.into_inner()); - all.push((at as u64, (at + len) as u64)); + all.push((at as u64, (at as u64).saturating_add(len as u64))); all.sort_unstable(); + all.dedup(); ANY_GPU_READ_ONLY.store(true, Ordering::Relaxed); } +/// Small inline interval list to avoid heap allocations on common `gpu_writes` splits (up to 4 intervals). +enum SmallRanges { + Inline([(u64, u64); 4], usize), + Heap(Vec<(u64, u64)>), +} + +impl SmallRanges { + fn new() -> Self { + Self::Inline([(0, 0); 4], 0) + } + + fn as_slice(&self) -> &[(u64, u64)] { + match self { + Self::Inline(buf, len) => &buf[..*len], + Self::Heap(vec) => vec.as_slice(), + } + } + + fn is_empty(&self) -> bool { + self.as_slice().is_empty() + } + + fn last_mut(&mut self) -> Option<&mut (u64, u64)> { + match self { + Self::Inline(buf, len) => buf[..*len].last_mut(), + Self::Heap(vec) => vec.last_mut(), + } + } + + fn push(&mut self, range: (u64, u64)) { + match self { + Self::Inline(buf, len) if *len < buf.len() => { + buf[*len] = range; + *len += 1; + } + Self::Inline(buf, len) => { + let mut vec = Vec::with_capacity(8); + vec.extend_from_slice(&buf[..*len]); + vec.push(range); + *self = Self::Heap(vec); + } + Self::Heap(vec) => vec.push(range), + } + } +} + +/// Clips regions in `all` (of at least `min_region_bytes`) to `[start, end)` and merges any +/// overlapping or adjacent intervals so the result is sorted and disjoint. +fn merge_clipped_parts(all: &[(u64, u64)], start: u64, end: u64, min_region_bytes: u64) -> SmallRanges { + let mut parts = SmallRanges::new(); + if start >= end { + return parts; + } + for &(from, to) in all { + if from >= end { + break; + } + if to <= start || to.saturating_sub(from) < min_region_bytes { + continue; + } + let clipped = (from.max(start), to.min(end)); + match parts.last_mut() { + Some(prev) if clipped.0 <= prev.1 => prev.1 = prev.1.max(clipped.1), + _ => parts.push(clipped), + } + } + parts +} + /// The parts of `[start, end)` that lie in GPU read-only title memory, in order and cut to it. -fn gpu_read_only_parts(start: u64, end: u64) -> Vec<(u64, u64)> { +fn gpu_read_only_parts(start: u64, end: u64) -> SmallRanges { if !ANY_GPU_READ_ONLY.load(Ordering::Relaxed) || start >= end { - return Vec::new(); + return SmallRanges::new(); } let all = GPU_READ_ONLY.read().unwrap_or_else(|e| e.into_inner()); - all.iter().filter(|&&(from, to)| from < end && to > start).map(|&(from, to)| (from.max(start), to.min(end))).collect() + merge_clipped_parts(&all, start, end, 0) +} + +/// The parts of `[start, end)` that lie in write-combined regions of at least `min_region_bytes`, +/// in order and cut to it. +#[cfg(test)] +fn write_combined_parts(start: u64, end: u64, min_region_bytes: u64) -> SmallRanges { + if !ANY_WRITE_COMBINED.load(Ordering::Relaxed) || start >= end { + return SmallRanges::new(); + } + let all = WRITE_COMBINED.read().unwrap_or_else(|e| e.into_inner()); + merge_clipped_parts(&all, start, end, min_region_bytes) +} + +/// Whether `[at, at + len)` is non-empty and covered by GPU read-only title memory. +pub fn title_memory_is_gpu_read_only(at: usize, len: usize) -> bool { + if len == 0 || !ANY_GPU_READ_ONLY.load(Ordering::Relaxed) { + return false; + } + let start = at as u64; + let end = start.saturating_add(len as u64); + start < end && gpu_read_only_parts(start, end).as_slice() == [(start, end)] } /// Whether shader writes declared over GPU read-only title memory are left out of the copy-back @@ -2876,8 +2979,202 @@ pub(crate) static GPU_RO_DECLARED: [AtomicU64; 2] = [const { AtomicU64::new(0) } /// Whether all of `[start, start + len)` lies in write-combined title memory /// (in one region the title asked for so: regions are hundreds of MB to GB). fn is_write_combined(start: u64, len: u64) -> bool { + if !ANY_WRITE_COMBINED.load(Ordering::Relaxed) || len == 0 { + return false; + } + let end = start.saturating_add(len); + let all = WRITE_COMBINED.read().unwrap_or_else(|e| e.into_inner()); + for &(from, to) in &*all { + if from > start { + break; + } + if end <= to { + return true; + } + } + false +} + +/// Write-combined classification of a copy's span (`[start, start + len)`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum WcKind { + None, + Whole, + Partial, +} + +/// Classifies `[start, start + len)` against [`WRITE_COMBINED`] in one sorted pass: +/// `Whole` if one registered WC region covers the whole span, `Partial` if at least one +/// qualifying WC region (`>= min_region_bytes`) overlaps part of it, otherwise `None`. +fn classify_write_combined(start: u64, len: u64, min_region_bytes: u64) -> WcKind { + if !ANY_WRITE_COMBINED.load(Ordering::Relaxed) || len == 0 { + return WcKind::None; + } + let end = start.saturating_add(len); + if start >= end { + return WcKind::None; + } let all = WRITE_COMBINED.read().unwrap_or_else(|e| e.into_inner()); - all.iter().any(|&(from, to)| from <= start && start + len <= to) + let mut partial = false; + for &(from, to) in &*all { + if from >= end { + break; + } + if from <= start && end <= to { + return WcKind::Whole; + } + if to > start && to.saturating_sub(from) >= min_region_bytes { + partial = true; + } + } + if partial { WcKind::Partial } else { WcKind::None } +} + +/// Whether `[at, at + len)` is non-empty and lies inside a write-combined region. +pub fn title_memory_is_write_combined(at: usize, len: usize) -> bool { + is_write_combined(at as u64, len as u64) +} + +/// Pure policy for [`wc_subrange_no_back`]: `LEONIDA_AB` on `LEONIDA_WC_NO_BACK` overrides +/// `LEONIDA_WC_NO_BACK=0`, and an explicit `LEONIDA_WC_NO_BACK=0` disables sub-range exclusion too. +fn wc_subrange_enabled(wc_explicit_off: bool, wc_ab: Option, subrange_on: bool) -> bool { + if let Some(ab_on) = wc_ab { + return ab_on && subrange_on; + } + if wc_explicit_off { + return false; + } + subrange_on +} + +/// Whether write-combined sub-ranges inside mixed card copies (such as the 47 MiB `0x2404` part of +/// the 32-bit graphics heap) are subtracted from shader write-back (`LEONIDA_WC_SUBRANGE_NO_BACK`, off +/// by default; `LEONIDA_AB`-switchable). +fn wc_subrange_no_back() -> bool { + let subrange_on = crate::asked!("LEONIDA_WC_SUBRANGE_NO_BACK"); + if !subrange_on { + return false; + } + static WC_EXPLICIT_OFF: std::sync::OnceLock = std::sync::OnceLock::new(); + let wc_explicit_off = + *WC_EXPLICIT_OFF.get_or_init(|| std::env::var_os("LEONIDA_WC_NO_BACK").is_some_and(|v| v == "0")); + #[cfg(feature = "diagnostics")] + let wc_ab = { + static BIT: std::sync::OnceLock> = std::sync::OnceLock::new(); + (*BIT.get_or_init(|| crate::ab::bit("LEONIDA_WC_NO_BACK"))).map(crate::ab::on) + }; + #[cfg(not(feature = "diagnostics"))] + let wc_ab = None; + wc_subrange_enabled(wc_explicit_off, wc_ab, subrange_on) +} + +#[derive(Clone, Copy)] +struct GpuWritePolicy { + copy_len: u64, + has_card: bool, + ro_on: bool, + wc_subrange_on: bool, + wc_min: u64, +} + +#[derive(Debug, Default, PartialEq, Eq)] +struct GpuWriteStats { + ro_declared: u64, + ro_left: u64, + wc_left: u64, +} + +fn subtract_sorted_parts_into(start: u64, end: u64, excluded: &[(u64, u64)], out: &mut SmallRanges) { + if start >= end { + return; + } + let mut at = start; + for &(from, to) in excluded { + if from > at { + out.push((at, from.min(end))); + } + at = at.max(to); + if at >= end { + break; + } + } + if at < end { + out.push((at, end)); + } +} + +/// Emits the kept sub-ranges and returns telemetry counts for a shader write declaration inside a copy. +/// `GPU_READ_ONLY` runs first so read-only WC parts (`0x1404`/`0x8404`) stay accounted in +/// `ro_declared`/`ro_left` without double-counting into `wc_left`. +fn for_each_gpu_write_range( + address: u64, + len: u64, + policy: GpuWritePolicy, + mut emit: impl FnMut(u64, u64), +) -> GpuWriteStats { + let mut stats = GpuWriteStats::default(); + let end = address.saturating_add(len); + if address >= end { + return stats; + } + let read_only = gpu_read_only_parts(address, end); + let mut segments = SmallRanges::new(); + if read_only.is_empty() { + segments.push((address, end)); + } else { + stats.ro_declared = read_only.as_slice().iter().map(|&(from, to)| to - from).sum(); + if policy.ro_on { + stats.ro_left = stats.ro_declared; + subtract_sorted_parts_into(address, end, read_only.as_slice(), &mut segments); + } else { + segments.push((address, end)); + } + } + if policy.has_card + && policy.copy_len >= policy.wc_min + && policy.wc_subrange_on + && !segments.is_empty() + && ANY_WRITE_COMBINED.load(Ordering::Relaxed) + { + let mut after_wc = SmallRanges::new(); + let all = WRITE_COMBINED.read().unwrap_or_else(|e| e.into_inner()); + for &(seg_start, seg_end) in segments.as_slice() { + let wc = merge_clipped_parts(&all, seg_start, seg_end, policy.wc_min); + if wc.is_empty() { + after_wc.push((seg_start, seg_end)); + } else { + stats.wc_left += wc.as_slice().iter().map(|&(from, to)| to - from).sum::(); + subtract_sorted_parts_into(seg_start, seg_end, wc.as_slice(), &mut after_wc); + } + } + drop(all); + segments = after_wc; + } + for &(from, to) in segments.as_slice() { + emit(from, to); + } + stats +} + +#[cfg(test)] +#[derive(Debug, Default, PartialEq, Eq)] +struct GpuWritePlan { + keep: Vec<(u64, u64)>, + ro_declared: u64, + ro_left: u64, + wc_left: u64, +} + +#[cfg(test)] +fn plan_gpu_write_ranges(address: u64, len: u64, policy: GpuWritePolicy) -> GpuWritePlan { + let mut keep = Vec::new(); + let stats = for_each_gpu_write_range(address, len, policy, |from, to| keep.push((from, to))); + GpuWritePlan { + keep, + ro_declared: stats.ro_declared, + ro_left: stats.ro_left, + wc_left: stats.wc_left, + } } /// Whether what shaders write into copies in the card's memory of @@ -3690,7 +3987,19 @@ mod landing_tests { #[cfg(test)] mod write_combined_tests { - use super::{is_write_combined, title_memory_write_combined, write_combined_freed}; + use super::{ + GpuWritePlan, GpuWritePolicy, WcKind, classify_write_combined, gpu_read_only_parts, is_write_combined, + plan_gpu_write_ranges, title_memory_gpu_read_only, title_memory_is_gpu_read_only, + title_memory_is_write_combined, title_memory_write_combined, wc_subrange_enabled, write_combined_freed, + write_combined_parts, + }; + + struct Cleanup(u64, u64); + impl Drop for Cleanup { + fn drop(&mut self) { + write_combined_freed(self.0 as usize, self.1 as usize); + } + } /// A copy counts as write-combined only inside one such region, and not /// after the region is let go (part of it or the whole allocation). @@ -3698,11 +4007,13 @@ mod write_combined_tests { fn write_combined_regions() { // Addresses of their own: other tests share the registry. let base = 0x7f00_0000_0000usize; + let _guard = Cleanup(base as u64, 0x2000_0000); title_memory_write_combined(base, 0x100_0000); assert!(is_write_combined(base as u64, 0x1000)); assert!(is_write_combined(base as u64 + 0xff_f000, 0x1000)); assert!(!is_write_combined(base as u64 + 0xff_f000, 0x2000), "past its end"); assert!(!is_write_combined(base as u64 - 0x1000, 0x2000), "before its start"); + assert!(title_memory_is_write_combined(base, 0x1000)); write_combined_freed(base + 0x10_0000, 0x1000); assert!(!is_write_combined(base as u64, 0x1000), "part of it decommitted"); let other = base + 0x1000_0000; @@ -3715,17 +4026,203 @@ mod write_combined_tests { /// clipped to the range; none outside them, none once let go. #[test] fn gpu_read_only_parts_of_a_range() { - use super::{gpu_read_only_parts, title_memory_gpu_read_only}; let base = 0x7e00_0000_0000u64; + let _guard = Cleanup(base, 0x1_0000); title_memory_gpu_read_only(base as usize + 0x3000, 0x2000); title_memory_gpu_read_only(base as usize, 0x1000); - assert_eq!(gpu_read_only_parts(base + 0x800, base + 0x4000), [(base + 0x800, base + 0x1000), (base + 0x3000, base + 0x4000)]); - assert_eq!(gpu_read_only_parts(base + 0x1000, base + 0x3000), [], "between them"); - assert_eq!(gpu_read_only_parts(base + 0x4000, base + 0x4000), [], "an empty range"); + assert!(title_memory_is_gpu_read_only(base as usize, 0x1000)); + assert!(!title_memory_is_gpu_read_only(base as usize, 0x2000)); + assert_eq!( + gpu_read_only_parts(base + 0x800, base + 0x4000).as_slice(), + [(base + 0x800, base + 0x1000), (base + 0x3000, base + 0x4000)] + ); + assert_eq!(gpu_read_only_parts(base + 0x1000, base + 0x3000).as_slice(), [], "between them"); + assert_eq!(gpu_read_only_parts(base + 0x4000, base + 0x4000).as_slice(), [], "an empty range"); write_combined_freed(base as usize + 0x3000, 0); - assert_eq!(gpu_read_only_parts(base, base + 0x8000), [(base, base + 0x1000)], "the second let go"); + assert_eq!(gpu_read_only_parts(base, base + 0x8000).as_slice(), [(base, base + 0x1000)], "the second let go"); write_combined_freed(base as usize, 0); } + + /// Write-combined sub-range lookup enforces the per-region minimum size and merges adjacent or + /// overlapping qualifying regions when clipped to a range. + #[test] + fn write_combined_parts_clips_merges_and_enforces_min_region() { + let base = 0x7d00_0000_0000u64; + let _guard = Cleanup(base, 0x100_0000); + let mib = 1024 * 1024; + let kib512 = 512 * 1024; + // Two adjacent 512 KiB regions must NOT satisfy a 1 MiB minimum-region floor. + title_memory_write_combined(base as usize, kib512 as usize); + title_memory_write_combined((base + kib512) as usize, kib512 as usize); + // Overlapping qualifying regions (>= 1 MiB each) merge cleanly when clipped. + title_memory_write_combined((base + 2 * mib) as usize, (2 * mib) as usize); + title_memory_write_combined((base + 3 * mib) as usize, (2 * mib) as usize); + + assert_eq!(write_combined_parts(base, base + 6 * mib, mib).as_slice(), [(base + 2 * mib, base + 5 * mib)]); + assert_eq!( + write_combined_parts(base + mib / 2, base + 4 * mib + mib / 2, 0).as_slice(), + [(base + mib / 2, base + mib), (base + 2 * mib, base + 4 * mib + mib / 2)] + ); + } + + /// Mixed copies (such as the title's 5-part 185 MiB 32-bit graphics heap) subtract GPU read-only + /// parts first and then qualifying write-combined sub-ranges, without double-counting overlap or + /// skipping small copies / small WC regions. + #[test] + fn mixed_copy_subtracts_gpu_ro_then_wc_subranges() { + let base = 0x7c00_0000_0000u64; + let mib = 1024 * 1024; + let min_1mib = mib; + let _guard = Cleanup(base, 200 * mib); + + // Model the 5-part 185 MiB heap: + // [0..10M) 0x1004 CPU cached, GPU RO + // [10..11M) 0x1404 WC, GPU RO + // [11..38M) 0x8404 WC, GPU execute-read (RO) + // [38..85M) 0x2404 WC, GPU RW + // [85..185M) 0x2004 CPU cached, GPU RW + title_memory_gpu_read_only(base as usize, (10 * mib) as usize); + title_memory_write_combined((base + 10 * mib) as usize, mib as usize); + title_memory_gpu_read_only((base + 10 * mib) as usize, mib as usize); + title_memory_write_combined((base + 11 * mib) as usize, (27 * mib) as usize); + title_memory_gpu_read_only((base + 11 * mib) as usize, (27 * mib) as usize); + title_memory_write_combined((base + 38 * mib) as usize, (47 * mib) as usize); + + // 174 MiB copy starting at +11 MiB (spans 27M 0x8404, 47M 0x2404, 100M 0x2004). + let copy_start = base + 11 * mib; + let copy_len = 174 * mib; + assert!(!is_write_combined(copy_start, copy_len), "mixed copy is not wholly WC"); + let policy = |has_card, ro_on, wc_subrange_on, copy_len| GpuWritePolicy { + copy_len, + has_card, + ro_on, + wc_subrange_on, + wc_min: min_1mib, + }; + + // With both GPU_RO and WC_SUBRANGE enabled: 27 MiB counted as RO, 47 MiB as WC, 100 MiB kept. + assert_eq!( + plan_gpu_write_ranges(copy_start, copy_len, policy(true, true, true, copy_len)), + GpuWritePlan { + keep: vec![(base + 85 * mib, base + 185 * mib)], + ro_declared: 27 * mib, + ro_left: 27 * mib, + wc_left: 47 * mib, + } + ); + + // Targeted UAV write strictly inside the 47 MiB 0x2404 sub-range inside the 174 MiB copy. + assert_eq!( + plan_gpu_write_ranges(base + 40 * mib, 256 * 1024, policy(true, true, true, copy_len)), + GpuWritePlan { keep: vec![], ro_declared: 0, ro_left: 0, wc_left: 256 * 1024 } + ); + + // With GPU_RO off and WC_SUBRANGE on: 27 MiB 0x8404 is WC too so all 74 MiB WC is skipped. + assert_eq!( + plan_gpu_write_ranges(copy_start, copy_len, policy(true, false, true, copy_len)), + GpuWritePlan { + keep: vec![(base + 85 * mib, base + 185 * mib)], + ro_declared: 27 * mib, + ro_left: 0, + wc_left: 74 * mib, + } + ); + + // Small copy (4 KiB < 1 MiB) or host-only copy (has_card=false): WC is kept. + assert_eq!( + plan_gpu_write_ranges(base + 40 * mib, 4096, policy(true, true, true, 4096)), + GpuWritePlan { keep: vec![(base + 40 * mib, base + 40 * mib + 4096)], ro_declared: 0, ro_left: 0, wc_left: 0 } + ); + assert_eq!( + plan_gpu_write_ranges(copy_start, copy_len, policy(false, true, true, copy_len)), + GpuWritePlan { keep: vec![(base + 38 * mib, base + 185 * mib)], ro_declared: 27 * mib, ro_left: 27 * mib, wc_left: 0 } + ); + + // A small 512 KiB WC sub-region inside a large mixed copy is NOT skipped when floor is 1 MiB. + let small_wc = base + 190 * mib; + title_memory_write_combined(small_wc as usize, (512 * 1024) as usize); + assert_eq!( + plan_gpu_write_ranges(base + 185 * mib, 10 * mib, policy(true, true, true, 10 * mib)), + GpuWritePlan { + keep: vec![(base + 185 * mib, base + 195 * mib)], + ro_declared: 0, + ro_left: 0, + wc_left: 0, + } + ); + } + + #[test] + fn classify_write_combined_distinguishes_none_whole_and_partial() { + let base = 0x7b00_0000_0000u64; + let mib = 1024 * 1024; + let _guard = Cleanup(base, 32 * mib); + + // Small under-floor WC region + larger covering region. + title_memory_write_combined(base as usize, (512 * 1024) as usize); + title_memory_write_combined((base + 2 * mib) as usize, (2 * mib) as usize); + title_memory_write_combined((base + 2 * mib) as usize, (4 * mib) as usize); + // Standalone 2 MiB WC sub-range for mixed span test. + title_memory_write_combined((base + 10 * mib) as usize, (2 * mib) as usize); + + assert_eq!(classify_write_combined(base + 20 * mib, 4 * mib, mib), WcKind::None, "outside WC"); + assert_eq!(classify_write_combined(base, mib, mib), WcKind::None, "overlapping WC below floor"); + assert_eq!(classify_write_combined(base, mib, 512 * 1024), WcKind::Partial, "meets smaller floor"); + assert_eq!( + classify_write_combined(base + 2 * mib, 4 * mib, mib), + WcKind::Whole, + "(start, mid) plus covering (start, end) is still Whole" + ); + assert_eq!(classify_write_combined(base + 9 * mib, 6 * mib, mib), WcKind::Partial, "mixed copy span"); + } + + #[test] + fn small_ranges_spills_past_four_intervals() { + let base = 0x7a00_0000_0000u64; + let mib = 1024 * 1024; + let _guard = Cleanup(base, 32 * mib); + + // 5 disjoint 1 MiB WC holes at +1, +3, +5, +7, +9 MiB inside a 12 MiB range -> 6 kept segments. + for hole in 0..5 { + title_memory_write_combined((base + (1 + 2 * hole) * mib) as usize, mib as usize); + } + assert_eq!( + plan_gpu_write_ranges( + base, + 12 * mib, + GpuWritePolicy { + copy_len: 12 * mib, + has_card: true, + ro_on: true, + wc_subrange_on: true, + wc_min: mib, + }, + ), + GpuWritePlan { + keep: vec![ + (base, base + mib), + (base + 2 * mib, base + 3 * mib), + (base + 4 * mib, base + 5 * mib), + (base + 6 * mib, base + 7 * mib), + (base + 8 * mib, base + 9 * mib), + (base + 10 * mib, base + 12 * mib), + ], + ro_declared: 0, + ro_left: 0, + wc_left: 5 * mib, + } + ); + } + + #[test] + fn wc_subrange_switch_policy_cases() { + assert!(!wc_subrange_enabled(false, None, false)); + assert!(wc_subrange_enabled(false, None, true)); + assert!(!wc_subrange_enabled(true, None, true), "LEONIDA_WC_NO_BACK=0 disables sub-range"); + assert!(!wc_subrange_enabled(false, Some(false), true), "LEONIDA_AB WC=off overrides"); + assert!(wc_subrange_enabled(true, Some(true), true), "LEONIDA_AB WC=on overrides explicit 0"); + assert!(!wc_subrange_enabled(false, Some(true), false), "sub-range switch still required"); + } } #[cfg(test)] @@ -4101,10 +4598,22 @@ impl Shadow { } self.written.store(true, Ordering::Relaxed); let len = len.min(self.left(address)); + if len == 0 { + return; + } // Write-combined title memory, which the title's CPU does not read // (`LEONIDA_WC_NO_BACK`, trustno1-coder/VIctory-NVIDIA 50c15a1, GPL-3.0): // what shaders write in a big copy with a card side stays on the card. - if self.card.is_some() && self.len >= wc_no_back_min() && wc_no_back() && self.write_combined() { + let wc_min = wc_no_back_min(); + let has_card = self.card.is_some(); + let wc_whole_on = has_card && self.len >= wc_min && wc_no_back(); + let wc_subrange_on = has_card && self.len >= wc_min && wc_subrange_no_back(); + let wc_kind = if (wc_whole_on || wc_subrange_on) && ANY_WRITE_COMBINED.load(Ordering::Relaxed) { + self.wc_kind(wc_min, wc_whole_on) + } else { + WcKind::None + }; + if wc_whole_on && wc_kind == WcKind::Whole { WC_LEFT.fetch_add(len, Ordering::Relaxed); return; } @@ -4114,47 +4623,61 @@ impl Shadow { self.elide_skipped(len); return; } - // Leonida: parts the console has the GPU read only cannot have been written there - // (`title_memory_gpu_read_only`, `LEONIDA_GPU_READ_ONLY_NO_BACK`): counted, and left out with the switch. - let read_only = gpu_read_only_parts(address, address + len); - if !read_only.is_empty() { - let bytes: u64 = read_only.iter().map(|&(from, to)| to - from).sum(); - GPU_RO_DECLARED[0].fetch_add(bytes, Ordering::Relaxed); - if gpu_ro_no_back() { - GPU_RO_DECLARED[1].fetch_add(bytes, Ordering::Relaxed); - let mut at = address; - for (from, to) in read_only { - if from > at { - list.defer_gpu_write(self, at as usize, (from - at) as usize); - } - at = at.max(to); - } - if at < address + len { - list.defer_gpu_write(self, at as usize, (address + len - at) as usize); - } - return; - } + // Fast zero-allocation path when neither GPU read-only nor write-combined sub-range + // filtering can apply to this copy. + let wc_subrange = wc_subrange_on && wc_kind == WcKind::Partial; + if !ANY_GPU_READ_ONLY.load(Ordering::Relaxed) && !wc_subrange { + list.defer_gpu_write(self, address as usize, len as usize); + return; + } + // Leonida: subtract GPU read-only parts first, then qualifying write-combined sub-ranges + // inside mixed copies (`LEONIDA_WC_SUBRANGE_NO_BACK`). + let stats = for_each_gpu_write_range( + address, + len, + GpuWritePolicy { + copy_len: self.len, + has_card, + ro_on: gpu_ro_no_back(), + wc_subrange_on: wc_subrange, + wc_min, + }, + |from, to| list.defer_gpu_write(self, from as usize, (to - from) as usize), + ); + if stats.ro_declared != 0 { + GPU_RO_DECLARED[0].fetch_add(stats.ro_declared, Ordering::Relaxed); + } + if stats.ro_left != 0 { + GPU_RO_DECLARED[1].fetch_add(stats.ro_left, Ordering::Relaxed); + } + if stats.wc_left != 0 { + WC_LEFT.fetch_add(stats.wc_left, Ordering::Relaxed); } - list.defer_gpu_write(self, address as usize, len as usize); } - /// Whether all of the copy's title memory was asked for write-combined - /// ([`title_memory_write_combined`]); found once (`LEONIDA_WC_NO_BACK`). - fn write_combined(&self) -> bool { + /// Write-combined classification of the copy's title memory + /// ([`title_memory_write_combined`]); found once (`LEONIDA_WC_NO_BACK` / `LEONIDA_WC_SUBRANGE_NO_BACK`). + fn wc_kind(&self, wc_min: u64, log_whole: bool) -> WcKind { match self.wc.load(Ordering::Relaxed) { - 1 => false, - 2 => true, + 1 => WcKind::None, + 2 => WcKind::Whole, + 3 => WcKind::Partial, _ => { - let wc = is_write_combined(self.start, self.len); - self.wc.store(if wc { 2 } else { 1 }, Ordering::Relaxed); - if wc { + let kind = classify_write_combined(self.start, self.len, wc_min); + let code = match kind { + WcKind::None => 1, + WcKind::Whole => 2, + WcKind::Partial => 3, + }; + let prev = self.wc.swap(code, Ordering::Relaxed); + if prev == 0 && kind == WcKind::Whole && log_whole { tracing::info!( start = format_args!("{:#x}", self.start), len = format_args!("{:#x}", self.len), "write-combined title memory: what shaders write in its copy is not copied back (LEONIDA_WC_NO_BACK)" ); } - wc + kind } } } diff --git a/d3d12/crates/leonida-gpu/src/watch.rs b/d3d12/crates/leonida-gpu/src/watch.rs index 02edd8e29d..c230dca8fe 100644 --- a/d3d12/crates/leonida-gpu/src/watch.rs +++ b/d3d12/crates/leonida-gpu/src/watch.rs @@ -4261,12 +4261,26 @@ pub fn title_memory_unmapping(at: usize, len: usize) { /// was noted of its blocks (guarded, clean, absent) would be taken for true /// of the next memory at the address. pub fn title_memory_freed(at: usize, len: usize) { - // (`LEONIDA_WC_NO_BACK`: write-combined regions in it are forgotten.) - crate::shadow::write_combined_freed(at, len); + let mut alloc_end = None; + let resolve_end = |cached: &mut Option| -> usize { + if at == 0 { + return 0; + } + *cached.get_or_insert_with(|| allocation_end(at, at)) + }; + // (`LEONIDA_WC_NO_BACK`: write-combined and GPU read-only regions in it are forgotten.) + let wc_len = if len != 0 { + len + } else if crate::shadow::has_memory_classes() { + resolve_end(&mut alloc_end).saturating_sub(at) + } else { + 0 + }; + crate::shadow::write_combined_freed(at, wc_len); if len != 0 { forget_views(at / BLOCK, at.saturating_add(len).div_ceil(BLOCK)); } else if VIEWS.any(at / BLOCK, at / BLOCK + 1) { - forget_views(at / BLOCK, allocation_end(at, at).div_ceil(BLOCK).max(at / BLOCK + 1)); + forget_views(at / BLOCK, resolve_end(&mut alloc_end).div_ceil(BLOCK).max(at / BLOCK + 1)); } let mut g = guards(); let first = at / BLOCK; diff --git a/d3d12/crates/leonida-hle/src/modules/xmem.rs b/d3d12/crates/leonida-hle/src/modules/xmem.rs index 16e83c130f..99393503db 100644 --- a/d3d12/crates/leonida-hle/src/modules/xmem.rs +++ b/d3d12/crates/leonida-hle/src/modules/xmem.rs @@ -128,7 +128,10 @@ pub extern "system" fn XMemVirtualAlloc( // the part is said all the same: the five parts of its 32-bit graphics heap, // which carry most of the bytes sent up and fetched a frame, come this way.) note_protection(asked, kind, flags, base as usize, size); - if gpu_read_only(asked) { + if !base.is_null() && asked & 0x400 != 0 { + leonida_gpu::title_memory_write_combined(base as usize, size); + } + if !base.is_null() && gpu_read_only(asked) { leonida_gpu::title_memory_gpu_read_only(base as usize, size); } return base; @@ -3218,4 +3221,54 @@ mod tests { assert_eq!(XMemFreePhysicalPages(3, a.as_ptr()), 1); assert_eq!(XMemFreePhysicalPages(1, b.as_ptr()), 1); } + + #[test] + fn placeholder_replace_registers_write_combined_and_gpu_read_only() { + let base = XMemVirtualAlloc( + std::ptr::null_mut(), + 4 * PAGE, + MEM_RESERVE | PAGES_64K, + GRAPHICS | ADDRESS_32BIT, + PAGE_NOACCESS, + ); + assert!(!base.is_null()); + let at = |page: usize| base.wrapping_byte_add(page * PAGE); + + // 0: CPU RW + GPU RO (0x1004) + // 1: WC + GPU execute-read / RO (0x8404) + // 2: WC + GPU RW (0x2404) + // 3: CPU cached + GPU RW (0x2004) + let protects = [0x1004u32, 0x8404, 0x2404, 0x2004]; + for (page, protect) in protects.iter().enumerate() { + let p = XMemVirtualAlloc( + at(page), + PAGE, + MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | PAGES_64K, + GRAPHICS | ADDRESS_32BIT, + *protect, + ); + assert_eq!(p, at(page)); + } + + let wc: Vec = (0..4) + .map(|page| leonida_gpu::title_memory_is_write_combined(at(page) as usize, PAGE)) + .collect(); + let ro: Vec = (0..4) + .map(|page| leonida_gpu::title_memory_is_gpu_read_only(at(page) as usize, PAGE)) + .collect(); + assert_eq!(wc, vec![false, true, true, false]); + assert_eq!(ro, vec![true, true, false, false]); + + assert_ne!(title_virtual_free(base, 0, MEM_RELEASE), 0); + for page in 0..4 { + assert!( + !leonida_gpu::title_memory_is_write_combined(at(page) as usize, PAGE), + "WC cleared on page {page}" + ); + assert!( + !leonida_gpu::title_memory_is_gpu_read_only(at(page) as usize, PAGE), + "GPU RO cleared on page {page}" + ); + } + } }