RX 7900 XT (RDNA 3) / RADV: a port of VICTORY_WC_NO_BACK takes ~11 ms off a CPU-bound frame (measurements on 88abc53) #19

Open
opened 2026-11-29 14:50:45 +00:00 by GreemSC · 3 comments
GreemSC commented 2026-11-29 14:50:45 +00:00 (Migrated from github.com)
Contributor

Imported from Slaktarn700/SlaktarnVI. Originally posted by GreemSC on 2026-11-29T14:50:45Z.


Thank you for SlaktarnVI. These are measurements on an RDNA 3 card, where the frame is bound by the CPU's memory work like in #18 and #4, and a port of VICTORY_WC_NO_BACK that took about 11 ms off the frame here. All numbers are from one machine; please treat them as such.

Setup: RX 7900 XT 20 GB (RDNA 3), i7-12700K, 24 GB RAM, Arch-based distro, kernel 7.2, Mesa 26.2.5 RADV, Proton-CachyOS with a view-tree wineserver. SlaktarnVI 88abc53, linux/run-7900.sh defaults plus CONSOLE=series-s, 1920x1080, 30 fps pacing, VICTORY_CARD_BUFFERS_MIN_KB=64, no FSR, no ray tracing. Each run: 200 s from the start of the title, intro skipped with VICTORY_KEYS, then the opening cutscene and the start of the prologue, no input. The figure is the median of the victory_gpu::host meter lines with at least 2,000 draws a frame. Run-to-run noise here is about ±4 ms.

Results

Build and settings ms/frame Runs
diag, defaults (VICTORY_FILL_TITLE alternating in-run, no difference) 84.8 1
diag, VICTORY_PORT_CONSTANTS=0 VICTORY_REFRESH_DIRTY=1 77.2, 80.5 2
release, same 73.3 (76.9–77.6 in three more runs with the no-effect settings below) 1 + 3
release + the port below, same + VICTORY_WC_NO_BACK=1 63.2, 61.7 2
release + the port, VICTORY_WC_NO_BACK=1 but VICTORY_PORT_CONSTANTS=1 82.2 1
  • In-run A/B of VICTORY_WC_NO_BACK (diag, VICTORY_AB=12,VICTORY_WC_NO_BACK): 67.5 ms on against 78.8 ms off. All 6 pairs of phases go the same way (on/off: 66.5/79.8, 62.6/74.2, 69.2/79.2, 82.5/89.2, 63.3/78.8, 64.2/73.3). The copy back went from about 44 MB / 30 ms to 22 MB / 15 ms a frame.
  • Picture: a separate A/B run with VICTORY_CAPTURE. Frames on either side of each switch compared by SSIM, plus a look by eye: no difference found in exposure, faces or lighting, and no darkening. Only the opening cutscene and the first minutes of the prologue were checked, not driving or daytime outdoors.
  • VICTORY_PORT_CONSTANTS=0 confirms #12 on RDNA 3: with it on, the per-submission userptr cost comes back even with fewer copies (82.2 ms against 61.7–63.2).

No effect here:

  • VICTORY_FILL_TITLE (A/B: 81.1 on / 81.5 off)
  • VICTORY_CARD_BUFFERS_MB=4096 (the 20 GB card reports vram_budget_mb=16861, so it lands in the 16 GB bucket)
  • lto = "fat" with codegen-units = 1
  • VKD3D_CONFIG=force_host_cached
  • WINE_CPU_TOPOLOGY=p

Measurement note: VICTORY_CAPTURE plus per-frame victory_gpu::frame=debug logging cost about 25 ms a frame here, so the speed runs above have neither.

The port

This is VICTORY_WC_NO_BACK and VICTORY_WC_NO_BACK_MIN_KB from readmet3xt-lab/foxhound 50c15a1 and 2f81d0c (also in trustno1-coder/VIctory-NVIDIA), by readmet3xt-lab, GPL-3.0-or-later.

  • XMemVirtualAlloc notes the regions the title asks for write-combined (0x400).
  • For a copy with a card side that lies wholly in such a region and is at least MIN_KB (default 1024), Shadow::gpu_writes no longer declares the shader write. There is then no snapshot, compare, fetch or merge for it.
  • The switch is off by default, and an ab::pick switch in diag builds.
  • VICTORY_WC_BAR is not ported.

Risks are listed in the doc comment of wc_no_back().

Tested:

  • The diff applies on 88abc53 and builds there (release and diag, --locked, no warnings).
  • The runs above.

Not tested:

  • The unit test in the diff (the suite needs Wine here).
  • Windows.
  • Other cards.
  • Long play sessions.

The port was written with Claude (Fable) and reviewed and measured by me with Claude (Opus).

wc-no-back.diff (against 88abc53)
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index 6ced0ae..48d7215 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -10306,10 +10306,12 @@ impl Meter {
             split_line(frames);
             {
                 let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
-                if passes + compares > 0.0 {
+                let wc_left = crate::shadow::WC_LEFT.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames;
+                if passes + compares + wc_left > 0.0 {
                     tracing::info!(
                         "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
-                         ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
+                         ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes; \
+                         {wc_left:.1} MB declared written in write-combined memory left on the card (VICTORY_WC_NO_BACK)",
                         if rehash_runs() { "on" } else { "off" }
                     );
                 }
diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs
index d1979e0..5361108 100644
--- a/crates/victory-gpu/src/lib.rs
+++ b/crates/victory-gpu/src/lib.rs
@@ -157,6 +157,8 @@ pub fn frames_begun() -> u64 {
 #[cfg(windows)]
 pub use inplace::{title_memory_freeing, title_memory_quiesce, title_memory_section, title_memory_section_gone, title_memory_view};
 #[cfg(windows)]
+pub use shadow::title_memory_write_combined;
+#[cfg(windows)]
 pub use watch::{
     view_watch, kernel_writing, title_memory_allocated, title_memory_freed, title_memory_unguarded, title_placeholder_released, title_placeholder_reserved, title_memory_reading, title_memory_remapped,
     title_memory_remapping, title_memory_splitting, title_memory_unmapping, title_memory_written,
diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index 91dd205..80da4ef 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -105,6 +105,9 @@ pub(crate) struct Shadow {
     /// Of a copy with two sides: only the dwords the title changed go up,
     /// as with [`send_changed`] ([`by_address`]).
     changes_only: std::sync::atomic::AtomicBool,
+    /// Whether its title memory is write-combined ([`Shadow::write_combined`]):
+    /// 0 not known yet, 1 no, 2 yes.
+    wc: AtomicU8,
     /// A window in card memory the CPU maps ([`window_mapped_for`]).
     mapped: bool,
     /// An arena of title memory by address ([`by_address`] with `own`): the
@@ -2187,6 +2190,88 @@ fn land_echo() -> bool {
     crate::toggled!("VICTORY_LAND_ECHO")
 }
 
+/// 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<Vec<(u64, u64)>> = RwLock::new(Vec::new());
+
+/// 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
+/// console, the GDK's read-back memory is cacheable).
+pub fn title_memory_write_combined(at: usize, len: usize) {
+    if len == 0 {
+        return;
+    }
+    let (from, to) = (at as u64, at.saturating_add(len) as u64);
+    let mut all = WRITE_COMBINED.write().unwrap_or_else(|e| e.into_inner());
+    // (Commits inside a region noted when it was reserved add nothing.)
+    if !all.iter().any(|&(a, e)| a <= from && to <= e) {
+        all.push((from, to));
+    }
+}
+
+/// The title let go of `[at, at + len)` (`len` 0: of the allocation at `at`):
+/// write-combined 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);
+    let mut all = WRITE_COMBINED.write().unwrap_or_else(|e| e.into_inner());
+    all.retain(|&(from, to)| if len == 0 { from != at } else { to <= at || from >= end });
+}
+
+/// 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 {
+    let all = WRITE_COMBINED.read().unwrap_or_else(|e| e.into_inner());
+    all.iter().any(|&(from, to)| from <= start && start + len <= to)
+}
+
+/// Whether what shaders write into copies in the card's memory of
+/// write-combined title memory stays on the card and is not compared,
+/// fetched and merged into title memory (`VICTORY_WC_NO_BACK=1`; off by
+/// default: an experiment; an A/B switch in diagnostics builds). From
+/// readmet3xt-lab/foxhound 50c15a1 (also in trustno1-coder/VIctory-NVIDIA).
+///
+/// The write-back of shader writes (`Shadow::gpu_writes`: hashes after
+/// sends, compare passes after the lists, fetches of the pieces that differ
+/// and their merge into title memory) keeps title memory the newest for the
+/// title's CPU. Memory the title asked for write-combined (protection
+/// 0x400) is what its CPU writes and the GPU reads.
+///
+/// What it risks, and why it may hold:
+/// - The title's CPU reading what shaders wrote there reads older bytes.
+///   Read back, write-combined memory is uncached on the console too, and
+///   results the CPU reads go to cacheable memory. Small copies are left
+///   out all the same ([`wc_no_back_min`]).
+/// - A page the CPU writes goes up whole from title memory (as before) and
+///   so takes back what shaders wrote in the same 4 KiB page since: mixed
+///   pages lose the shaders' bytes (with the write-back they were in title
+///   memory).
+/// - Another host copy of the same bytes (a texture placed there, a single
+///   view's copy) does not see what shaders wrote through title memory.
+/// - Changed while the title runs (`VICTORY_AB`): what shaders wrote while
+///   it was on is not in title memory when it goes off.
+fn wc_no_back() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    let on = *ON.get_or_init(|| std::env::var_os("VICTORY_WC_NO_BACK").is_some_and(|v| v == "1"));
+    #[cfg(feature = "diagnostics")]
+    let on = crate::ab::pick("VICTORY_WC_NO_BACK").unwrap_or(on);
+    on
+}
+
+/// The smallest copy whose shader writes [`wc_no_back`] leaves on the card,
+/// in bytes (`VICTORY_WC_NO_BACK_MIN_KB`, 1024 unset; 0: all). With every
+/// copy left, upstream's cutscenes went near black (readmet3xt-lab/foxhound
+/// 2f81d0c: small results the title reads back, such as exposure, came back
+/// stale; 3,245 write-combined copies there, median 4 KB, 82 of 1 MB or
+/// more) while most of the saving is in a few ranges of hundreds of MB.
+fn wc_no_back_min() -> u64 {
+    static MIN: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+    *MIN.get_or_init(|| std::env::var("VICTORY_WC_NO_BACK_MIN_KB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(1024) << 10)
+}
+
+/// Bytes shaders were declared to write in write-combined copies and that
+/// were left on the card ([`wc_no_back`]), since the last frame-rate line.
+pub(crate) static WC_LEFT: AtomicU64 = AtomicU64::new(0);
+
 /// Whether we run under Wine: its ntdll exports `wine_get_version` (as
 /// `victory_hle::modules::xmem` tells it).
 pub(crate) fn on_wine() -> bool {
@@ -3438,6 +3523,7 @@ impl Shadow {
             card: None,
             window: false,
             changes_only: Default::default(),
+            wc: AtomicU8::new(0),
             mapped: false,
             own_side: false,
             place: None,
@@ -3469,11 +3555,39 @@ impl Shadow {
         if self.place.is_some() {
             return;
         }
+        // Write-combined title memory, which the title's CPU does not read
+        // (`VICTORY_WC_NO_BACK`): what shaders write stays on the card.
+        if self.card.is_some() && wc_no_back() && self.len >= wc_no_back_min() && self.write_combined() {
+            self.written.store(true, Ordering::Relaxed);
+            WC_LEFT.fetch_add(len.min(self.left(address)), Ordering::Relaxed);
+            return;
+        }
         self.written.store(true, Ordering::Relaxed);
         let len = len.min(self.left(address));
         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.
+    fn write_combined(&self) -> bool {
+        match self.wc.load(Ordering::Relaxed) {
+            1 => false,
+            2 => true,
+            _ => {
+                let wc = is_write_combined(self.start, self.len);
+                self.wc.store(if wc { 2 } else { 1 }, Ordering::Relaxed);
+                if wc {
+                    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 (VICTORY_WC_NO_BACK)"
+                    );
+                }
+                wc
+            }
+        }
+    }
+
     /// At submission, after the range's refresh: a submitted list's shaders
     /// write this range. Its bytes are kept to tell later what the GPU wrote:
     /// one snapshot per copy and submission, each byte taken once, when the
@@ -7529,3 +7643,29 @@ mod plain_tests {
         assert_eq!(plain_side_bytes(), before);
     }
 }
+
+#[cfg(test)]
+mod write_combined_tests {
+    use super::{is_write_combined, title_memory_write_combined, write_combined_freed};
+
+    /// 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).
+    #[test]
+    fn write_combined_regions() {
+        // Addresses of their own: other tests share the registry.
+        let base = 0x7f00_0000_0000usize;
+        title_memory_write_combined(base, 0x100_0000);
+        // (A commit inside it adds nothing.)
+        title_memory_write_combined(base + 0x1000, 0x1000);
+        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");
+        write_combined_freed(base + 0x10_0000, 0x1000);
+        assert!(!is_write_combined(base as u64, 0x1000), "part of it decommitted");
+        let other = base + 0x1000_0000;
+        title_memory_write_combined(other, 0x10_0000);
+        write_combined_freed(other, 0);
+        assert!(!is_write_combined(other as u64, 0x1000), "the allocation released");
+    }
+}
diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs
index fbcf560..f050f1f 100644
--- a/crates/victory-gpu/src/watch.rs
+++ b/crates/victory-gpu/src/watch.rs
@@ -4284,6 +4284,7 @@ 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) {
+    crate::shadow::write_combined_freed(at, len);
     crate::memory::title_let_go(at, len);
     if len != 0 {
         let last = at.saturating_add(len).div_ceil(BLOCK);
diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs
index f19b9db..8e2d255 100644
--- a/crates/victory-hle/src/modules/xmem.rs
+++ b/crates/victory-hle/src/modules/xmem.rs
@@ -191,6 +191,10 @@ pub extern "system" fn XMemVirtualAlloc(
     if !at.is_null() && constrained && kind & MEM_COMMIT == 0 && flags & ADDRESS_32BIT != 0 {
         LOW_RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner()).push((at as usize, size));
     }
+    // Write-combined: memory the title's CPU writes and does not read.
+    if !at.is_null() && asked & 0x400 != 0 {
+        victory_gpu::title_memory_write_combined(at as usize, size);
+    }
     note_protection(asked, kind, flags, at as usize, size);
     at
 }
<!-- greyfinch-sync:Slaktarn700/SlaktarnVI:issue:6680133626 --> Imported from [Slaktarn700/SlaktarnVI](https://github.com/Slaktarn700/SlaktarnVI/issues/19). Originally posted by [GreemSC](https://github.com/GreemSC) on 2026-11-29T14:50:45Z. --- Thank you for SlaktarnVI. These are measurements on an RDNA 3 card, where the frame is bound by the CPU's memory work like in #18 and #4, and a port of `VICTORY_WC_NO_BACK` that took about 11 ms off the frame here. All numbers are from one machine; please treat them as such. **Setup:** RX 7900 XT 20 GB (RDNA 3), i7-12700K, 24 GB RAM, Arch-based distro, kernel 7.2, Mesa 26.2.5 RADV, Proton-CachyOS with a view-tree wineserver. SlaktarnVI `88abc53`, `linux/run-7900.sh` defaults plus `CONSOLE=series-s`, 1920x1080, 30 fps pacing, `VICTORY_CARD_BUFFERS_MIN_KB=64`, no FSR, no ray tracing. Each run: 200 s from the start of the title, intro skipped with `VICTORY_KEYS`, then the opening cutscene and the start of the prologue, no input. The figure is the median of the `victory_gpu::host` meter lines with at least 2,000 draws a frame. Run-to-run noise here is about ±4 ms. ## Results | Build and settings | ms/frame | Runs | |---|---|---| | diag, defaults (`VICTORY_FILL_TITLE` alternating in-run, no difference) | 84.8 | 1 | | diag, `VICTORY_PORT_CONSTANTS=0 VICTORY_REFRESH_DIRTY=1` | 77.2, 80.5 | 2 | | release, same | 73.3 (76.9–77.6 in three more runs with the no-effect settings below) | 1 + 3 | | release + the port below, same + `VICTORY_WC_NO_BACK=1` | **63.2, 61.7** | 2 | | release + the port, `VICTORY_WC_NO_BACK=1` but `VICTORY_PORT_CONSTANTS=1` | 82.2 | 1 | - **In-run A/B of `VICTORY_WC_NO_BACK`** (diag, `VICTORY_AB=12,VICTORY_WC_NO_BACK`): 67.5 ms on against 78.8 ms off. All 6 pairs of phases go the same way (on/off: 66.5/79.8, 62.6/74.2, 69.2/79.2, 82.5/89.2, 63.3/78.8, 64.2/73.3). The copy back went from about 44 MB / 30 ms to 22 MB / 15 ms a frame. - **Picture:** a separate A/B run with `VICTORY_CAPTURE`. Frames on either side of each switch compared by SSIM, plus a look by eye: no difference found in exposure, faces or lighting, and no darkening. Only the opening cutscene and the first minutes of the prologue were checked, not driving or daytime outdoors. - **`VICTORY_PORT_CONSTANTS=0`** confirms #12 on RDNA 3: with it on, the per-submission userptr cost comes back even with fewer copies (82.2 ms against 61.7–63.2). **No effect here:** - `VICTORY_FILL_TITLE` (A/B: 81.1 on / 81.5 off) - `VICTORY_CARD_BUFFERS_MB=4096` (the 20 GB card reports `vram_budget_mb=16861`, so it lands in the 16 GB bucket) - `lto = "fat"` with `codegen-units = 1` - `VKD3D_CONFIG=force_host_cached` - `WINE_CPU_TOPOLOGY=p` **Measurement note:** `VICTORY_CAPTURE` plus per-frame `victory_gpu::frame=debug` logging cost about 25 ms a frame here, so the speed runs above have neither. ## The port This is `VICTORY_WC_NO_BACK` and `VICTORY_WC_NO_BACK_MIN_KB` from readmet3xt-lab/foxhound `50c15a1` and `2f81d0c` (also in trustno1-coder/VIctory-NVIDIA), by readmet3xt-lab, GPL-3.0-or-later. - `XMemVirtualAlloc` notes the regions the title asks for write-combined (0x400). - For a copy with a card side that lies wholly in such a region and is at least `MIN_KB` (default 1024), `Shadow::gpu_writes` no longer declares the shader write. There is then no snapshot, compare, fetch or merge for it. - The switch is off by default, and an `ab::pick` switch in diag builds. - `VICTORY_WC_BAR` is not ported. Risks are listed in the doc comment of `wc_no_back()`. **Tested:** - The diff applies on `88abc53` and builds there (release and diag, `--locked`, no warnings). - The runs above. **Not tested:** - The unit test in the diff (the suite needs Wine here). - Windows. - Other cards. - Long play sessions. The port was written with Claude (Fable) and reviewed and measured by me with Claude (Opus). <details><summary>wc-no-back.diff (against 88abc53)</summary> ```diff diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6ced0ae..48d7215 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -10306,10 +10306,12 @@ impl Meter { split_line(frames); { let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); - if passes + compares > 0.0 { + let wc_left = crate::shadow::WC_LEFT.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames; + if passes + compares + wc_left > 0.0 { tracing::info!( "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ - ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes", + ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes; \ + {wc_left:.1} MB declared written in write-combined memory left on the card (VICTORY_WC_NO_BACK)", if rehash_runs() { "on" } else { "off" } ); } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index d1979e0..5361108 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -157,6 +157,8 @@ pub fn frames_begun() -> u64 { #[cfg(windows)] pub use inplace::{title_memory_freeing, title_memory_quiesce, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] +pub use shadow::title_memory_write_combined; +#[cfg(windows)] pub use watch::{ view_watch, kernel_writing, title_memory_allocated, title_memory_freed, title_memory_unguarded, title_placeholder_released, title_placeholder_reserved, title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_splitting, title_memory_unmapping, title_memory_written, diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 91dd205..80da4ef 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -105,6 +105,9 @@ pub(crate) struct Shadow { /// Of a copy with two sides: only the dwords the title changed go up, /// as with [`send_changed`] ([`by_address`]). changes_only: std::sync::atomic::AtomicBool, + /// Whether its title memory is write-combined ([`Shadow::write_combined`]): + /// 0 not known yet, 1 no, 2 yes. + wc: AtomicU8, /// A window in card memory the CPU maps ([`window_mapped_for`]). mapped: bool, /// An arena of title memory by address ([`by_address`] with `own`): the @@ -2187,6 +2190,88 @@ fn land_echo() -> bool { crate::toggled!("VICTORY_LAND_ECHO") } +/// 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<Vec<(u64, u64)>> = RwLock::new(Vec::new()); + +/// 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 +/// console, the GDK's read-back memory is cacheable). +pub fn title_memory_write_combined(at: usize, len: usize) { + if len == 0 { + return; + } + let (from, to) = (at as u64, at.saturating_add(len) as u64); + let mut all = WRITE_COMBINED.write().unwrap_or_else(|e| e.into_inner()); + // (Commits inside a region noted when it was reserved add nothing.) + if !all.iter().any(|&(a, e)| a <= from && to <= e) { + all.push((from, to)); + } +} + +/// The title let go of `[at, at + len)` (`len` 0: of the allocation at `at`): +/// write-combined 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); + let mut all = WRITE_COMBINED.write().unwrap_or_else(|e| e.into_inner()); + all.retain(|&(from, to)| if len == 0 { from != at } else { to <= at || from >= end }); +} + +/// 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 { + let all = WRITE_COMBINED.read().unwrap_or_else(|e| e.into_inner()); + all.iter().any(|&(from, to)| from <= start && start + len <= to) +} + +/// Whether what shaders write into copies in the card's memory of +/// write-combined title memory stays on the card and is not compared, +/// fetched and merged into title memory (`VICTORY_WC_NO_BACK=1`; off by +/// default: an experiment; an A/B switch in diagnostics builds). From +/// readmet3xt-lab/foxhound 50c15a1 (also in trustno1-coder/VIctory-NVIDIA). +/// +/// The write-back of shader writes (`Shadow::gpu_writes`: hashes after +/// sends, compare passes after the lists, fetches of the pieces that differ +/// and their merge into title memory) keeps title memory the newest for the +/// title's CPU. Memory the title asked for write-combined (protection +/// 0x400) is what its CPU writes and the GPU reads. +/// +/// What it risks, and why it may hold: +/// - The title's CPU reading what shaders wrote there reads older bytes. +/// Read back, write-combined memory is uncached on the console too, and +/// results the CPU reads go to cacheable memory. Small copies are left +/// out all the same ([`wc_no_back_min`]). +/// - A page the CPU writes goes up whole from title memory (as before) and +/// so takes back what shaders wrote in the same 4 KiB page since: mixed +/// pages lose the shaders' bytes (with the write-back they were in title +/// memory). +/// - Another host copy of the same bytes (a texture placed there, a single +/// view's copy) does not see what shaders wrote through title memory. +/// - Changed while the title runs (`VICTORY_AB`): what shaders wrote while +/// it was on is not in title memory when it goes off. +fn wc_no_back() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let on = *ON.get_or_init(|| std::env::var_os("VICTORY_WC_NO_BACK").is_some_and(|v| v == "1")); + #[cfg(feature = "diagnostics")] + let on = crate::ab::pick("VICTORY_WC_NO_BACK").unwrap_or(on); + on +} + +/// The smallest copy whose shader writes [`wc_no_back`] leaves on the card, +/// in bytes (`VICTORY_WC_NO_BACK_MIN_KB`, 1024 unset; 0: all). With every +/// copy left, upstream's cutscenes went near black (readmet3xt-lab/foxhound +/// 2f81d0c: small results the title reads back, such as exposure, came back +/// stale; 3,245 write-combined copies there, median 4 KB, 82 of 1 MB or +/// more) while most of the saving is in a few ranges of hundreds of MB. +fn wc_no_back_min() -> u64 { + static MIN: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MIN.get_or_init(|| std::env::var("VICTORY_WC_NO_BACK_MIN_KB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(1024) << 10) +} + +/// Bytes shaders were declared to write in write-combined copies and that +/// were left on the card ([`wc_no_back`]), since the last frame-rate line. +pub(crate) static WC_LEFT: AtomicU64 = AtomicU64::new(0); + /// Whether we run under Wine: its ntdll exports `wine_get_version` (as /// `victory_hle::modules::xmem` tells it). pub(crate) fn on_wine() -> bool { @@ -3438,6 +3523,7 @@ impl Shadow { card: None, window: false, changes_only: Default::default(), + wc: AtomicU8::new(0), mapped: false, own_side: false, place: None, @@ -3469,11 +3555,39 @@ impl Shadow { if self.place.is_some() { return; } + // Write-combined title memory, which the title's CPU does not read + // (`VICTORY_WC_NO_BACK`): what shaders write stays on the card. + if self.card.is_some() && wc_no_back() && self.len >= wc_no_back_min() && self.write_combined() { + self.written.store(true, Ordering::Relaxed); + WC_LEFT.fetch_add(len.min(self.left(address)), Ordering::Relaxed); + return; + } self.written.store(true, Ordering::Relaxed); let len = len.min(self.left(address)); 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. + fn write_combined(&self) -> bool { + match self.wc.load(Ordering::Relaxed) { + 1 => false, + 2 => true, + _ => { + let wc = is_write_combined(self.start, self.len); + self.wc.store(if wc { 2 } else { 1 }, Ordering::Relaxed); + if wc { + 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 (VICTORY_WC_NO_BACK)" + ); + } + wc + } + } + } + /// At submission, after the range's refresh: a submitted list's shaders /// write this range. Its bytes are kept to tell later what the GPU wrote: /// one snapshot per copy and submission, each byte taken once, when the @@ -7529,3 +7643,29 @@ mod plain_tests { assert_eq!(plain_side_bytes(), before); } } + +#[cfg(test)] +mod write_combined_tests { + use super::{is_write_combined, title_memory_write_combined, write_combined_freed}; + + /// 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). + #[test] + fn write_combined_regions() { + // Addresses of their own: other tests share the registry. + let base = 0x7f00_0000_0000usize; + title_memory_write_combined(base, 0x100_0000); + // (A commit inside it adds nothing.) + title_memory_write_combined(base + 0x1000, 0x1000); + 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"); + write_combined_freed(base + 0x10_0000, 0x1000); + assert!(!is_write_combined(base as u64, 0x1000), "part of it decommitted"); + let other = base + 0x1000_0000; + title_memory_write_combined(other, 0x10_0000); + write_combined_freed(other, 0); + assert!(!is_write_combined(other as u64, 0x1000), "the allocation released"); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index fbcf560..f050f1f 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -4284,6 +4284,7 @@ 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) { + crate::shadow::write_combined_freed(at, len); crate::memory::title_let_go(at, len); if len != 0 { let last = at.saturating_add(len).div_ceil(BLOCK); diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index f19b9db..8e2d255 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -191,6 +191,10 @@ pub extern "system" fn XMemVirtualAlloc( if !at.is_null() && constrained && kind & MEM_COMMIT == 0 && flags & ADDRESS_32BIT != 0 { LOW_RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner()).push((at as usize, size)); } + // Write-combined: memory the title's CPU writes and does not read. + if !at.is_null() && asked & 0x400 != 0 { + victory_gpu::title_memory_write_combined(at as usize, size); + } note_protection(asked, kind, flags, at as usize, size); at } ``` </details>
GreemSC commented 2026-11-29 20:40:48 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Slaktarn700/SlaktarnVI. Originally posted by GreemSC on 2026-11-29T20:40:48Z.


Follow-up: 60 → 45–48 ms/frame on the RX 7900 XT, by keeping two buffers' memory away from the copy and userptr paths

Same machine as above (RX 7900 XT, i7-12700K, 24 GB, Mesa 26.2.5 RADV, Proton-CachyOS). Two things changed since my first post, both for every number below: kernel 7.3.6 (CachyOS), and the GC 11.0.0 firmware from before AMD's revert (linux-firmware 9a7c283fa003, drm/amd#5711). Same 200 s scenario (opening cutscene, then the start of the prologue), release builds, median of the meter lines with ≥ 2,000 draws. Run-to-run noise with one setting is about ±2 ms (59.8 / 61.7 / 63.2).

Base for this post: 88abc53 + VICTORY_WC_NO_BACK (above), VICTORY_PORT_CONSTANTS=0 VICTORY_REFRESH_DIRTY=1: 59.8–61.8 ms.

What the diag log showed

One 20 MB buffer (allocation 0x1420000, length 0x1412200, a committed resource whose memory XMemAllocDefault takes from the host heap, so it is not write-watched) is rewritten whole by shaders every frame. Each frame it was copied whole twice by refreshes (≈ 41 MB, 4.6 ms), sent up again (20 of 48 MB), compared and fetched back (21 of the 22 MB "copying back"): the card received the bytes it had just written.

Results

Settings on top of the base ms/frame Crashes
VICTORY_OWN_WATCH=1 (that memory in a write-watched allocation of its own, kept above 4 GiB) 62.4 0 / 1
+ VICTORY_WC_COMMITTED=1 (shader writes to write-combined committed resources stay on the card), all such allocations 51.8 when it survived 3 / 4 (title code, early or mid-cutscene)
+ VICTORY_WC_COMMITTED_ONLY=0x1420000 (only that buffer) 51.8, 53.5 0 / 2
VICTORY_PORT_CONSTANTS=1 VICTORY_PORT_PRIVATE=1 VICTORY_PORT_OWNED=1 VICTORY_PORT_OWNED_ONLY=1 alone (port 1's heap is driver-owned memory mapped at the title's addresses, no userptr) 56.5, 61.3 0 / 2
both of the above together 45.4, 47.6 (21–22 real fps) 0 / 3 (one with captures)
VICTORY_PORT_OWNED_VRAM=1 (that heap in BAR VRAM instead of cached GTT) 2,500–4,500 (the CPU reads it) stopped

With everything on: copies 108 → 64 MB/frame, copy-back 22 → 0.8 MB/frame, the submitting thread's preparing 40 → 31 ms, card ~22 % busy. Picture: captures of the opening cutscene and prologue compared by eye with the base runs (faces, lighting, buildings, title card, credits): no difference found; driving and daytime exteriors not checked.

The code

7 patches on 88abc53 (git am applies them; release and diag build with --locked, no warnings): in the next comment (one git am-able file)

  1. VICTORY_WC_NO_BACK: the port posted above.
  2. VICTORY_OWN_WATCH: written here.
  3. VICTORY_WC_COMMITTED: written here.
  4. OWN_WATCH's allocations above the low 4 GiB, after trustno1-coder/VIctory-NVIDIA 7cd552bd64 (shreezzz). Without it, the blocks landed at 0x178d0000 / 0x7b700100 and the title hung or crashed.
  5. VICTORY_PORT_OWNED: port of cairodavila/SlaktarnVI gtabox de9be80 + 16b722e, plus the =2 bisection mode of 34b39f8. I added _ONLY (no other private memory imported as a host pointer) and _VRAM. The raw mmap goes through Wine's syscall-user-dispatch selector byte at TEB+0x340, checked only in wine-cachyos cd14106e, and the code gives up unless the byte reads 1.
  6. VICTORY_WC_COMMITTED_ONLY: written here.
  7. A provenance fix in a comment.

All of it is off by default.

Settings as run: VICTORY_PORT_CONSTANTS=1 VICTORY_PORT_PRIVATE=1 VICTORY_PORT_OWNED=1 VICTORY_PORT_OWNED_ONLY=1 VICTORY_OWN_WATCH=1 VICTORY_WC_COMMITTED=1 VICTORY_WC_COMMITTED_ONLY=0x1420000 VICTORY_REFRESH_DIRTY=1 VICTORY_WC_NO_BACK=1.

Tested: the runs above, all on this one machine. The exact series above (diag build of these 7 patches on 88abc53, all switches on): one run, 51.0 ms in diag (diag runs ~4 ms slower than release here), no crash, both mechanisms reported active in the log.

Not tested:

  • Windows (PORT_OWNED is Wine-only by design).
  • Other cards, and other Wine builds (the TEB+0x340 offset).
  • Long sessions.
  • The unit tests, which need Wine here.

0x1420000 is a size seen in this build of the title; another build may need another value (the diag log line memory for a committed resource in a watched allocation of its own lists the candidates).

Written with Claude (Opus and Fable); measured and checked on my PC.

<!-- greyfinch-sync:Slaktarn700/SlaktarnVI:comment:7262272102 --> Imported from [Slaktarn700/SlaktarnVI](https://github.com/Slaktarn700/SlaktarnVI/issues/19#issuecomment-7262272102). Originally posted by [GreemSC](https://github.com/GreemSC) on 2026-11-29T20:40:48Z. --- **Follow-up: 60 → 45–48 ms/frame on the RX 7900 XT, by keeping two buffers' memory away from the copy and userptr paths** Same machine as above (RX 7900 XT, i7-12700K, 24 GB, Mesa 26.2.5 RADV, Proton-CachyOS). Two things changed since my first post, both for every number below: kernel 7.3.6 (CachyOS), and the GC 11.0.0 firmware from before AMD's revert (linux-firmware 9a7c283fa003, drm/amd#5711). Same 200 s scenario (opening cutscene, then the start of the prologue), release builds, median of the meter lines with ≥ 2,000 draws. Run-to-run noise with one setting is about ±2 ms (59.8 / 61.7 / 63.2). Base for this post: `88abc53` + `VICTORY_WC_NO_BACK` (above), `VICTORY_PORT_CONSTANTS=0 VICTORY_REFRESH_DIRTY=1`: **59.8–61.8 ms**. ## What the diag log showed One 20 MB buffer (allocation `0x1420000`, length `0x1412200`, a committed resource whose memory `XMemAllocDefault` takes from the host heap, so it is not write-watched) is rewritten whole by shaders every frame. Each frame it was copied whole twice by refreshes (≈ 41 MB, 4.6 ms), sent up again (20 of 48 MB), compared and fetched back (21 of the 22 MB "copying back"): the card received the bytes it had just written. ## Results | Settings on top of the base | ms/frame | Crashes | |---|---|---| | `VICTORY_OWN_WATCH=1` (that memory in a write-watched allocation of its own, **kept above 4 GiB**) | 62.4 | 0 / 1 | | + `VICTORY_WC_COMMITTED=1` (shader writes to write-combined committed resources stay on the card), **all** such allocations | 51.8 when it survived | **3 / 4** (title code, early or mid-cutscene) | | + `VICTORY_WC_COMMITTED_ONLY=0x1420000` (only that buffer) | **51.8, 53.5** | 0 / 2 | | `VICTORY_PORT_CONSTANTS=1 VICTORY_PORT_PRIVATE=1 VICTORY_PORT_OWNED=1 VICTORY_PORT_OWNED_ONLY=1` alone (port 1's heap is driver-owned memory mapped at the title's addresses, no userptr) | 56.5, 61.3 | 0 / 2 | | **both of the above together** | **45.4, 47.6** (21–22 real fps) | 0 / 3 (one with captures) | | `VICTORY_PORT_OWNED_VRAM=1` (that heap in BAR VRAM instead of cached GTT) | 2,500–4,500 (the CPU reads it) | stopped | With everything on: copies 108 → 64 MB/frame, copy-back 22 → 0.8 MB/frame, the submitting thread's preparing 40 → 31 ms, card ~22 % busy. Picture: captures of the opening cutscene and prologue compared by eye with the base runs (faces, lighting, buildings, title card, credits): no difference found; driving and daytime exteriors not checked. ## The code 7 patches on `88abc53` (`git am` applies them; release and diag build with `--locked`, no warnings): in the next comment (one `git am`-able file) 1. `VICTORY_WC_NO_BACK`: the port posted above. 2. `VICTORY_OWN_WATCH`: written here. 3. `VICTORY_WC_COMMITTED`: written here. 4. OWN_WATCH's allocations above the low 4 GiB, after trustno1-coder/VIctory-NVIDIA `7cd552bd64` (shreezzz). Without it, the blocks landed at 0x178d0000 / 0x7b700100 and the title hung or crashed. 5. `VICTORY_PORT_OWNED`: port of cairodavila/SlaktarnVI `gtabox` `de9be80` + `16b722e`, plus the `=2` bisection mode of `34b39f8`. I added `_ONLY` (no other private memory imported as a host pointer) and `_VRAM`. The raw `mmap` goes through Wine's syscall-user-dispatch selector byte at `TEB+0x340`, checked only in wine-cachyos `cd14106e`, and the code gives up unless the byte reads 1. 6. `VICTORY_WC_COMMITTED_ONLY`: written here. 7. A provenance fix in a comment. All of it is off by default. Settings as run: `VICTORY_PORT_CONSTANTS=1 VICTORY_PORT_PRIVATE=1 VICTORY_PORT_OWNED=1 VICTORY_PORT_OWNED_ONLY=1 VICTORY_OWN_WATCH=1 VICTORY_WC_COMMITTED=1 VICTORY_WC_COMMITTED_ONLY=0x1420000 VICTORY_REFRESH_DIRTY=1 VICTORY_WC_NO_BACK=1`. **Tested:** the runs above, all on this one machine. The exact series above (diag build of these 7 patches on `88abc53`, all switches on): one run, 51.0 ms in diag (diag runs ~4 ms slower than release here), no crash, both mechanisms reported active in the log. **Not tested:** - Windows (PORT_OWNED is Wine-only by design). - Other cards, and other Wine builds (the `TEB+0x340` offset). - Long sessions. - The unit tests, which need Wine here. `0x1420000` is a size seen in this build of the title; another build may need another value (the diag log line `memory for a committed resource in a watched allocation of its own` lists the candidates). Written with Claude (Opus and Fable); measured and checked on my PC.
GreemSC commented 2026-11-29 20:40:56 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Slaktarn700/SlaktarnVI. Originally posted by GreemSC on 2026-11-29T20:40:56Z.


slaktarnvi-7900xt-series.patch (7 patches on 88abc53, git am)
From 82ccd140a107cf5f379a6ab2e530ee56b370bb03 Mon Sep 17 00:00:00 2001
From: GreemSC <[email protected]>
Date: Sun, 29 Nov 2026 14:43:40 +0100
Subject: [PATCH 1/7] shadow: shader writes into write-combined title memory
 stay on the card (VICTORY_WC_NO_BACK)

Port of the write-combined "no write-back" switch to this tree. Off by
default.

- xmem notes the regions the title asks for write-combined (the console's
  0x400 protection bit), forgotten when freed or decommitted
  (victory_gpu::title_memory_write_combined, watch::title_memory_freed).
- VICTORY_WC_NO_BACK=1: Shadow::gpu_writes declares nothing for a copy with
  a card side whose title memory lies whole in such a region: no snapshot,
  hash or compare pass, fetch or merge (relay/land) on its account; what
  shaders wrote stays on the card. In diagnostics builds the switch changes
  in a run (VICTORY_AB=<s>,VICTORY_WC_NO_BACK).
- VICTORY_WC_NO_BACK_MIN_KB (1024 unset, 0: all): only copies at least this
  large; upstream's cutscenes went near black with every copy (small results
  the title reads back came back stale).
- The frame line of card passes says how many MB a frame were left.

Not ported: VICTORY_WC_BAR (one mapped copy in card memory), reported to
break lighting. Renderer port 1's memory is in place and has no write-back
already; this is for the other copies in the card's memory.

Risks (shadow.rs, wc_no_back): the title's CPU reading what shaders wrote
there reads older bytes; a page the title writes goes up whole and takes
back what shaders wrote in the same 4 KiB page; another host copy of the
same bytes does not see shader writes.

Provenance (GPL-3.0-or-later, as this tree): commits 50c15a1 "Write-combined
title memory: no write-back of shader writes, one mapped copy (switches)"
and 2f81d0c "VICTORY_WC_NO_BACK_MIN_KB: only copies at least this large
leave shader writes on the card" by readmet3xt-lab
<[email protected]> (fxceless's tree, read
in trustno1-coder/VIctory-NVIDIA; the same change is
MJ26gaming/victory-rdna4-linux-rt-MJ26 461cb68 and
anoyarou/VIctory-RDNA4-linux 9489522; results in Marvisak/VIctory#3570).
Changed here: the default threshold (1024 KB), the registry leaves out
commits inside a region already noted, the A/B switch.

Test: the registry of write-combined regions (not run here: needs Wine).

Co-Authored-By: Claude Fable 5.2 <[email protected]>
(cherry picked from commit a2de0d2178d686e7cc2e8a71646aa461295bddca)
---
 crates/victory-gpu/src/host.rs         |   6 +-
 crates/victory-gpu/src/lib.rs          |   2 +
 crates/victory-gpu/src/shadow.rs       | 140 +++++++++++++++++++++++++
 crates/victory-gpu/src/watch.rs        |   1 +
 crates/victory-hle/src/modules/xmem.rs |   4 +
 5 files changed, 151 insertions(+), 2 deletions(-)

diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index 6ced0ae..48d7215 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -10306,10 +10306,12 @@ impl Meter {
             split_line(frames);
             {
                 let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames);
-                if passes + compares > 0.0 {
+                let wc_left = crate::shadow::WC_LEFT.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames;
+                if passes + compares + wc_left > 0.0 {
                     tracing::info!(
                         "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \
-                         ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes",
+                         ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes; \
+                         {wc_left:.1} MB declared written in write-combined memory left on the card (VICTORY_WC_NO_BACK)",
                         if rehash_runs() { "on" } else { "off" }
                     );
                 }
diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs
index d1979e0..5361108 100644
--- a/crates/victory-gpu/src/lib.rs
+++ b/crates/victory-gpu/src/lib.rs
@@ -157,6 +157,8 @@ pub fn frames_begun() -> u64 {
 #[cfg(windows)]
 pub use inplace::{title_memory_freeing, title_memory_quiesce, title_memory_section, title_memory_section_gone, title_memory_view};
 #[cfg(windows)]
+pub use shadow::title_memory_write_combined;
+#[cfg(windows)]
 pub use watch::{
     view_watch, kernel_writing, title_memory_allocated, title_memory_freed, title_memory_unguarded, title_placeholder_released, title_placeholder_reserved, title_memory_reading, title_memory_remapped,
     title_memory_remapping, title_memory_splitting, title_memory_unmapping, title_memory_written,
diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index 4e183b8..551a1df 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -105,6 +105,9 @@ pub(crate) struct Shadow {
     /// Of a copy with two sides: only the dwords the title changed go up,
     /// as with [`send_changed`] ([`by_address`]).
     changes_only: std::sync::atomic::AtomicBool,
+    /// Whether its title memory is write-combined ([`Shadow::write_combined`]):
+    /// 0 not known yet, 1 no, 2 yes.
+    wc: AtomicU8,
     /// A window in card memory the CPU maps ([`window_mapped_for`]).
     mapped: bool,
     /// An arena of title memory by address ([`by_address`] with `own`): the
@@ -2187,6 +2190,88 @@ fn land_echo() -> bool {
     crate::toggled!("VICTORY_LAND_ECHO")
 }
 
+/// 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<Vec<(u64, u64)>> = RwLock::new(Vec::new());
+
+/// 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
+/// console, the GDK's read-back memory is cacheable).
+pub fn title_memory_write_combined(at: usize, len: usize) {
+    if len == 0 {
+        return;
+    }
+    let (from, to) = (at as u64, at.saturating_add(len) as u64);
+    let mut all = WRITE_COMBINED.write().unwrap_or_else(|e| e.into_inner());
+    // (Commits inside a region noted when it was reserved add nothing.)
+    if !all.iter().any(|&(a, e)| a <= from && to <= e) {
+        all.push((from, to));
+    }
+}
+
+/// The title let go of `[at, at + len)` (`len` 0: of the allocation at `at`):
+/// write-combined 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);
+    let mut all = WRITE_COMBINED.write().unwrap_or_else(|e| e.into_inner());
+    all.retain(|&(from, to)| if len == 0 { from != at } else { to <= at || from >= end });
+}
+
+/// 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 {
+    let all = WRITE_COMBINED.read().unwrap_or_else(|e| e.into_inner());
+    all.iter().any(|&(from, to)| from <= start && start + len <= to)
+}
+
+/// Whether what shaders write into copies in the card's memory of
+/// write-combined title memory stays on the card and is not compared,
+/// fetched and merged into title memory (`VICTORY_WC_NO_BACK=1`; off by
+/// default: an experiment; an A/B switch in diagnostics builds). From
+/// fxceless/VIctory-NVIDIA 50c15a1.
+///
+/// The write-back of shader writes (`Shadow::gpu_writes`: hashes after
+/// sends, compare passes after the lists, fetches of the pieces that differ
+/// and their merge into title memory) keeps title memory the newest for the
+/// title's CPU. Memory the title asked for write-combined (protection
+/// 0x400) is what its CPU writes and the GPU reads.
+///
+/// What it risks, and why it may hold:
+/// - The title's CPU reading what shaders wrote there reads older bytes.
+///   Read back, write-combined memory is uncached on the console too, and
+///   results the CPU reads go to cacheable memory. Small copies are left
+///   out all the same ([`wc_no_back_min`]).
+/// - A page the CPU writes goes up whole from title memory (as before) and
+///   so takes back what shaders wrote in the same 4 KiB page since: mixed
+///   pages lose the shaders' bytes (with the write-back they were in title
+///   memory).
+/// - Another host copy of the same bytes (a texture placed there, a single
+///   view's copy) does not see what shaders wrote through title memory.
+/// - Changed while the title runs (`VICTORY_AB`): what shaders wrote while
+///   it was on is not in title memory when it goes off.
+fn wc_no_back() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    let on = *ON.get_or_init(|| std::env::var_os("VICTORY_WC_NO_BACK").is_some_and(|v| v == "1"));
+    #[cfg(feature = "diagnostics")]
+    let on = crate::ab::pick("VICTORY_WC_NO_BACK").unwrap_or(on);
+    on
+}
+
+/// The smallest copy whose shader writes [`wc_no_back`] leaves on the card,
+/// in bytes (`VICTORY_WC_NO_BACK_MIN_KB`, 1024 unset; 0: all). With every
+/// copy left, upstream's cutscenes went near black (fxceless/VIctory-NVIDIA
+/// 2f81d0c: small results the title reads back, such as exposure, came back
+/// stale; 3,245 write-combined copies there, median 4 KB, 82 of 1 MB or
+/// more) while most of the saving is in a few ranges of hundreds of MB.
+fn wc_no_back_min() -> u64 {
+    static MIN: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
+    *MIN.get_or_init(|| std::env::var("VICTORY_WC_NO_BACK_MIN_KB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(1024) << 10)
+}
+
+/// Bytes shaders were declared to write in write-combined copies and that
+/// were left on the card ([`wc_no_back`]), since the last frame-rate line.
+pub(crate) static WC_LEFT: AtomicU64 = AtomicU64::new(0);
+
 /// Whether we run under Wine: its ntdll exports `wine_get_version` (as
 /// `victory_hle::modules::xmem` tells it).
 pub(crate) fn on_wine() -> bool {
@@ -3438,6 +3523,7 @@ impl Shadow {
             card: None,
             window: false,
             changes_only: Default::default(),
+            wc: AtomicU8::new(0),
             mapped: false,
             own_side: false,
             place: None,
@@ -3469,11 +3555,39 @@ impl Shadow {
         if self.place.is_some() {
             return;
         }
+        // Write-combined title memory, which the title's CPU does not read
+        // (`VICTORY_WC_NO_BACK`): what shaders write stays on the card.
+        if self.card.is_some() && wc_no_back() && self.len >= wc_no_back_min() && self.write_combined() {
+            self.written.store(true, Ordering::Relaxed);
+            WC_LEFT.fetch_add(len.min(self.left(address)), Ordering::Relaxed);
+            return;
+        }
         self.written.store(true, Ordering::Relaxed);
         let len = len.min(self.left(address));
         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.
+    fn write_combined(&self) -> bool {
+        match self.wc.load(Ordering::Relaxed) {
+            1 => false,
+            2 => true,
+            _ => {
+                let wc = is_write_combined(self.start, self.len);
+                self.wc.store(if wc { 2 } else { 1 }, Ordering::Relaxed);
+                if wc {
+                    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 (VICTORY_WC_NO_BACK)"
+                    );
+                }
+                wc
+            }
+        }
+    }
+
     /// At submission, after the range's refresh: a submitted list's shaders
     /// write this range. Its bytes are kept to tell later what the GPU wrote:
     /// one snapshot per copy and submission, each byte taken once, when the
@@ -7472,3 +7586,29 @@ mod plain_tests {
         assert_eq!(plain_side_bytes(), before);
     }
 }
+
+#[cfg(test)]
+mod write_combined_tests {
+    use super::{is_write_combined, title_memory_write_combined, write_combined_freed};
+
+    /// 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).
+    #[test]
+    fn write_combined_regions() {
+        // Addresses of their own: other tests share the registry.
+        let base = 0x7f00_0000_0000usize;
+        title_memory_write_combined(base, 0x100_0000);
+        // (A commit inside it adds nothing.)
+        title_memory_write_combined(base + 0x1000, 0x1000);
+        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");
+        write_combined_freed(base + 0x10_0000, 0x1000);
+        assert!(!is_write_combined(base as u64, 0x1000), "part of it decommitted");
+        let other = base + 0x1000_0000;
+        title_memory_write_combined(other, 0x10_0000);
+        write_combined_freed(other, 0);
+        assert!(!is_write_combined(other as u64, 0x1000), "the allocation released");
+    }
+}
diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs
index fbcf560..f050f1f 100644
--- a/crates/victory-gpu/src/watch.rs
+++ b/crates/victory-gpu/src/watch.rs
@@ -4284,6 +4284,7 @@ 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) {
+    crate::shadow::write_combined_freed(at, len);
     crate::memory::title_let_go(at, len);
     if len != 0 {
         let last = at.saturating_add(len).div_ceil(BLOCK);
diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs
index f19b9db..8e2d255 100644
--- a/crates/victory-hle/src/modules/xmem.rs
+++ b/crates/victory-hle/src/modules/xmem.rs
@@ -191,6 +191,10 @@ pub extern "system" fn XMemVirtualAlloc(
     if !at.is_null() && constrained && kind & MEM_COMMIT == 0 && flags & ADDRESS_32BIT != 0 {
         LOW_RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner()).push((at as usize, size));
     }
+    // Write-combined: memory the title's CPU writes and does not read.
+    if !at.is_null() && asked & 0x400 != 0 {
+        victory_gpu::title_memory_write_combined(at as usize, size);
+    }
     note_protection(asked, kind, flags, at as usize, size);
     at
 }
-- 
2.56.0

From 544f969b0c99b35278e836c3317abe6cba751670 Mon Sep 17 00:00:00 2001
From: GreemSC <[email protected]>
Date: Sun, 29 Nov 2026 15:46:22 +0100
Subject: [PATCH 2/7] xmem: big blocks for the D3D runtime in write-watched
 memory (VICTORY_OWN_WATCH)

XMemAllocDefault took a committed resource's memory from the host heap, which
is not write-watched: its host copy was copied whole at every refresh and sent
to the card again whole (run n18: 0x7db20000+0x1412200, 1.9 refreshes and
40 MB a frame, 4.6 ms on the submitting thread, 20 of the 48 MB sent up).

With VICTORY_OWN_WATCH=1 a block of 1 MiB or more (VICTORY_OWN_WATCH_MIN_KB)
asked for with allocator 128 is an allocation of its own with MEM_WRITE_WATCH,
in whole 64 KiB pages; one of memory type 1 is told to the GPU side
(VICTORY_WC_COMMITTED). Off by default, read once.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
(cherry picked from commit 410a93b18e4e550ea5111d5dca24ffc08d011676)
---
 crates/victory-hle/src/modules/xmem.rs | 83 ++++++++++++++++++++++++++
 1 file changed, 83 insertions(+)

diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs
index 8e2d255..d90fab7 100644
--- a/crates/victory-hle/src/modules/xmem.rs
+++ b/crates/victory-hle/src/modules/xmem.rs
@@ -345,6 +345,9 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_
     let Some(layout) = layout(size, attributes) else {
         return std::ptr::null_mut();
     };
+    if let Some(user) = watched_block(size, layout.align(), attributes) {
+        return user;
+    }
     // shortcut: the host heap's addresses lie above 2^40, unlike the
     // console's; nothing seen builds ray-tracing structures in this memory
     // (the title uses its GPU heap). Sub-allocate from a
@@ -366,6 +369,80 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_
     }
 }
 
+/// In the second word of a block's header, where the host heap's blocks have
+/// their alignment: a block of [`watched_block`].
+const WATCHED_BLOCK: usize = 1 << (usize::BITS - 1);
+
+/// The smallest block [`XMemAllocDefault`] gives the D3D runtime out of
+/// memory the kernel watches, in bytes (`VICTORY_OWN_WATCH=1`; off by
+/// default; `VICTORY_OWN_WATCH_MIN_KB`, 1024 unset). Read once: memory made
+/// before stays what it is.
+///
+/// A committed resource's memory comes from here through the title's
+/// allocation hook, out of the host heap, which is not write-watched: the
+/// GPU side copies such a buffer whole at every refresh and sends all of it
+/// to the card again (run n18: one buffer of 20 MB that shaders write, 40 MB
+/// and 4.6 ms a frame copied on the submitting thread, 20 of the 48 MB sent
+/// up). Watched like the title's other memory, only the pages written since
+/// the last copy are taken.
+fn own_watch_min() -> Option<usize> {
+    static MIN: LazyLock<Option<usize>> = LazyLock::new(|| {
+        let kb = || std::env::var("VICTORY_OWN_WATCH_MIN_KB").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(1024);
+        std::env::var_os("VICTORY_OWN_WATCH").is_some_and(|v| v == "1").then(|| kb().saturating_mul(1024))
+    });
+    *MIN
+}
+
+/// [`XMemAllocDefault`]'s block of `size` bytes for the D3D runtime
+/// (allocator 128, `victory_gpu`'s committed resources) in an allocation of
+/// its own that the kernel watches, if [`own_watch_min`] asks for it; `None`:
+/// the host heap as before. Whole 64 KiB pages, which the GPU side asks
+/// about. A GPU-only heap's (memory type 1, write-combined) is told to the
+/// GPU side (`VICTORY_WC_COMMITTED`).
+fn watched_block(size: usize, align: usize, attributes: u64) -> Option<*mut c_void> {
+    const D3D: u64 = 128;
+    const WRITE_COMBINED: u64 = 1;
+    let min = own_watch_min()?;
+    if size < min {
+        return None;
+    }
+    if attributes >> 16 & 0xff != D3D || align > PAGE || size & WATCHED_BLOCK != 0 {
+        // (Said a few times: what else is this big, if the resources' own
+        // do not come by here as expected.)
+        static LEFT: AtomicU64 = AtomicU64::new(0);
+        if LEFT.fetch_add(1, Ordering::Relaxed) < 8 {
+            tracing::info!("VICTORY_OWN_WATCH: a block of {size:#x} bytes left to the host heap, attributes {attributes:#x}, alignment {align:#x}");
+        }
+        return None;
+    }
+    let len = size.checked_add(align)?.checked_next_multiple_of(PAGE)?;
+    // SAFETY: a plain allocation.
+    let base = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }.cast::<u8>();
+    if base.is_null() {
+        return None;
+    }
+    // SAFETY: the allocation holds the alignment (at least the header) and
+    // then `size` bytes.
+    let user = unsafe {
+        let user = base.add(align);
+        user.sub(HEADER).cast::<[usize; 2]>().write([base as usize, size | WATCHED_BLOCK]);
+        user
+    };
+    victory_gpu::title_memory_allocated(user as usize, size);
+    let write_combined = attributes >> 29 & 0xf == WRITE_COMBINED;
+    if write_combined {
+        victory_gpu::title_memory_committed(user as usize, size);
+    }
+    static MADE: AtomicU64 = AtomicU64::new(0);
+    let made = MADE.fetch_add(1, Ordering::Relaxed) + 1;
+    if made <= 32 || made.is_power_of_two() {
+        tracing::info!(
+            "memory for a committed resource in a watched allocation of its own (VICTORY_OWN_WATCH): {user:p}+{size:#x}, write-combined on the console: {write_combined}; {made} so far"
+        );
+    }
+    Some(user.cast())
+}
+
 /// Frees what [`XMemAllocDefault`] returned, given the same attributes.
 pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) {
     if address.is_null() {
@@ -380,6 +457,12 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) {
         }
         let user = address.cast::<u8>();
         let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read();
+        if align & WATCHED_BLOCK != 0 {
+            // ([`watched_block`]: the allocation's base in place of the size.)
+            victory_gpu::title_memory_committed_freed(user as usize);
+            VirtualFree(size as *mut c_void, 0, MEM_RELEASE);
+            return;
+        }
         dealloc(
             user.sub(align),
             Layout::from_size_align_unchecked(size, align),
-- 
2.56.0

From bfdb40ad5aadc161b08b3e4439a54af6c626426e Mon Sep 17 00:00:00 2001
From: GreemSC <[email protected]>
Date: Sun, 29 Nov 2026 15:46:22 +0100
Subject: [PATCH 3/7] shadow: shader writes into committed resources of
 GPU-only heaps stay on the card (VICTORY_WC_COMMITTED)

With VICTORY_WC_NO_BACK=1: a copy in the card's memory whose title memory the
runtime made for a committed resource of a GPU-only heap (told by
title_memory_committed, memory type write-combined in the allocation
attributes) no longer declares its shader writes, as copies of memory the
title asked for write-combined already do. Only while the memory is known to
be watched by the kernel (VICTORY_OWN_WATCH): a refresh of unwatched memory
copies it whole and would send it over what the shaders wrote.

Run n18 (world, 65 ms a frame): one such buffer of 20 MB is written whole by
shaders every frame; 21 of the 22 MB a frame copied back are its pieces.

Off by default; an A/B switch in diagnostics builds.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
(cherry picked from commit cf6c9da5c30a9364730037895c29d5ece2b68a82)
---
 crates/victory-gpu/src/lib.rs    |  2 +-
 crates/victory-gpu/src/shadow.rs | 83 +++++++++++++++++++++++++++++++-
 2 files changed, 82 insertions(+), 3 deletions(-)

diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs
index 5361108..5c8e2a5 100644
--- a/crates/victory-gpu/src/lib.rs
+++ b/crates/victory-gpu/src/lib.rs
@@ -157,7 +157,7 @@ pub fn frames_begun() -> u64 {
 #[cfg(windows)]
 pub use inplace::{title_memory_freeing, title_memory_quiesce, title_memory_section, title_memory_section_gone, title_memory_view};
 #[cfg(windows)]
-pub use shadow::title_memory_write_combined;
+pub use shadow::{title_memory_committed, title_memory_committed_freed, title_memory_write_combined};
 #[cfg(windows)]
 pub use watch::{
     view_watch, kernel_writing, title_memory_allocated, title_memory_freed, title_memory_unguarded, title_placeholder_released, title_placeholder_reserved, title_memory_reading, title_memory_remapped,
diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index 551a1df..efffc65 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -106,7 +106,8 @@ pub(crate) struct Shadow {
     /// as with [`send_changed`] ([`by_address`]).
     changes_only: std::sync::atomic::AtomicBool,
     /// Whether its title memory is write-combined ([`Shadow::write_combined`]):
-    /// 0 not known yet, 1 no, 2 yes.
+    /// 0 not known yet, 1 no, 2 yes, 3 a committed resource's
+    /// ([`title_memory_committed`]).
     wc: AtomicU8,
     /// A window in card memory the CPU maps ([`window_mapped_for`]).
     mapped: bool,
@@ -2224,6 +2225,64 @@ fn is_write_combined(start: u64, len: u64) -> bool {
     all.iter().any(|&(from, to)| from <= start && start + len <= to)
 }
 
+/// Memory the runtime gave a committed resource of a GPU-only heap, write
+/// watched, as `[start, end)` ([`title_memory_committed`]).
+static COMMITTED: RwLock<Vec<(u64, u64)>> = RwLock::new(Vec::new());
+
+/// The runtime made `[at, at + len)` for a committed resource of a GPU-only
+/// heap (the allocation attributes' memory type says write-combined,
+/// `crate::resource`'s `resource_attributes`), in memory the kernel watches
+/// (`VICTORY_OWN_WATCH`): see [`wc_committed`].
+pub fn title_memory_committed(at: usize, len: usize) {
+    if len != 0 {
+        COMMITTED.write().unwrap_or_else(|e| e.into_inner()).push((at as u64, at.saturating_add(len) as u64));
+    }
+}
+
+/// The memory [`title_memory_committed`] told of at `at` is let go.
+pub fn title_memory_committed_freed(at: usize) {
+    COMMITTED.write().unwrap_or_else(|e| e.into_inner()).retain(|&(from, _)| from != at as u64);
+}
+
+/// Whether all of `[start, start + len)` lies in one such allocation.
+fn is_committed(start: u64, len: u64) -> bool {
+    let all = COMMITTED.read().unwrap_or_else(|e| e.into_inner());
+    all.iter().any(|&(from, to)| from <= start && start + len <= to)
+}
+
+/// Whether [`wc_no_back`] also leaves on the card what shaders write into
+/// copies of committed resources of GPU-only heaps
+/// (`VICTORY_WC_COMMITTED=1`, with `VICTORY_WC_NO_BACK=1` and
+/// `VICTORY_OWN_WATCH=1`; off by default: an experiment; an A/B switch in
+/// diagnostics builds).
+///
+/// Why: such a resource's memory came from the host heap, which nothing
+/// watches. In the world one buffer of 20 MB there (run n18) is written whole
+/// by shaders every frame: 21 MB a frame compared, fetched and merged into
+/// title memory (all but 1 MB of the frame line's "copying back"), then
+/// copied whole from title memory at every refresh (40 MB, 4.6 ms a frame)
+/// and sent up again (20 of 48 MB), the very bytes the card held. On the
+/// console that memory is write-combined (the type the runtime asks the
+/// title's allocator for: the plausible one, not known), which the title's
+/// CPU does not read.
+///
+/// Only for memory the kernel watches (`VICTORY_OWN_WATCH`, the runtime's
+/// `XMemAllocDefault`): a refresh of memory that is not watched copies title
+/// memory whole and sends it over what the shaders wrote
+/// ([`Shadow::committed_left`]).
+///
+/// What it risks is what [`wc_no_back`] risks. Changed while the title runs:
+/// when it goes on, the last landings are sent up once more, over what
+/// shaders wrote since; when it goes off, title memory lacks what was written
+/// meanwhile until shaders write it again.
+fn wc_committed() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    let on = *ON.get_or_init(|| std::env::var_os("VICTORY_WC_COMMITTED").is_some_and(|v| v == "1"));
+    #[cfg(feature = "diagnostics")]
+    let on = crate::ab::pick("VICTORY_WC_COMMITTED").unwrap_or(on);
+    on
+}
+
 /// Whether what shaders write into copies in the card's memory of
 /// write-combined title memory stays on the card and is not compared,
 /// fetched and merged into title memory (`VICTORY_WC_NO_BACK=1`; off by
@@ -3568,13 +3627,25 @@ impl Shadow {
     }
 
     /// Whether all of the copy's title memory was asked for write-combined
-    /// ([`title_memory_write_combined`]); found once.
+    /// ([`title_memory_write_combined`]), or is a committed resource's whose
+    /// shader writes stay on the card now ([`Shadow::committed_left`]); which
+    /// memory it is is found once.
     fn write_combined(&self) -> bool {
         match self.wc.load(Ordering::Relaxed) {
             1 => false,
             2 => true,
+            3 => self.committed_left(),
             _ => {
                 let wc = is_write_combined(self.start, self.len);
+                if !wc && is_committed(self.start, self.len) {
+                    self.wc.store(3, Ordering::Relaxed);
+                    tracing::info!(
+                        start = format_args!("{:#x}", self.start),
+                        len = format_args!("{:#x}", self.len),
+                        "a committed resource of a GPU-only heap in watched memory: what shaders write in its copy is not copied back with VICTORY_WC_COMMITTED"
+                    );
+                    return self.committed_left();
+                }
                 self.wc.store(if wc { 2 } else { 1 }, Ordering::Relaxed);
                 if wc {
                     tracing::info!(
@@ -3588,6 +3659,14 @@ impl Shadow {
         }
     }
 
+    /// Of a copy of a committed resource's memory ([`title_memory_committed`]):
+    /// whether what shaders write stays on the card now ([`wc_committed`]).
+    /// Not while the memory is not known to be watched: a refresh would copy
+    /// it whole, and send it over what the shaders wrote.
+    fn committed_left(&self) -> bool {
+        wc_committed() && self.watched.load(Ordering::Relaxed) == 1
+    }
+
     /// At submission, after the range's refresh: a submitted list's shaders
     /// write this range. Its bytes are kept to tell later what the GPU wrote:
     /// one snapshot per copy and submission, each byte taken once, when the
-- 
2.56.0

From ebc908f976e9c03d0d9893022fc5e3ba145de2e9 Mon Sep 17 00:00:00 2001
From: GreemSC <[email protected]>
Date: Sun, 29 Nov 2026 20:21:27 +0100
Subject: [PATCH 4/7] xmem: OWN_WATCH blocks above the low 4 GiB (after
 trustno1-coder/VIctory-NVIDIA 7cd552bd64 by shreezzz)

A plain VirtualAlloc took addresses under 4 GiB for the watched blocks
(n19, n20: 0x178d0000, 0x7b700100), which the title's 32-bit requests and
renderer port 1's heap need: the title hung or crashed. The reservation is
now bounded with VirtualAlloc2 and address_range(0), as
trustno1-coder/VIctory-NVIDIA 7cd552bd64 (shreezzz) bounds its own.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
(cherry picked from commit 17273da6d26d672f0e8bf9e0061371ed51efe6b9)
---
 crates/victory-hle/src/modules/xmem.rs | 19 +++++++++++++++++--
 1 file changed, 17 insertions(+), 2 deletions(-)

diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs
index d90fab7..c15ecfc 100644
--- a/crates/victory-hle/src/modules/xmem.rs
+++ b/crates/victory-hle/src/modules/xmem.rs
@@ -416,8 +416,23 @@ fn watched_block(size: usize, align: usize, attributes: u64) -> Option<*mut c_vo
         return None;
     }
     let len = size.checked_add(align)?.checked_next_multiple_of(PAGE)?;
-    // SAFETY: a plain allocation.
-    let base = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }.cast::<u8>();
+    // Above the low 4 GiB, which the title's 32-bit requests (and renderer
+    // port 1's heap) need: a plain VirtualAlloc took addresses there (n19,
+    // n20: 0x178d0000, 0x7b700100) and the title hung or crashed.
+    // trustno1-coder/VIctory-NVIDIA 7cd552bd64 (shreezzz) bounds its watched
+    // reservations the same way.
+    let (lowest, highest) = address_range(0);
+    let mut requirements =
+        MEM_ADDRESS_REQUIREMENTS { LowestStartingAddress: lowest as *mut c_void, HighestEndingAddress: highest as *mut c_void, Alignment: 0 };
+    let mut parameter = MEM_EXTENDED_PARAMETER::default();
+    parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64;
+    parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
+    // SAFETY: the host chooses an address within `requirements`, which
+    // outlives the call through `parameter`.
+    let base = unsafe {
+        VirtualAlloc2(GetCurrentProcess(), std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE, &mut parameter, 1)
+    }
+    .cast::<u8>();
     if base.is_null() {
         return None;
     }
-- 
2.56.0

From 9f1843f1e91861a930d8fc1696350c0c34181db7 Mon Sep 17 00:00:00 2001
From: GreemSC <[email protected]>
Date: Sun, 29 Nov 2026 20:36:14 +0100
Subject: [PATCH 5/7] port 1: VICTORY_PORT_OWNED backs the 32-bit graphics heap
 with a driver heap mapped at the title's addresses (no userptr)

Port of cairodavila/SlaktarnVI, branch gtabox, commits de9be80 ("port 1:
VICTORY_PORT_OWNED=1 backs the 32-bit graphics heap with a driver heap
mapped at the title's addresses (no userptr)") and 16b722e ("owned: retire
the driver heap only when the whole of it is given up"), and the one change
of code in 34b39f8 (the switch value 2; the rest of it reformats three
files). Author: Cairo (cairodavila), GPL-3.0-or-later, as this tree.

When xmem makes the 32-bit graphics heap one private allocation
(VICTORY_PORT_PRIVATE=1), a D3D12 heap of the driver's own is made and its
CPU mapping (the render node at the BO's offset) is mapped over the title's
addresses with a raw Linux mmap(MAP_FIXED), issued from this PE code with
Wine's syscall-user-dispatch selector byte (TEB+0x340) cleared around the
syscall. Port 1 places its buffers in that heap; nothing is imported by
host pointer for it, so amdgpu has no userptr to walk per submission.
Off by default.

- VICTORY_PORT_OWNED=1 (with VICTORY_PORT_CONSTANTS=1, VICTORY_PORT_PRIVATE=1).
- VICTORY_PORT_OWNED=2: upstream's bisection: driver memory, nothing placed
  in it (the card gets copies).
- VICTORY_PORT_OWNED_VRAM=1 (new): the heap in the card's memory,
  write-combined, seen through the BAR, not in cached system memory: the
  card works at home, CPU reads of the heap are very slow.
- VICTORY_PORT_OWNED_ONLY=1 (new): no other private memory opened in place
  (run n16 had three more stretches, 34 MB, still host-pointer imports).

Other changes from upstream: only under Wine; what a raw call returns is
bounded (a signal between the selector's write and the syscall makes it a
Windows call); the driver's mapping must hold the whole heap; refused with
VICTORY_SAFE_COPY=0 (NtWriteVirtualMemory goes through wineserver, which
does not reach a VM_PFNMAP mapping); mod owned stays under cfg(windows).
The heap is not write-watched (xmem commits it without MEM_WRITE_WATCH and
tells it unguarded), which the kernel's scan would skip silently there.

Not run: built only.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
(cherry picked from commit a7c44a6f67fd1883064c45ad07e70666765063ac)
---
 crates/victory-gpu/src/inplace.rs      |   1 +
 crates/victory-gpu/src/lib.rs          |   4 +
 crates/victory-gpu/src/owned.rs        | 327 +++++++++++++++++++++++++
 crates/victory-gpu/src/port.rs         |  19 +-
 crates/victory-hle/src/modules/xmem.rs |   2 +
 5 files changed, 350 insertions(+), 3 deletions(-)
 create mode 100644 crates/victory-gpu/src/owned.rs

diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs
index 10844e8..a9f1227 100644
--- a/crates/victory-gpu/src/inplace.rs
+++ b/crates/victory-gpu/src/inplace.rs
@@ -191,6 +191,7 @@ pub(crate) fn gone(window: bool, bytes: u64) {
 pub fn title_memory_freeing(at: usize, len: usize) {
     // Renderer port 1's regions there: no longer what the title shows.
     crate::port::forget(at, len);
+    crate::owned::freeing(at, len);
     if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 {
         return;
     }
diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs
index 5c8e2a5..b4aaf7a 100644
--- a/crates/victory-gpu/src/lib.rs
+++ b/crates/victory-gpu/src/lib.rs
@@ -57,6 +57,8 @@ mod indirect;
 #[cfg(windows)]
 mod inplace;
 #[cfg(windows)]
+mod owned;
+#[cfg(windows)]
 mod port;
 #[cfg(windows)]
 mod port_cbv;
@@ -155,6 +157,8 @@ pub fn frames_begun() -> u64 {
     frame::current()
 }
 #[cfg(windows)]
+pub use owned::title_memory_owned;
+#[cfg(windows)]
 pub use inplace::{title_memory_freeing, title_memory_quiesce, title_memory_section, title_memory_section_gone, title_memory_view};
 #[cfg(windows)]
 pub use shadow::{title_memory_committed, title_memory_committed_freed, title_memory_write_combined};
diff --git a/crates/victory-gpu/src/owned.rs b/crates/victory-gpu/src/owned.rs
new file mode 100644
index 0000000..b90dc41
--- /dev/null
+++ b/crates/victory-gpu/src/owned.rs
@@ -0,0 +1,327 @@
+//! Renderer port 1 on memory the card's driver owns (`VICTORY_PORT_OWNED=1`,
+//! Linux only, with `VICTORY_PORT_CONSTANTS=1` and `VICTORY_PORT_PRIVATE=1`).
+//!
+//! Port 1 opens the title's 32-bit graphics heap where it is
+//! (`OpenExistingHeapFromAddress1`). Under vkd3d-proton on RADV that is a
+//! host-pointer import, an amdgpu userptr: the kernel walks and compares all
+//! ~47,000 pages of it on every submission (~23 ms of GPU wait a frame here).
+//! Here instead, when `xmem` makes that heap (fresh, before the title writes
+//! it), a heap of the driver's own (custom, write-back, L0: cached GTT) is
+//! made and its CPU mapping (an mmap of the render node at the BO's fake
+//! offset) is mapped a second time over the title's addresses with a raw
+//! Linux `mmap(MAP_FIXED)`. The title and the card then share the same
+//! pages, and the kernel has nothing to check per submission. Wine still
+//! believes it is private memory; protecting and freeing it work as before.
+//!
+//! What a mapping of the render node cannot do: be the target of O_DIRECT
+//! reads or of another process's `process_vm_readv` (no struct pages).
+//!
+//! From cairodavila/SlaktarnVI, branch `gtabox` (Cairo, GPL-3.0-or-later):
+//! de9be80 and 16b722e, and the switch value `2` of 34b39f8. Added here:
+//! the Wine check, the bounds on what a raw call returns, the check that the
+//! driver's mapping holds the whole heap, `VICTORY_PORT_OWNED_VRAM` and
+//! `VICTORY_PORT_OWNED_ONLY`.
+//!
+//! What was looked at for that mapping (`VM_PFNMAP | VM_IO`), wine-cachyos
+//! cd14106e and Linux 7.3:
+//! - write watching: the kernel's `PAGEMAP_SCAN` skips such a mapping without
+//!   an error, so it would read as never written. The heap is not watched:
+//!   `xmem` commits it without `MEM_WRITE_WATCH` and tells
+//!   `crate::watch::title_memory_unguarded`, whose blocks count as written at
+//!   every asking; the buffers placed in it are not copied at all.
+//! - O_DIRECT: Wine opens no file with it (`FILE_FLAG_NO_BUFFERING` is a
+//!   buffered read there), so the title's reads into the heap work.
+//! - the kernel's copies of `VICTORY_SAFE_COPY=0`: `ReadProcessMemory` on our
+//!   own process is a `memmove` inside Wine, but `NtWriteVirtualMemory` goes
+//!   through wineserver (`process_vm_writev`, then ptrace), which does not
+//!   reach driver memory: with that setting the heap is left as it is
+//!   ([`title_memory_owned`]). Another process (a debugger) does not read it.
+//! - not to be mixed with what imports title memory in the heap by host
+//!   pointer (`VICTORY_INPLACE`) or collapses it from outside
+//!   (`VICTORY_PORT_HUGE`): neither works on a driver mapping.
+
+use std::arch::asm;
+use std::collections::BTreeMap;
+use std::ffi::c_void;
+use std::sync::Mutex;
+
+use windows::Win32::Graphics::Direct3D12::*;
+use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC};
+
+/// `VICTORY_PORT_OWNED`: `1` or `2` puts port 1's private heap in driver
+/// memory (off by default; under Wine only: the raw call is Linux's).
+pub(crate) fn on() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    *ON.get_or_init(|| crate::port::on() && std::env::var("VICTORY_PORT_OWNED").is_ok_and(|v| matches!(v.trim(), "1" | "2")) && crate::shadow::on_wine())
+}
+
+/// `VICTORY_PORT_OWNED=2`: the heap is driver memory, but port 1 places
+/// nothing in it (copies as without the port): tells a CPU-side problem of
+/// driver memory from a card-side one.
+pub(crate) fn hands_off() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    *ON.get_or_init(|| std::env::var("VICTORY_PORT_OWNED").is_ok_and(|v| v.trim() == "2"))
+}
+
+/// `VICTORY_PORT_OWNED_VRAM=1` (with `VICTORY_PORT_OWNED`; off by default):
+/// the driver heap is made in the card's own memory, write-combined and seen
+/// by the CPU through the resizable BAR (custom, write-combine, L1: vkd3d's
+/// GPU upload heap), not in cached system memory. The card then reads and
+/// writes the heap at home, not over PCIe (a 20 MB buffer of the title in
+/// system memory took the card from 30 to 50 % busy, run n28); CPU writes
+/// stay quick (write-combined), but every CPU read of it (the title's, and
+/// the fills and copies port 1's line counts) is uncached and very slow.
+/// Refused by the host without a resizable BAR: the heap is then opened in
+/// place as before.
+fn vram() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    *ON.get_or_init(|| std::env::var("VICTORY_PORT_OWNED_VRAM").is_ok_and(|v| v.trim() == "1"))
+}
+
+/// `VICTORY_PORT_OWNED_ONLY=1` (off by default), while a heap is driver-owned:
+/// port 1 opens no other private memory in place. Without it the title's
+/// other buffers under 4 GiB (run n16: three stretches, 34 MB, one a 21 MB
+/// buffer shaders write) are still opened where they are, host-pointer
+/// imports the kernel walks on every submission as it did the heap.
+pub(crate) fn only() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    *ON.get_or_init(|| std::env::var("VICTORY_PORT_OWNED_ONLY").is_ok_and(|v| v.trim() == "1")) && !OWNED.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
+}
+
+/// Driver heaps over title memory: base -> (bytes, heap, the buffer whose Map keeps vkd3d's mapping).
+struct Owned {
+    bytes: usize,
+    heap: ID3D12Heap,
+    _mapped: ID3D12Resource,
+}
+// SAFETY: D3D12 objects are free-threaded.
+unsafe impl Send for Owned {}
+
+static OWNED: Mutex<BTreeMap<usize, Owned>> = Mutex::new(BTreeMap::new());
+/// Heaps the title has given up: kept, the card may still name them.
+/// shortcut: never released (one per time the title remakes its heap, 185 MB each; it makes it once).
+static RETIRED: Mutex<Vec<Owned>> = Mutex::new(Vec::new());
+
+/// The driver heap holding `[at, end)`, as (its start, heap).
+pub(crate) fn heap_for(at: u64, end: u64) -> Option<(u64, u64, ID3D12Heap)> {
+    let owned = OWNED.lock().unwrap_or_else(|e| e.into_inner());
+    let (&base, o) = owned.range(..=at as usize).next_back()?;
+    (end as usize <= base + o.bytes).then(|| (base as u64, (base + o.bytes) as u64, o.heap.clone()))
+}
+
+/// A buffer over `[offset, offset + size)` of a driver heap (port 1's place,
+/// minus the cross-adapter flag only opened heaps need).
+pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result<ID3D12Resource> {
+    let mut placed: Option<ID3D12Resource> = None;
+    // SAFETY: plain creation in a live heap.
+    unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size as usize), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? };
+    placed.ok_or_else(windows::core::Error::empty)
+}
+
+fn buffer_desc(bytes: usize) -> D3D12_RESOURCE_DESC {
+    D3D12_RESOURCE_DESC {
+        Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+        Alignment: 0,
+        Width: bytes as u64,
+        Height: 1,
+        DepthOrArraySize: 1,
+        MipLevels: 1,
+        Format: DXGI_FORMAT_UNKNOWN,
+        SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+        Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+        Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
+    }
+}
+
+/// The title gives `[at, at + len)` up: a heap over it is retired.
+pub(crate) fn freeing(at: usize, len: usize) {
+    let mut owned = OWNED.lock().unwrap_or_else(|e| e.into_inner());
+    // Only the whole heap (xmem's deactivate): mappings into it come and go (give_back,
+    // remaps) while the memory stays, and port 1 reopens its regions from here.
+    let gone: Vec<usize> = owned.range(at..at + len).filter(|(b, o)| **b + o.bytes <= at + len).map(|(b, _)| *b).collect();
+    let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner());
+    for b in gone {
+        if let Some(o) = owned.remove(&b) {
+            tracing::info!(base = format_args!("{b:#x}"), bytes = o.bytes, "renderer port 1: driver-owned heap given up by the title (kept for the card)");
+            retired.push(o);
+        }
+    }
+}
+
+/// A raw Linux syscall from this PE code. Wine traps `syscall` outside its
+/// own code (syscall user dispatch) unless the thread's selector byte,
+/// TEB+0x340 (`amd64_thread_data.syscall_dispatch`), is ALLOW (0); it is
+/// BLOCK (1) while PE code runs. `None` if the byte is not what Wine puts there.
+fn linux(nr: usize, a: [usize; 6]) -> Option<isize> {
+    // SAFETY: gs:[0x30] is the TEB on Windows x64 and under Wine; 0x340 is
+    // inside it (Wine's per-thread data), only toggled around one syscall.
+    unsafe {
+        let teb: *mut u8;
+        asm!("mov {}, gs:[0x30]", out(reg) teb, options(nostack, readonly, preserves_flags));
+        let sel = teb.add(0x340);
+        if sel.read_volatile() != 1 {
+            return None;
+        }
+        sel.write_volatile(0);
+        let ret: isize;
+        asm!("syscall", inlateout("rax") nr as isize => ret, in("rdi") a[0], in("rsi") a[1], in("rdx") a[2],
+            in("r10") a[3], in("r8") a[4], in("r9") a[5], lateout("rcx") _, lateout("r11") _, options(nostack));
+        sel.write_volatile(1);
+        Some(ret)
+    }
+}
+
+const SYS_READ: usize = 0;
+const SYS_CLOSE: usize = 3;
+const SYS_MMAP: usize = 9;
+const SYS_MUNMAP: usize = 11;
+const SYS_READLINK: usize = 89;
+const SYS_OPENAT: usize = 257;
+const PROT_RW: usize = 3;
+const MAP_SHARED: usize = 0x01;
+const MAP_FIXED: usize = 0x10;
+
+fn failed(r: isize) -> bool {
+    (-4095..0).contains(&r)
+}
+
+fn read_file(path: &str) -> Option<String> {
+    let c = format!("{path}\0");
+    let fd = linux(SYS_OPENAT, [-100isize as usize, c.as_ptr() as usize, 0, 0, 0, 0]).filter(|r| *r >= 0)?;
+    let mut out = Vec::new();
+    let mut buf = vec![0u8; 1 << 16];
+    // (`n` within the buffer: a signal between the selector's write and the call makes it a Windows call, with any answer)
+    while let Some(n) = linux(SYS_READ, [fd as usize, buf.as_mut_ptr() as usize, buf.len(), 0, 0, 0]).filter(|n| *n > 0 && *n as usize <= buf.len()) {
+        out.extend_from_slice(&buf[..n as usize]);
+    }
+    linux(SYS_CLOSE, [fd as usize, 0, 0, 0, 0, 0]);
+    Some(String::from_utf8_lossy(&out).into_owned())
+}
+
+/// The Linux mapping holding `at`: (its start, end, file offset, path).
+fn mapping_of(at: usize) -> Option<(usize, usize, usize, String)> {
+    read_file("/proc/self/maps")?.lines().find_map(|line| {
+        let f: Vec<&str> = line.split_whitespace().collect();
+        let (s, e) = f.first()?.split_once('-')?;
+        let (s, e) = (usize::from_str_radix(s, 16).ok()?, usize::from_str_radix(e, 16).ok()?);
+        (s <= at && at < e).then(|| Some((s, e, usize::from_str_radix(f.get(2)?, 16).ok()?, f.get(5).unwrap_or(&"").to_string())))?
+    })
+}
+
+/// An fd of `path` (the render node) that the BO's fake `offset` belongs to:
+/// DRM checks the offset against the open file it was made for.
+fn render_fd(path: &str, offset: usize) -> Option<usize> {
+    let mut buf = [0u8; 256];
+    (0..65536usize).find(|fd| {
+        let link = format!("/proc/self/fd/{fd}\0");
+        let n = linux(SYS_READLINK, [link.as_ptr() as usize, buf.as_mut_ptr() as usize, buf.len(), 0, 0, 0]).unwrap_or(-1);
+        if n <= 0 || n as usize > buf.len() || &buf[..n as usize] != path.as_bytes() {
+            return false;
+        }
+        let m = linux(SYS_MMAP, [0, 4096, 1, MAP_SHARED, *fd, offset]).unwrap_or(-1);
+        if failed(m) {
+            return false;
+        }
+        linux(SYS_MUNMAP, [m as usize, 4096, 0, 0, 0, 0]);
+        true
+    })
+}
+
+/// `xmem` made `[base, base + bytes)` (fresh private memory, before the title
+/// writes it) port 1's heap: back it with driver memory. False leaves it as
+/// it is (port 1 then opens it in place as before).
+pub fn title_memory_owned(base: usize, bytes: usize) -> bool {
+    if !on() {
+        return false;
+    }
+    if !crate::safecopy::on() {
+        tracing::warn!(base = format_args!("{base:#x}"), bytes, "renderer port 1: the heap not driver-owned (VICTORY_SAFE_COPY=0 writes title memory through wineserver, which does not reach driver memory), opened in place as before");
+        return false;
+    }
+    match make(base, bytes) {
+        Ok(o) => {
+            if vram() {
+                tracing::info!(
+                    base = format_args!("{base:#x}"),
+                    bytes,
+                    "renderer port 1: the 32-bit graphics heap is driver-owned memory (the card's, write-combined: VICTORY_PORT_OWNED_VRAM) mapped at the title's addresses (VICTORY_PORT_OWNED)"
+                );
+            } else {
+                tracing::info!(
+                    base = format_args!("{base:#x}"),
+                    bytes,
+                    "renderer port 1: the 32-bit graphics heap is driver-owned memory (cached GTT) mapped at the title's addresses (VICTORY_PORT_OWNED)"
+                );
+            }
+            if hands_off() {
+                tracing::info!("renderer port 1: VICTORY_PORT_OWNED=2: nothing is placed in the driver-owned heap, the card gets copies of it as without the port");
+            }
+            OWNED.lock().unwrap_or_else(|e| e.into_inner()).insert(base, o);
+            true
+        }
+        Err(why) => {
+            tracing::warn!(base = format_args!("{base:#x}"), bytes, why, "renderer port 1: the heap not driver-owned, opened in place as before");
+            false
+        }
+    }
+}
+
+fn make(base: usize, bytes: usize) -> Result<Owned, String> {
+    let device = &crate::host::host().ok_or("no host device")?.device;
+    // Cached system memory (vkd3d: cached GTT), or the card's own behind the BAR ([`vram`]).
+    let (cpu, pool) = if vram() { (D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L1) } else { (D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0) };
+    let desc = D3D12_HEAP_DESC {
+        SizeInBytes: bytes as u64,
+        Properties: D3D12_HEAP_PROPERTIES {
+            Type: D3D12_HEAP_TYPE_CUSTOM,
+            CPUPageProperty: cpu,
+            MemoryPoolPreference: pool,
+            CreationNodeMask: 0,
+            VisibleNodeMask: 0,
+        },
+        Alignment: 65536,
+        Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS,
+    };
+    let mut heap: Option<ID3D12Heap> = None;
+    // SAFETY: plain creation.
+    unsafe { device.CreateHeap(&desc, &mut heap) }.map_err(|e| format!("CreateHeap: {e}"))?;
+    let heap = heap.ok_or("CreateHeap: none")?;
+    let buffer = buffer_desc(bytes);
+    let mut mapped: Option<ID3D12Resource> = None;
+    // SAFETY: plain creation in a live heap.
+    unsafe { device.CreatePlacedResource(&heap, 0, &buffer, D3D12_RESOURCE_STATE_COMMON, None, &mut mapped) }.map_err(|e| format!("CreatePlacedResource: {e}"))?;
+    let mapped = mapped.ok_or("CreatePlacedResource: none")?;
+    let mut p: *mut c_void = std::ptr::null_mut();
+    // SAFETY: a buffer in a CPU-visible heap.
+    unsafe { mapped.Map(0, None, Some(&mut p)) }.map_err(|e| format!("Map: {e}"))?;
+    let p = p as usize;
+    let (start, end, offset, path) = mapping_of(p).ok_or("the heap's mapping is not in /proc/self/maps (or no raw Linux call from here: Wine's selector byte is not at TEB+0x340)")?;
+    if !path.starts_with("/dev/dri/") {
+        return Err(format!("the heap is mapped from {path:?}, not a render node"));
+    }
+    if p + bytes > end {
+        return Err(format!("the driver's mapping {start:#x}-{end:#x} does not hold the heap's {bytes:#x} bytes at {p:#x}"));
+    }
+    let offset = offset + (p - start);
+    let fd = render_fd(&path, offset).ok_or("no render node fd takes the heap's offset")?;
+    // SAFETY: both are `bytes` long: the title's fresh heap and the driver's.
+    unsafe { std::ptr::copy_nonoverlapping(base as *const u8, p as *mut u8, bytes) };
+    let m = linux(SYS_MMAP, [base, bytes, PROT_RW, MAP_SHARED | MAP_FIXED, fd, offset]).unwrap_or(-1);
+    if m != base as isize {
+        // A failed MAP_FIXED leaves the old mapping (the kernel checks before it unmaps).
+        return Err(format!("mmap over the title's heap: {m}"));
+    }
+    // One word each way through the two mappings: the same pages.
+    // SAFETY: inside both mappings.
+    unsafe {
+        let t = base as *mut u32;
+        let old = t.read_volatile();
+        t.write_volatile(0x5a17_c0de);
+        let seen = (p as *const u32).read_volatile();
+        t.write_volatile(old);
+        if seen != 0x5a17_c0de {
+            return Err("the title's addresses do not show the driver's pages".into());
+        }
+    }
+    Ok(Owned { bytes, heap, _mapped: mapped })
+}
diff --git a/crates/victory-gpu/src/port.rs b/crates/victory-gpu/src/port.rs
index e899cab..d331813 100644
--- a/crates/victory-gpu/src/port.rs
+++ b/crates/victory-gpu/src/port.rs
@@ -83,6 +83,8 @@ struct Region {
     start: u64,
     end: u64,
     heap: ID3D12Heap,
+    /// The driver's own heap (`crate::owned`), not one opened on title memory.
+    owned: bool,
 }
 
 // SAFETY: D3D12 heaps are free-threaded.
@@ -165,7 +167,8 @@ pub(crate) fn place_in(device: &ID3D12Device, start: u64, len: u64) -> Result<Pl
         }
     };
     let region = &regions[i];
-    let buffer = crate::inplace::place(device, &region.heap, at - region.start, end - at).map_err(|e| (6, format!("no buffer placed in the region: {e}")))?;
+    let placed = if region.owned { crate::owned::place } else { crate::inplace::place };
+    let buffer = placed(device, &region.heap, at - region.start, end - at).map_err(|e| (6, format!("no buffer placed in the region: {e}")))?;
     // SAFETY: a live buffer.
     let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at);
     Ok(Placed { buffer, heap: region.heap.clone(), gpu, bias: start - at })
@@ -257,7 +260,7 @@ fn open_region(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usiz
             );
             // shortcut: the view stays mapped for good (the heap holds its
             // pages while anything names it).
-            Ok(Region { start: first, end: first + bytes, heap })
+            Ok(Region { start: first, end: first + bytes, heap, owned: false })
         }
         Err(e) => {
             unmap();
@@ -272,6 +275,16 @@ fn open_region(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usiz
 /// (`crate::inplace::title_memory_freeing`) and waits for the card before
 /// it gives the memory up.
 fn open_private(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usize, String)> {
+    if let Some((start, end, heap)) = crate::owned::heap_for(at, end) {
+        // The bisection (`VICTORY_PORT_OWNED=2`): the title's heap is driver memory, the card is given copies.
+        if crate::owned::hands_off() {
+            return Err((5, "VICTORY_PORT_OWNED=2: driver memory left to copies".into()));
+        }
+        return Ok(Region { start, end, heap, owned: true });
+    }
+    if crate::owned::only() {
+        return Err((5, "VICTORY_PORT_OWNED_ONLY: private memory outside the driver-owned heap left to copies".into()));
+    }
     // SAFETY: plain data filled in by the query.
     let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
     // SAFETY: a valid out pointer of the right size.
@@ -311,7 +324,7 @@ fn open_private(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usi
                     "renderer port 1: a stretch of the title's graphics memory, private memory, opened as a host heap where it is"
                 );
             }
-            Ok(Region { start: first, end: first + bytes, heap })
+            Ok(Region { start: first, end: first + bytes, heap, owned: false })
         }
         Err(e) => Err((5, format!("refused by the host: {e}"))),
     }
diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs
index c15ecfc..72b8fe8 100644
--- a/crates/victory-hle/src/modules/xmem.rs
+++ b/crates/victory-hle/src/modules/xmem.rs
@@ -2174,6 +2174,8 @@ fn activate(physical: &mut Physical, base: usize, bytes: usize) -> bool {
         return false;
     }
     physical.holes.retain(|&at, _| at < base || at >= end);
+    // Fresh memory, nothing of the title's in it yet: the moment to back it with the driver's (VICTORY_PORT_OWNED).
+    victory_gpu::title_memory_owned(base, bytes);
     victory_gpu::title_memory_allocated(base, bytes);
     victory_gpu::title_memory_unguarded(base, bytes, true);
     PRIVATE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()).push(PrivateRegion { base, bytes, refused: false });
-- 
2.56.0

From b00b0d03bb7fe4a1154c87f86199ec9b603f786f Mon Sep 17 00:00:00 2001
From: GreemSC <[email protected]>
Date: Sun, 29 Nov 2026 21:31:20 +0100
Subject: [PATCH 6/7] shadow: VICTORY_WC_COMMITTED_ONLY=<len>,..: only
 committed allocations of those sizes stay on the card

With every write-combined committed allocation left on the card the title crashed
in 4 of 5 runs (n31, n37, n38; it reads some back). Only the 20 MB buffer
(allocation 0x1420000): runs n47, n47b, n49, n49b, n50 without a crash.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(cherry picked from commit 2a6eb6d8ccaa20c38e4f54bc092981826a4abd3d)
---
 crates/victory-gpu/src/shadow.rs | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)

diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index efffc65..1cfc86d 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -2234,6 +2234,23 @@ static COMMITTED: RwLock<Vec<(u64, u64)>> = RwLock::new(Vec::new());
 /// `crate::resource`'s `resource_attributes`), in memory the kernel watches
 /// (`VICTORY_OWN_WATCH`): see [`wc_committed`].
 pub fn title_memory_committed(at: usize, len: usize) {
+    // `VICTORY_WC_COMMITTED_ONLY=<len>[,<len>..]` (bytes, 0x.. or decimal):
+    // only allocations of those sizes (the 20 MB buffer's is 0x1420000), as
+    // the title may read others back (runs n37, n38 crashed with all of them).
+    static ONLY: std::sync::OnceLock<Vec<usize>> = std::sync::OnceLock::new();
+    let only = ONLY.get_or_init(|| {
+        std::env::var("VICTORY_WC_COMMITTED_ONLY")
+            .unwrap_or_default()
+            .split(',')
+            .filter_map(|v| {
+                let v = v.trim();
+                v.strip_prefix("0x").map_or_else(|| v.parse().ok(), |h| usize::from_str_radix(h, 16).ok())
+            })
+            .collect()
+    });
+    if !only.is_empty() && !only.contains(&len) {
+        return;
+    }
     if len != 0 {
         COMMITTED.write().unwrap_or_else(|e| e.into_inner()).push((at as u64, at.saturating_add(len) as u64));
     }
-- 
2.56.0

From 3658cae9150d9d53a35b9d45e09aa80c0f37c3aa Mon Sep 17 00:00:00 2001
From: GreemSC <[email protected]>
Date: Sun, 29 Nov 2026 21:36:13 +0100
Subject: [PATCH 7/7] shadow: provenance of VICTORY_WC_NO_BACK is
 readmet3xt-lab/foxhound

Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 crates/victory-gpu/src/shadow.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index 1cfc86d..53b0a32 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -2304,7 +2304,7 @@ fn wc_committed() -> bool {
 /// write-combined title memory stays on the card and is not compared,
 /// fetched and merged into title memory (`VICTORY_WC_NO_BACK=1`; off by
 /// default: an experiment; an A/B switch in diagnostics builds). From
-/// fxceless/VIctory-NVIDIA 50c15a1.
+/// readmet3xt-lab/foxhound 50c15a1 (also in trustno1-coder/VIctory-NVIDIA).
 ///
 /// The write-back of shader writes (`Shadow::gpu_writes`: hashes after
 /// sends, compare passes after the lists, fetches of the pieces that differ
@@ -2335,7 +2335,7 @@ fn wc_no_back() -> bool {
 
 /// The smallest copy whose shader writes [`wc_no_back`] leaves on the card,
 /// in bytes (`VICTORY_WC_NO_BACK_MIN_KB`, 1024 unset; 0: all). With every
-/// copy left, upstream's cutscenes went near black (fxceless/VIctory-NVIDIA
+/// copy left, upstream's cutscenes went near black (readmet3xt-lab/foxhound
 /// 2f81d0c: small results the title reads back, such as exposure, came back
 /// stale; 3,245 write-combined copies there, median 4 KB, 82 of 1 MB or
 /// more) while most of the saving is in a few ranges of hundreds of MB.
-- 
2.56.0


<!-- greyfinch-sync:Slaktarn700/SlaktarnVI:comment:7262273944 --> Imported from [Slaktarn700/SlaktarnVI](https://github.com/Slaktarn700/SlaktarnVI/issues/19#issuecomment-7262273944). Originally posted by [GreemSC](https://github.com/GreemSC) on 2026-11-29T20:40:56Z. --- <details><summary>slaktarnvi-7900xt-series.patch (7 patches on 88abc53, <code>git am</code>)</summary> ```diff From 82ccd140a107cf5f379a6ab2e530ee56b370bb03 Mon Sep 17 00:00:00 2001 From: GreemSC <[email protected]> Date: Sun, 29 Nov 2026 14:43:40 +0100 Subject: [PATCH 1/7] shadow: shader writes into write-combined title memory stay on the card (VICTORY_WC_NO_BACK) Port of the write-combined "no write-back" switch to this tree. Off by default. - xmem notes the regions the title asks for write-combined (the console's 0x400 protection bit), forgotten when freed or decommitted (victory_gpu::title_memory_write_combined, watch::title_memory_freed). - VICTORY_WC_NO_BACK=1: Shadow::gpu_writes declares nothing for a copy with a card side whose title memory lies whole in such a region: no snapshot, hash or compare pass, fetch or merge (relay/land) on its account; what shaders wrote stays on the card. In diagnostics builds the switch changes in a run (VICTORY_AB=<s>,VICTORY_WC_NO_BACK). - VICTORY_WC_NO_BACK_MIN_KB (1024 unset, 0: all): only copies at least this large; upstream's cutscenes went near black with every copy (small results the title reads back came back stale). - The frame line of card passes says how many MB a frame were left. Not ported: VICTORY_WC_BAR (one mapped copy in card memory), reported to break lighting. Renderer port 1's memory is in place and has no write-back already; this is for the other copies in the card's memory. Risks (shadow.rs, wc_no_back): the title's CPU reading what shaders wrote there reads older bytes; a page the title writes goes up whole and takes back what shaders wrote in the same 4 KiB page; another host copy of the same bytes does not see shader writes. Provenance (GPL-3.0-or-later, as this tree): commits 50c15a1 "Write-combined title memory: no write-back of shader writes, one mapped copy (switches)" and 2f81d0c "VICTORY_WC_NO_BACK_MIN_KB: only copies at least this large leave shader writes on the card" by readmet3xt-lab <238408149+[email protected]> (fxceless's tree, read in trustno1-coder/VIctory-NVIDIA; the same change is MJ26gaming/victory-rdna4-linux-rt-MJ26 461cb68 and anoyarou/VIctory-RDNA4-linux 9489522; results in Marvisak/VIctory#3570). Changed here: the default threshold (1024 KB), the registry leaves out commits inside a region already noted, the A/B switch. Test: the registry of write-combined regions (not run here: needs Wine). Co-Authored-By: Claude Fable 5.2 <[email protected]> (cherry picked from commit a2de0d2178d686e7cc2e8a71646aa461295bddca) --- crates/victory-gpu/src/host.rs | 6 +- crates/victory-gpu/src/lib.rs | 2 + crates/victory-gpu/src/shadow.rs | 140 +++++++++++++++++++++++++ crates/victory-gpu/src/watch.rs | 1 + crates/victory-hle/src/modules/xmem.rs | 4 + 5 files changed, 151 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 6ced0ae..48d7215 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -10306,10 +10306,12 @@ impl Meter { split_line(frames); { let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); - if passes + compares > 0.0 { + let wc_left = crate::shadow::WC_LEFT.swap(0, Ordering::Relaxed) as f64 / 1e6 / frames; + if passes + compares + wc_left > 0.0 { tracing::info!( "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ - ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes", + ranges were sent up (VICTORY_CARD_REHASH_RUNS=1 joins them: now {}), {compares:.0} compare passes; \ + {wc_left:.1} MB declared written in write-combined memory left on the card (VICTORY_WC_NO_BACK)", if rehash_runs() { "on" } else { "off" } ); } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index d1979e0..5361108 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -157,6 +157,8 @@ pub fn frames_begun() -> u64 { #[cfg(windows)] pub use inplace::{title_memory_freeing, title_memory_quiesce, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] +pub use shadow::title_memory_write_combined; +#[cfg(windows)] pub use watch::{ view_watch, kernel_writing, title_memory_allocated, title_memory_freed, title_memory_unguarded, title_placeholder_released, title_placeholder_reserved, title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_splitting, title_memory_unmapping, title_memory_written, diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 4e183b8..551a1df 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -105,6 +105,9 @@ pub(crate) struct Shadow { /// Of a copy with two sides: only the dwords the title changed go up, /// as with [`send_changed`] ([`by_address`]). changes_only: std::sync::atomic::AtomicBool, + /// Whether its title memory is write-combined ([`Shadow::write_combined`]): + /// 0 not known yet, 1 no, 2 yes. + wc: AtomicU8, /// A window in card memory the CPU maps ([`window_mapped_for`]). mapped: bool, /// An arena of title memory by address ([`by_address`] with `own`): the @@ -2187,6 +2190,88 @@ fn land_echo() -> bool { crate::toggled!("VICTORY_LAND_ECHO") } +/// 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<Vec<(u64, u64)>> = RwLock::new(Vec::new()); + +/// 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 +/// console, the GDK's read-back memory is cacheable). +pub fn title_memory_write_combined(at: usize, len: usize) { + if len == 0 { + return; + } + let (from, to) = (at as u64, at.saturating_add(len) as u64); + let mut all = WRITE_COMBINED.write().unwrap_or_else(|e| e.into_inner()); + // (Commits inside a region noted when it was reserved add nothing.) + if !all.iter().any(|&(a, e)| a <= from && to <= e) { + all.push((from, to)); + } +} + +/// The title let go of `[at, at + len)` (`len` 0: of the allocation at `at`): +/// write-combined 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); + let mut all = WRITE_COMBINED.write().unwrap_or_else(|e| e.into_inner()); + all.retain(|&(from, to)| if len == 0 { from != at } else { to <= at || from >= end }); +} + +/// 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 { + let all = WRITE_COMBINED.read().unwrap_or_else(|e| e.into_inner()); + all.iter().any(|&(from, to)| from <= start && start + len <= to) +} + +/// Whether what shaders write into copies in the card's memory of +/// write-combined title memory stays on the card and is not compared, +/// fetched and merged into title memory (`VICTORY_WC_NO_BACK=1`; off by +/// default: an experiment; an A/B switch in diagnostics builds). From +/// fxceless/VIctory-NVIDIA 50c15a1. +/// +/// The write-back of shader writes (`Shadow::gpu_writes`: hashes after +/// sends, compare passes after the lists, fetches of the pieces that differ +/// and their merge into title memory) keeps title memory the newest for the +/// title's CPU. Memory the title asked for write-combined (protection +/// 0x400) is what its CPU writes and the GPU reads. +/// +/// What it risks, and why it may hold: +/// - The title's CPU reading what shaders wrote there reads older bytes. +/// Read back, write-combined memory is uncached on the console too, and +/// results the CPU reads go to cacheable memory. Small copies are left +/// out all the same ([`wc_no_back_min`]). +/// - A page the CPU writes goes up whole from title memory (as before) and +/// so takes back what shaders wrote in the same 4 KiB page since: mixed +/// pages lose the shaders' bytes (with the write-back they were in title +/// memory). +/// - Another host copy of the same bytes (a texture placed there, a single +/// view's copy) does not see what shaders wrote through title memory. +/// - Changed while the title runs (`VICTORY_AB`): what shaders wrote while +/// it was on is not in title memory when it goes off. +fn wc_no_back() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let on = *ON.get_or_init(|| std::env::var_os("VICTORY_WC_NO_BACK").is_some_and(|v| v == "1")); + #[cfg(feature = "diagnostics")] + let on = crate::ab::pick("VICTORY_WC_NO_BACK").unwrap_or(on); + on +} + +/// The smallest copy whose shader writes [`wc_no_back`] leaves on the card, +/// in bytes (`VICTORY_WC_NO_BACK_MIN_KB`, 1024 unset; 0: all). With every +/// copy left, upstream's cutscenes went near black (fxceless/VIctory-NVIDIA +/// 2f81d0c: small results the title reads back, such as exposure, came back +/// stale; 3,245 write-combined copies there, median 4 KB, 82 of 1 MB or +/// more) while most of the saving is in a few ranges of hundreds of MB. +fn wc_no_back_min() -> u64 { + static MIN: std::sync::OnceLock<u64> = std::sync::OnceLock::new(); + *MIN.get_or_init(|| std::env::var("VICTORY_WC_NO_BACK_MIN_KB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(1024) << 10) +} + +/// Bytes shaders were declared to write in write-combined copies and that +/// were left on the card ([`wc_no_back`]), since the last frame-rate line. +pub(crate) static WC_LEFT: AtomicU64 = AtomicU64::new(0); + /// Whether we run under Wine: its ntdll exports `wine_get_version` (as /// `victory_hle::modules::xmem` tells it). pub(crate) fn on_wine() -> bool { @@ -3438,6 +3523,7 @@ impl Shadow { card: None, window: false, changes_only: Default::default(), + wc: AtomicU8::new(0), mapped: false, own_side: false, place: None, @@ -3469,11 +3555,39 @@ impl Shadow { if self.place.is_some() { return; } + // Write-combined title memory, which the title's CPU does not read + // (`VICTORY_WC_NO_BACK`): what shaders write stays on the card. + if self.card.is_some() && wc_no_back() && self.len >= wc_no_back_min() && self.write_combined() { + self.written.store(true, Ordering::Relaxed); + WC_LEFT.fetch_add(len.min(self.left(address)), Ordering::Relaxed); + return; + } self.written.store(true, Ordering::Relaxed); let len = len.min(self.left(address)); 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. + fn write_combined(&self) -> bool { + match self.wc.load(Ordering::Relaxed) { + 1 => false, + 2 => true, + _ => { + let wc = is_write_combined(self.start, self.len); + self.wc.store(if wc { 2 } else { 1 }, Ordering::Relaxed); + if wc { + 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 (VICTORY_WC_NO_BACK)" + ); + } + wc + } + } + } + /// At submission, after the range's refresh: a submitted list's shaders /// write this range. Its bytes are kept to tell later what the GPU wrote: /// one snapshot per copy and submission, each byte taken once, when the @@ -7472,3 +7586,29 @@ mod plain_tests { assert_eq!(plain_side_bytes(), before); } } + +#[cfg(test)] +mod write_combined_tests { + use super::{is_write_combined, title_memory_write_combined, write_combined_freed}; + + /// 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). + #[test] + fn write_combined_regions() { + // Addresses of their own: other tests share the registry. + let base = 0x7f00_0000_0000usize; + title_memory_write_combined(base, 0x100_0000); + // (A commit inside it adds nothing.) + title_memory_write_combined(base + 0x1000, 0x1000); + 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"); + write_combined_freed(base + 0x10_0000, 0x1000); + assert!(!is_write_combined(base as u64, 0x1000), "part of it decommitted"); + let other = base + 0x1000_0000; + title_memory_write_combined(other, 0x10_0000); + write_combined_freed(other, 0); + assert!(!is_write_combined(other as u64, 0x1000), "the allocation released"); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index fbcf560..f050f1f 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -4284,6 +4284,7 @@ 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) { + crate::shadow::write_combined_freed(at, len); crate::memory::title_let_go(at, len); if len != 0 { let last = at.saturating_add(len).div_ceil(BLOCK); diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index f19b9db..8e2d255 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -191,6 +191,10 @@ pub extern "system" fn XMemVirtualAlloc( if !at.is_null() && constrained && kind & MEM_COMMIT == 0 && flags & ADDRESS_32BIT != 0 { LOW_RESERVATIONS.lock().unwrap_or_else(|e| e.into_inner()).push((at as usize, size)); } + // Write-combined: memory the title's CPU writes and does not read. + if !at.is_null() && asked & 0x400 != 0 { + victory_gpu::title_memory_write_combined(at as usize, size); + } note_protection(asked, kind, flags, at as usize, size); at } -- 2.56.0 From 544f969b0c99b35278e836c3317abe6cba751670 Mon Sep 17 00:00:00 2001 From: GreemSC <[email protected]> Date: Sun, 29 Nov 2026 15:46:22 +0100 Subject: [PATCH 2/7] xmem: big blocks for the D3D runtime in write-watched memory (VICTORY_OWN_WATCH) XMemAllocDefault took a committed resource's memory from the host heap, which is not write-watched: its host copy was copied whole at every refresh and sent to the card again whole (run n18: 0x7db20000+0x1412200, 1.9 refreshes and 40 MB a frame, 4.6 ms on the submitting thread, 20 of the 48 MB sent up). With VICTORY_OWN_WATCH=1 a block of 1 MiB or more (VICTORY_OWN_WATCH_MIN_KB) asked for with allocator 128 is an allocation of its own with MEM_WRITE_WATCH, in whole 64 KiB pages; one of memory type 1 is told to the GPU side (VICTORY_WC_COMMITTED). Off by default, read once. Co-Authored-By: Claude Fable 5.2 <[email protected]> (cherry picked from commit 410a93b18e4e550ea5111d5dca24ffc08d011676) --- crates/victory-hle/src/modules/xmem.rs | 83 ++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 8e2d255..d90fab7 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -345,6 +345,9 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_ let Some(layout) = layout(size, attributes) else { return std::ptr::null_mut(); }; + if let Some(user) = watched_block(size, layout.align(), attributes) { + return user; + } // shortcut: the host heap's addresses lie above 2^40, unlike the // console's; nothing seen builds ray-tracing structures in this memory // (the title uses its GPU heap). Sub-allocate from a @@ -366,6 +369,80 @@ pub extern "system" fn XMemAllocDefault(size: usize, attributes: u64) -> *mut c_ } } +/// In the second word of a block's header, where the host heap's blocks have +/// their alignment: a block of [`watched_block`]. +const WATCHED_BLOCK: usize = 1 << (usize::BITS - 1); + +/// The smallest block [`XMemAllocDefault`] gives the D3D runtime out of +/// memory the kernel watches, in bytes (`VICTORY_OWN_WATCH=1`; off by +/// default; `VICTORY_OWN_WATCH_MIN_KB`, 1024 unset). Read once: memory made +/// before stays what it is. +/// +/// A committed resource's memory comes from here through the title's +/// allocation hook, out of the host heap, which is not write-watched: the +/// GPU side copies such a buffer whole at every refresh and sends all of it +/// to the card again (run n18: one buffer of 20 MB that shaders write, 40 MB +/// and 4.6 ms a frame copied on the submitting thread, 20 of the 48 MB sent +/// up). Watched like the title's other memory, only the pages written since +/// the last copy are taken. +fn own_watch_min() -> Option<usize> { + static MIN: LazyLock<Option<usize>> = LazyLock::new(|| { + let kb = || std::env::var("VICTORY_OWN_WATCH_MIN_KB").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(1024); + std::env::var_os("VICTORY_OWN_WATCH").is_some_and(|v| v == "1").then(|| kb().saturating_mul(1024)) + }); + *MIN +} + +/// [`XMemAllocDefault`]'s block of `size` bytes for the D3D runtime +/// (allocator 128, `victory_gpu`'s committed resources) in an allocation of +/// its own that the kernel watches, if [`own_watch_min`] asks for it; `None`: +/// the host heap as before. Whole 64 KiB pages, which the GPU side asks +/// about. A GPU-only heap's (memory type 1, write-combined) is told to the +/// GPU side (`VICTORY_WC_COMMITTED`). +fn watched_block(size: usize, align: usize, attributes: u64) -> Option<*mut c_void> { + const D3D: u64 = 128; + const WRITE_COMBINED: u64 = 1; + let min = own_watch_min()?; + if size < min { + return None; + } + if attributes >> 16 & 0xff != D3D || align > PAGE || size & WATCHED_BLOCK != 0 { + // (Said a few times: what else is this big, if the resources' own + // do not come by here as expected.) + static LEFT: AtomicU64 = AtomicU64::new(0); + if LEFT.fetch_add(1, Ordering::Relaxed) < 8 { + tracing::info!("VICTORY_OWN_WATCH: a block of {size:#x} bytes left to the host heap, attributes {attributes:#x}, alignment {align:#x}"); + } + return None; + } + let len = size.checked_add(align)?.checked_next_multiple_of(PAGE)?; + // SAFETY: a plain allocation. + let base = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }.cast::<u8>(); + if base.is_null() { + return None; + } + // SAFETY: the allocation holds the alignment (at least the header) and + // then `size` bytes. + let user = unsafe { + let user = base.add(align); + user.sub(HEADER).cast::<[usize; 2]>().write([base as usize, size | WATCHED_BLOCK]); + user + }; + victory_gpu::title_memory_allocated(user as usize, size); + let write_combined = attributes >> 29 & 0xf == WRITE_COMBINED; + if write_combined { + victory_gpu::title_memory_committed(user as usize, size); + } + static MADE: AtomicU64 = AtomicU64::new(0); + let made = MADE.fetch_add(1, Ordering::Relaxed) + 1; + if made <= 32 || made.is_power_of_two() { + tracing::info!( + "memory for a committed resource in a watched allocation of its own (VICTORY_OWN_WATCH): {user:p}+{size:#x}, write-combined on the console: {write_combined}; {made} so far" + ); + } + Some(user.cast()) +} + /// Frees what [`XMemAllocDefault`] returned, given the same attributes. pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { if address.is_null() { @@ -380,6 +457,12 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { } let user = address.cast::<u8>(); let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read(); + if align & WATCHED_BLOCK != 0 { + // ([`watched_block`]: the allocation's base in place of the size.) + victory_gpu::title_memory_committed_freed(user as usize); + VirtualFree(size as *mut c_void, 0, MEM_RELEASE); + return; + } dealloc( user.sub(align), Layout::from_size_align_unchecked(size, align), -- 2.56.0 From bfdb40ad5aadc161b08b3e4439a54af6c626426e Mon Sep 17 00:00:00 2001 From: GreemSC <[email protected]> Date: Sun, 29 Nov 2026 15:46:22 +0100 Subject: [PATCH 3/7] shadow: shader writes into committed resources of GPU-only heaps stay on the card (VICTORY_WC_COMMITTED) With VICTORY_WC_NO_BACK=1: a copy in the card's memory whose title memory the runtime made for a committed resource of a GPU-only heap (told by title_memory_committed, memory type write-combined in the allocation attributes) no longer declares its shader writes, as copies of memory the title asked for write-combined already do. Only while the memory is known to be watched by the kernel (VICTORY_OWN_WATCH): a refresh of unwatched memory copies it whole and would send it over what the shaders wrote. Run n18 (world, 65 ms a frame): one such buffer of 20 MB is written whole by shaders every frame; 21 of the 22 MB a frame copied back are its pieces. Off by default; an A/B switch in diagnostics builds. Co-Authored-By: Claude Fable 5.2 <[email protected]> (cherry picked from commit cf6c9da5c30a9364730037895c29d5ece2b68a82) --- crates/victory-gpu/src/lib.rs | 2 +- crates/victory-gpu/src/shadow.rs | 83 +++++++++++++++++++++++++++++++- 2 files changed, 82 insertions(+), 3 deletions(-) diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 5361108..5c8e2a5 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -157,7 +157,7 @@ pub fn frames_begun() -> u64 { #[cfg(windows)] pub use inplace::{title_memory_freeing, title_memory_quiesce, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] -pub use shadow::title_memory_write_combined; +pub use shadow::{title_memory_committed, title_memory_committed_freed, title_memory_write_combined}; #[cfg(windows)] pub use watch::{ view_watch, kernel_writing, title_memory_allocated, title_memory_freed, title_memory_unguarded, title_placeholder_released, title_placeholder_reserved, title_memory_reading, title_memory_remapped, diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 551a1df..efffc65 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -106,7 +106,8 @@ pub(crate) struct Shadow { /// as with [`send_changed`] ([`by_address`]). changes_only: std::sync::atomic::AtomicBool, /// Whether its title memory is write-combined ([`Shadow::write_combined`]): - /// 0 not known yet, 1 no, 2 yes. + /// 0 not known yet, 1 no, 2 yes, 3 a committed resource's + /// ([`title_memory_committed`]). wc: AtomicU8, /// A window in card memory the CPU maps ([`window_mapped_for`]). mapped: bool, @@ -2224,6 +2225,64 @@ fn is_write_combined(start: u64, len: u64) -> bool { all.iter().any(|&(from, to)| from <= start && start + len <= to) } +/// Memory the runtime gave a committed resource of a GPU-only heap, write +/// watched, as `[start, end)` ([`title_memory_committed`]). +static COMMITTED: RwLock<Vec<(u64, u64)>> = RwLock::new(Vec::new()); + +/// The runtime made `[at, at + len)` for a committed resource of a GPU-only +/// heap (the allocation attributes' memory type says write-combined, +/// `crate::resource`'s `resource_attributes`), in memory the kernel watches +/// (`VICTORY_OWN_WATCH`): see [`wc_committed`]. +pub fn title_memory_committed(at: usize, len: usize) { + if len != 0 { + COMMITTED.write().unwrap_or_else(|e| e.into_inner()).push((at as u64, at.saturating_add(len) as u64)); + } +} + +/// The memory [`title_memory_committed`] told of at `at` is let go. +pub fn title_memory_committed_freed(at: usize) { + COMMITTED.write().unwrap_or_else(|e| e.into_inner()).retain(|&(from, _)| from != at as u64); +} + +/// Whether all of `[start, start + len)` lies in one such allocation. +fn is_committed(start: u64, len: u64) -> bool { + let all = COMMITTED.read().unwrap_or_else(|e| e.into_inner()); + all.iter().any(|&(from, to)| from <= start && start + len <= to) +} + +/// Whether [`wc_no_back`] also leaves on the card what shaders write into +/// copies of committed resources of GPU-only heaps +/// (`VICTORY_WC_COMMITTED=1`, with `VICTORY_WC_NO_BACK=1` and +/// `VICTORY_OWN_WATCH=1`; off by default: an experiment; an A/B switch in +/// diagnostics builds). +/// +/// Why: such a resource's memory came from the host heap, which nothing +/// watches. In the world one buffer of 20 MB there (run n18) is written whole +/// by shaders every frame: 21 MB a frame compared, fetched and merged into +/// title memory (all but 1 MB of the frame line's "copying back"), then +/// copied whole from title memory at every refresh (40 MB, 4.6 ms a frame) +/// and sent up again (20 of 48 MB), the very bytes the card held. On the +/// console that memory is write-combined (the type the runtime asks the +/// title's allocator for: the plausible one, not known), which the title's +/// CPU does not read. +/// +/// Only for memory the kernel watches (`VICTORY_OWN_WATCH`, the runtime's +/// `XMemAllocDefault`): a refresh of memory that is not watched copies title +/// memory whole and sends it over what the shaders wrote +/// ([`Shadow::committed_left`]). +/// +/// What it risks is what [`wc_no_back`] risks. Changed while the title runs: +/// when it goes on, the last landings are sent up once more, over what +/// shaders wrote since; when it goes off, title memory lacks what was written +/// meanwhile until shaders write it again. +fn wc_committed() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + let on = *ON.get_or_init(|| std::env::var_os("VICTORY_WC_COMMITTED").is_some_and(|v| v == "1")); + #[cfg(feature = "diagnostics")] + let on = crate::ab::pick("VICTORY_WC_COMMITTED").unwrap_or(on); + on +} + /// Whether what shaders write into copies in the card's memory of /// write-combined title memory stays on the card and is not compared, /// fetched and merged into title memory (`VICTORY_WC_NO_BACK=1`; off by @@ -3568,13 +3627,25 @@ impl Shadow { } /// Whether all of the copy's title memory was asked for write-combined - /// ([`title_memory_write_combined`]); found once. + /// ([`title_memory_write_combined`]), or is a committed resource's whose + /// shader writes stay on the card now ([`Shadow::committed_left`]); which + /// memory it is is found once. fn write_combined(&self) -> bool { match self.wc.load(Ordering::Relaxed) { 1 => false, 2 => true, + 3 => self.committed_left(), _ => { let wc = is_write_combined(self.start, self.len); + if !wc && is_committed(self.start, self.len) { + self.wc.store(3, Ordering::Relaxed); + tracing::info!( + start = format_args!("{:#x}", self.start), + len = format_args!("{:#x}", self.len), + "a committed resource of a GPU-only heap in watched memory: what shaders write in its copy is not copied back with VICTORY_WC_COMMITTED" + ); + return self.committed_left(); + } self.wc.store(if wc { 2 } else { 1 }, Ordering::Relaxed); if wc { tracing::info!( @@ -3588,6 +3659,14 @@ impl Shadow { } } + /// Of a copy of a committed resource's memory ([`title_memory_committed`]): + /// whether what shaders write stays on the card now ([`wc_committed`]). + /// Not while the memory is not known to be watched: a refresh would copy + /// it whole, and send it over what the shaders wrote. + fn committed_left(&self) -> bool { + wc_committed() && self.watched.load(Ordering::Relaxed) == 1 + } + /// At submission, after the range's refresh: a submitted list's shaders /// write this range. Its bytes are kept to tell later what the GPU wrote: /// one snapshot per copy and submission, each byte taken once, when the -- 2.56.0 From ebc908f976e9c03d0d9893022fc5e3ba145de2e9 Mon Sep 17 00:00:00 2001 From: GreemSC <[email protected]> Date: Sun, 29 Nov 2026 20:21:27 +0100 Subject: [PATCH 4/7] xmem: OWN_WATCH blocks above the low 4 GiB (after trustno1-coder/VIctory-NVIDIA 7cd552bd64 by shreezzz) A plain VirtualAlloc took addresses under 4 GiB for the watched blocks (n19, n20: 0x178d0000, 0x7b700100), which the title's 32-bit requests and renderer port 1's heap need: the title hung or crashed. The reservation is now bounded with VirtualAlloc2 and address_range(0), as trustno1-coder/VIctory-NVIDIA 7cd552bd64 (shreezzz) bounds its own. Co-Authored-By: Claude Fable 5.2 <[email protected]> (cherry picked from commit 17273da6d26d672f0e8bf9e0061371ed51efe6b9) --- crates/victory-hle/src/modules/xmem.rs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index d90fab7..c15ecfc 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -416,8 +416,23 @@ fn watched_block(size: usize, align: usize, attributes: u64) -> Option<*mut c_vo return None; } let len = size.checked_add(align)?.checked_next_multiple_of(PAGE)?; - // SAFETY: a plain allocation. - let base = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) }.cast::<u8>(); + // Above the low 4 GiB, which the title's 32-bit requests (and renderer + // port 1's heap) need: a plain VirtualAlloc took addresses there (n19, + // n20: 0x178d0000, 0x7b700100) and the title hung or crashed. + // trustno1-coder/VIctory-NVIDIA 7cd552bd64 (shreezzz) bounds its watched + // reservations the same way. + let (lowest, highest) = address_range(0); + let mut requirements = + MEM_ADDRESS_REQUIREMENTS { LowestStartingAddress: lowest as *mut c_void, HighestEndingAddress: highest as *mut c_void, Alignment: 0 }; + let mut parameter = MEM_EXTENDED_PARAMETER::default(); + parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64; + parameter.Anonymous2.Pointer = (&raw mut requirements).cast(); + // SAFETY: the host chooses an address within `requirements`, which + // outlives the call through `parameter`. + let base = unsafe { + VirtualAlloc2(GetCurrentProcess(), std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE, &mut parameter, 1) + } + .cast::<u8>(); if base.is_null() { return None; } -- 2.56.0 From 9f1843f1e91861a930d8fc1696350c0c34181db7 Mon Sep 17 00:00:00 2001 From: GreemSC <[email protected]> Date: Sun, 29 Nov 2026 20:36:14 +0100 Subject: [PATCH 5/7] port 1: VICTORY_PORT_OWNED backs the 32-bit graphics heap with a driver heap mapped at the title's addresses (no userptr) Port of cairodavila/SlaktarnVI, branch gtabox, commits de9be80 ("port 1: VICTORY_PORT_OWNED=1 backs the 32-bit graphics heap with a driver heap mapped at the title's addresses (no userptr)") and 16b722e ("owned: retire the driver heap only when the whole of it is given up"), and the one change of code in 34b39f8 (the switch value 2; the rest of it reformats three files). Author: Cairo (cairodavila), GPL-3.0-or-later, as this tree. When xmem makes the 32-bit graphics heap one private allocation (VICTORY_PORT_PRIVATE=1), a D3D12 heap of the driver's own is made and its CPU mapping (the render node at the BO's offset) is mapped over the title's addresses with a raw Linux mmap(MAP_FIXED), issued from this PE code with Wine's syscall-user-dispatch selector byte (TEB+0x340) cleared around the syscall. Port 1 places its buffers in that heap; nothing is imported by host pointer for it, so amdgpu has no userptr to walk per submission. Off by default. - VICTORY_PORT_OWNED=1 (with VICTORY_PORT_CONSTANTS=1, VICTORY_PORT_PRIVATE=1). - VICTORY_PORT_OWNED=2: upstream's bisection: driver memory, nothing placed in it (the card gets copies). - VICTORY_PORT_OWNED_VRAM=1 (new): the heap in the card's memory, write-combined, seen through the BAR, not in cached system memory: the card works at home, CPU reads of the heap are very slow. - VICTORY_PORT_OWNED_ONLY=1 (new): no other private memory opened in place (run n16 had three more stretches, 34 MB, still host-pointer imports). Other changes from upstream: only under Wine; what a raw call returns is bounded (a signal between the selector's write and the syscall makes it a Windows call); the driver's mapping must hold the whole heap; refused with VICTORY_SAFE_COPY=0 (NtWriteVirtualMemory goes through wineserver, which does not reach a VM_PFNMAP mapping); mod owned stays under cfg(windows). The heap is not write-watched (xmem commits it without MEM_WRITE_WATCH and tells it unguarded), which the kernel's scan would skip silently there. Not run: built only. Co-Authored-By: Claude Fable 5.2 <[email protected]> (cherry picked from commit a7c44a6f67fd1883064c45ad07e70666765063ac) --- crates/victory-gpu/src/inplace.rs | 1 + crates/victory-gpu/src/lib.rs | 4 + crates/victory-gpu/src/owned.rs | 327 +++++++++++++++++++++++++ crates/victory-gpu/src/port.rs | 19 +- crates/victory-hle/src/modules/xmem.rs | 2 + 5 files changed, 350 insertions(+), 3 deletions(-) create mode 100644 crates/victory-gpu/src/owned.rs diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 10844e8..a9f1227 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -191,6 +191,7 @@ pub(crate) fn gone(window: bool, bytes: u64) { pub fn title_memory_freeing(at: usize, len: usize) { // Renderer port 1's regions there: no longer what the title shows. crate::port::forget(at, len); + crate::owned::freeing(at, len); if STATS[0].load(Ordering::Relaxed) + STATS[2].load(Ordering::Relaxed) == 0 { return; } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index 5c8e2a5..b4aaf7a 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -57,6 +57,8 @@ mod indirect; #[cfg(windows)] mod inplace; #[cfg(windows)] +mod owned; +#[cfg(windows)] mod port; #[cfg(windows)] mod port_cbv; @@ -155,6 +157,8 @@ pub fn frames_begun() -> u64 { frame::current() } #[cfg(windows)] +pub use owned::title_memory_owned; +#[cfg(windows)] pub use inplace::{title_memory_freeing, title_memory_quiesce, title_memory_section, title_memory_section_gone, title_memory_view}; #[cfg(windows)] pub use shadow::{title_memory_committed, title_memory_committed_freed, title_memory_write_combined}; diff --git a/crates/victory-gpu/src/owned.rs b/crates/victory-gpu/src/owned.rs new file mode 100644 index 0000000..b90dc41 --- /dev/null +++ b/crates/victory-gpu/src/owned.rs @@ -0,0 +1,327 @@ +//! Renderer port 1 on memory the card's driver owns (`VICTORY_PORT_OWNED=1`, +//! Linux only, with `VICTORY_PORT_CONSTANTS=1` and `VICTORY_PORT_PRIVATE=1`). +//! +//! Port 1 opens the title's 32-bit graphics heap where it is +//! (`OpenExistingHeapFromAddress1`). Under vkd3d-proton on RADV that is a +//! host-pointer import, an amdgpu userptr: the kernel walks and compares all +//! ~47,000 pages of it on every submission (~23 ms of GPU wait a frame here). +//! Here instead, when `xmem` makes that heap (fresh, before the title writes +//! it), a heap of the driver's own (custom, write-back, L0: cached GTT) is +//! made and its CPU mapping (an mmap of the render node at the BO's fake +//! offset) is mapped a second time over the title's addresses with a raw +//! Linux `mmap(MAP_FIXED)`. The title and the card then share the same +//! pages, and the kernel has nothing to check per submission. Wine still +//! believes it is private memory; protecting and freeing it work as before. +//! +//! What a mapping of the render node cannot do: be the target of O_DIRECT +//! reads or of another process's `process_vm_readv` (no struct pages). +//! +//! From cairodavila/SlaktarnVI, branch `gtabox` (Cairo, GPL-3.0-or-later): +//! de9be80 and 16b722e, and the switch value `2` of 34b39f8. Added here: +//! the Wine check, the bounds on what a raw call returns, the check that the +//! driver's mapping holds the whole heap, `VICTORY_PORT_OWNED_VRAM` and +//! `VICTORY_PORT_OWNED_ONLY`. +//! +//! What was looked at for that mapping (`VM_PFNMAP | VM_IO`), wine-cachyos +//! cd14106e and Linux 7.3: +//! - write watching: the kernel's `PAGEMAP_SCAN` skips such a mapping without +//! an error, so it would read as never written. The heap is not watched: +//! `xmem` commits it without `MEM_WRITE_WATCH` and tells +//! `crate::watch::title_memory_unguarded`, whose blocks count as written at +//! every asking; the buffers placed in it are not copied at all. +//! - O_DIRECT: Wine opens no file with it (`FILE_FLAG_NO_BUFFERING` is a +//! buffered read there), so the title's reads into the heap work. +//! - the kernel's copies of `VICTORY_SAFE_COPY=0`: `ReadProcessMemory` on our +//! own process is a `memmove` inside Wine, but `NtWriteVirtualMemory` goes +//! through wineserver (`process_vm_writev`, then ptrace), which does not +//! reach driver memory: with that setting the heap is left as it is +//! ([`title_memory_owned`]). Another process (a debugger) does not read it. +//! - not to be mixed with what imports title memory in the heap by host +//! pointer (`VICTORY_INPLACE`) or collapses it from outside +//! (`VICTORY_PORT_HUGE`): neither works on a driver mapping. + +use std::arch::asm; +use std::collections::BTreeMap; +use std::ffi::c_void; +use std::sync::Mutex; + +use windows::Win32::Graphics::Direct3D12::*; +use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_UNKNOWN, DXGI_SAMPLE_DESC}; + +/// `VICTORY_PORT_OWNED`: `1` or `2` puts port 1's private heap in driver +/// memory (off by default; under Wine only: the raw call is Linux's). +pub(crate) fn on() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| crate::port::on() && std::env::var("VICTORY_PORT_OWNED").is_ok_and(|v| matches!(v.trim(), "1" | "2")) && crate::shadow::on_wine()) +} + +/// `VICTORY_PORT_OWNED=2`: the heap is driver memory, but port 1 places +/// nothing in it (copies as without the port): tells a CPU-side problem of +/// driver memory from a card-side one. +pub(crate) fn hands_off() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_PORT_OWNED").is_ok_and(|v| v.trim() == "2")) +} + +/// `VICTORY_PORT_OWNED_VRAM=1` (with `VICTORY_PORT_OWNED`; off by default): +/// the driver heap is made in the card's own memory, write-combined and seen +/// by the CPU through the resizable BAR (custom, write-combine, L1: vkd3d's +/// GPU upload heap), not in cached system memory. The card then reads and +/// writes the heap at home, not over PCIe (a 20 MB buffer of the title in +/// system memory took the card from 30 to 50 % busy, run n28); CPU writes +/// stay quick (write-combined), but every CPU read of it (the title's, and +/// the fills and copies port 1's line counts) is uncached and very slow. +/// Refused by the host without a resizable BAR: the heap is then opened in +/// place as before. +fn vram() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_PORT_OWNED_VRAM").is_ok_and(|v| v.trim() == "1")) +} + +/// `VICTORY_PORT_OWNED_ONLY=1` (off by default), while a heap is driver-owned: +/// port 1 opens no other private memory in place. Without it the title's +/// other buffers under 4 GiB (run n16: three stretches, 34 MB, one a 21 MB +/// buffer shaders write) are still opened where they are, host-pointer +/// imports the kernel walks on every submission as it did the heap. +pub(crate) fn only() -> bool { + static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_PORT_OWNED_ONLY").is_ok_and(|v| v.trim() == "1")) && !OWNED.lock().unwrap_or_else(|e| e.into_inner()).is_empty() +} + +/// Driver heaps over title memory: base -> (bytes, heap, the buffer whose Map keeps vkd3d's mapping). +struct Owned { + bytes: usize, + heap: ID3D12Heap, + _mapped: ID3D12Resource, +} +// SAFETY: D3D12 objects are free-threaded. +unsafe impl Send for Owned {} + +static OWNED: Mutex<BTreeMap<usize, Owned>> = Mutex::new(BTreeMap::new()); +/// Heaps the title has given up: kept, the card may still name them. +/// shortcut: never released (one per time the title remakes its heap, 185 MB each; it makes it once). +static RETIRED: Mutex<Vec<Owned>> = Mutex::new(Vec::new()); + +/// The driver heap holding `[at, end)`, as (its start, heap). +pub(crate) fn heap_for(at: u64, end: u64) -> Option<(u64, u64, ID3D12Heap)> { + let owned = OWNED.lock().unwrap_or_else(|e| e.into_inner()); + let (&base, o) = owned.range(..=at as usize).next_back()?; + (end as usize <= base + o.bytes).then(|| (base as u64, (base + o.bytes) as u64, o.heap.clone())) +} + +/// A buffer over `[offset, offset + size)` of a driver heap (port 1's place, +/// minus the cross-adapter flag only opened heaps need). +pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result<ID3D12Resource> { + let mut placed: Option<ID3D12Resource> = None; + // SAFETY: plain creation in a live heap. + unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size as usize), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? }; + placed.ok_or_else(windows::core::Error::empty) +} + +fn buffer_desc(bytes: usize) -> D3D12_RESOURCE_DESC { + D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Alignment: 0, + Width: bytes as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_UNKNOWN, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + } +} + +/// The title gives `[at, at + len)` up: a heap over it is retired. +pub(crate) fn freeing(at: usize, len: usize) { + let mut owned = OWNED.lock().unwrap_or_else(|e| e.into_inner()); + // Only the whole heap (xmem's deactivate): mappings into it come and go (give_back, + // remaps) while the memory stays, and port 1 reopens its regions from here. + let gone: Vec<usize> = owned.range(at..at + len).filter(|(b, o)| **b + o.bytes <= at + len).map(|(b, _)| *b).collect(); + let mut retired = RETIRED.lock().unwrap_or_else(|e| e.into_inner()); + for b in gone { + if let Some(o) = owned.remove(&b) { + tracing::info!(base = format_args!("{b:#x}"), bytes = o.bytes, "renderer port 1: driver-owned heap given up by the title (kept for the card)"); + retired.push(o); + } + } +} + +/// A raw Linux syscall from this PE code. Wine traps `syscall` outside its +/// own code (syscall user dispatch) unless the thread's selector byte, +/// TEB+0x340 (`amd64_thread_data.syscall_dispatch`), is ALLOW (0); it is +/// BLOCK (1) while PE code runs. `None` if the byte is not what Wine puts there. +fn linux(nr: usize, a: [usize; 6]) -> Option<isize> { + // SAFETY: gs:[0x30] is the TEB on Windows x64 and under Wine; 0x340 is + // inside it (Wine's per-thread data), only toggled around one syscall. + unsafe { + let teb: *mut u8; + asm!("mov {}, gs:[0x30]", out(reg) teb, options(nostack, readonly, preserves_flags)); + let sel = teb.add(0x340); + if sel.read_volatile() != 1 { + return None; + } + sel.write_volatile(0); + let ret: isize; + asm!("syscall", inlateout("rax") nr as isize => ret, in("rdi") a[0], in("rsi") a[1], in("rdx") a[2], + in("r10") a[3], in("r8") a[4], in("r9") a[5], lateout("rcx") _, lateout("r11") _, options(nostack)); + sel.write_volatile(1); + Some(ret) + } +} + +const SYS_READ: usize = 0; +const SYS_CLOSE: usize = 3; +const SYS_MMAP: usize = 9; +const SYS_MUNMAP: usize = 11; +const SYS_READLINK: usize = 89; +const SYS_OPENAT: usize = 257; +const PROT_RW: usize = 3; +const MAP_SHARED: usize = 0x01; +const MAP_FIXED: usize = 0x10; + +fn failed(r: isize) -> bool { + (-4095..0).contains(&r) +} + +fn read_file(path: &str) -> Option<String> { + let c = format!("{path}\0"); + let fd = linux(SYS_OPENAT, [-100isize as usize, c.as_ptr() as usize, 0, 0, 0, 0]).filter(|r| *r >= 0)?; + let mut out = Vec::new(); + let mut buf = vec![0u8; 1 << 16]; + // (`n` within the buffer: a signal between the selector's write and the call makes it a Windows call, with any answer) + while let Some(n) = linux(SYS_READ, [fd as usize, buf.as_mut_ptr() as usize, buf.len(), 0, 0, 0]).filter(|n| *n > 0 && *n as usize <= buf.len()) { + out.extend_from_slice(&buf[..n as usize]); + } + linux(SYS_CLOSE, [fd as usize, 0, 0, 0, 0, 0]); + Some(String::from_utf8_lossy(&out).into_owned()) +} + +/// The Linux mapping holding `at`: (its start, end, file offset, path). +fn mapping_of(at: usize) -> Option<(usize, usize, usize, String)> { + read_file("/proc/self/maps")?.lines().find_map(|line| { + let f: Vec<&str> = line.split_whitespace().collect(); + let (s, e) = f.first()?.split_once('-')?; + let (s, e) = (usize::from_str_radix(s, 16).ok()?, usize::from_str_radix(e, 16).ok()?); + (s <= at && at < e).then(|| Some((s, e, usize::from_str_radix(f.get(2)?, 16).ok()?, f.get(5).unwrap_or(&"").to_string())))? + }) +} + +/// An fd of `path` (the render node) that the BO's fake `offset` belongs to: +/// DRM checks the offset against the open file it was made for. +fn render_fd(path: &str, offset: usize) -> Option<usize> { + let mut buf = [0u8; 256]; + (0..65536usize).find(|fd| { + let link = format!("/proc/self/fd/{fd}\0"); + let n = linux(SYS_READLINK, [link.as_ptr() as usize, buf.as_mut_ptr() as usize, buf.len(), 0, 0, 0]).unwrap_or(-1); + if n <= 0 || n as usize > buf.len() || &buf[..n as usize] != path.as_bytes() { + return false; + } + let m = linux(SYS_MMAP, [0, 4096, 1, MAP_SHARED, *fd, offset]).unwrap_or(-1); + if failed(m) { + return false; + } + linux(SYS_MUNMAP, [m as usize, 4096, 0, 0, 0, 0]); + true + }) +} + +/// `xmem` made `[base, base + bytes)` (fresh private memory, before the title +/// writes it) port 1's heap: back it with driver memory. False leaves it as +/// it is (port 1 then opens it in place as before). +pub fn title_memory_owned(base: usize, bytes: usize) -> bool { + if !on() { + return false; + } + if !crate::safecopy::on() { + tracing::warn!(base = format_args!("{base:#x}"), bytes, "renderer port 1: the heap not driver-owned (VICTORY_SAFE_COPY=0 writes title memory through wineserver, which does not reach driver memory), opened in place as before"); + return false; + } + match make(base, bytes) { + Ok(o) => { + if vram() { + tracing::info!( + base = format_args!("{base:#x}"), + bytes, + "renderer port 1: the 32-bit graphics heap is driver-owned memory (the card's, write-combined: VICTORY_PORT_OWNED_VRAM) mapped at the title's addresses (VICTORY_PORT_OWNED)" + ); + } else { + tracing::info!( + base = format_args!("{base:#x}"), + bytes, + "renderer port 1: the 32-bit graphics heap is driver-owned memory (cached GTT) mapped at the title's addresses (VICTORY_PORT_OWNED)" + ); + } + if hands_off() { + tracing::info!("renderer port 1: VICTORY_PORT_OWNED=2: nothing is placed in the driver-owned heap, the card gets copies of it as without the port"); + } + OWNED.lock().unwrap_or_else(|e| e.into_inner()).insert(base, o); + true + } + Err(why) => { + tracing::warn!(base = format_args!("{base:#x}"), bytes, why, "renderer port 1: the heap not driver-owned, opened in place as before"); + false + } + } +} + +fn make(base: usize, bytes: usize) -> Result<Owned, String> { + let device = &crate::host::host().ok_or("no host device")?.device; + // Cached system memory (vkd3d: cached GTT), or the card's own behind the BAR ([`vram`]). + let (cpu, pool) = if vram() { (D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE, D3D12_MEMORY_POOL_L1) } else { (D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, D3D12_MEMORY_POOL_L0) }; + let desc = D3D12_HEAP_DESC { + SizeInBytes: bytes as u64, + Properties: D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_CUSTOM, + CPUPageProperty: cpu, + MemoryPoolPreference: pool, + CreationNodeMask: 0, + VisibleNodeMask: 0, + }, + Alignment: 65536, + Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS, + }; + let mut heap: Option<ID3D12Heap> = None; + // SAFETY: plain creation. + unsafe { device.CreateHeap(&desc, &mut heap) }.map_err(|e| format!("CreateHeap: {e}"))?; + let heap = heap.ok_or("CreateHeap: none")?; + let buffer = buffer_desc(bytes); + let mut mapped: Option<ID3D12Resource> = None; + // SAFETY: plain creation in a live heap. + unsafe { device.CreatePlacedResource(&heap, 0, &buffer, D3D12_RESOURCE_STATE_COMMON, None, &mut mapped) }.map_err(|e| format!("CreatePlacedResource: {e}"))?; + let mapped = mapped.ok_or("CreatePlacedResource: none")?; + let mut p: *mut c_void = std::ptr::null_mut(); + // SAFETY: a buffer in a CPU-visible heap. + unsafe { mapped.Map(0, None, Some(&mut p)) }.map_err(|e| format!("Map: {e}"))?; + let p = p as usize; + let (start, end, offset, path) = mapping_of(p).ok_or("the heap's mapping is not in /proc/self/maps (or no raw Linux call from here: Wine's selector byte is not at TEB+0x340)")?; + if !path.starts_with("/dev/dri/") { + return Err(format!("the heap is mapped from {path:?}, not a render node")); + } + if p + bytes > end { + return Err(format!("the driver's mapping {start:#x}-{end:#x} does not hold the heap's {bytes:#x} bytes at {p:#x}")); + } + let offset = offset + (p - start); + let fd = render_fd(&path, offset).ok_or("no render node fd takes the heap's offset")?; + // SAFETY: both are `bytes` long: the title's fresh heap and the driver's. + unsafe { std::ptr::copy_nonoverlapping(base as *const u8, p as *mut u8, bytes) }; + let m = linux(SYS_MMAP, [base, bytes, PROT_RW, MAP_SHARED | MAP_FIXED, fd, offset]).unwrap_or(-1); + if m != base as isize { + // A failed MAP_FIXED leaves the old mapping (the kernel checks before it unmaps). + return Err(format!("mmap over the title's heap: {m}")); + } + // One word each way through the two mappings: the same pages. + // SAFETY: inside both mappings. + unsafe { + let t = base as *mut u32; + let old = t.read_volatile(); + t.write_volatile(0x5a17_c0de); + let seen = (p as *const u32).read_volatile(); + t.write_volatile(old); + if seen != 0x5a17_c0de { + return Err("the title's addresses do not show the driver's pages".into()); + } + } + Ok(Owned { bytes, heap, _mapped: mapped }) +} diff --git a/crates/victory-gpu/src/port.rs b/crates/victory-gpu/src/port.rs index e899cab..d331813 100644 --- a/crates/victory-gpu/src/port.rs +++ b/crates/victory-gpu/src/port.rs @@ -83,6 +83,8 @@ struct Region { start: u64, end: u64, heap: ID3D12Heap, + /// The driver's own heap (`crate::owned`), not one opened on title memory. + owned: bool, } // SAFETY: D3D12 heaps are free-threaded. @@ -165,7 +167,8 @@ pub(crate) fn place_in(device: &ID3D12Device, start: u64, len: u64) -> Result<Pl } }; let region = &regions[i]; - let buffer = crate::inplace::place(device, &region.heap, at - region.start, end - at).map_err(|e| (6, format!("no buffer placed in the region: {e}")))?; + let placed = if region.owned { crate::owned::place } else { crate::inplace::place }; + let buffer = placed(device, &region.heap, at - region.start, end - at).map_err(|e| (6, format!("no buffer placed in the region: {e}")))?; // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at); Ok(Placed { buffer, heap: region.heap.clone(), gpu, bias: start - at }) @@ -257,7 +260,7 @@ fn open_region(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usiz ); // shortcut: the view stays mapped for good (the heap holds its // pages while anything names it). - Ok(Region { start: first, end: first + bytes, heap }) + Ok(Region { start: first, end: first + bytes, heap, owned: false }) } Err(e) => { unmap(); @@ -272,6 +275,16 @@ fn open_region(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usiz /// (`crate::inplace::title_memory_freeing`) and waits for the card before /// it gives the memory up. fn open_private(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usize, String)> { + if let Some((start, end, heap)) = crate::owned::heap_for(at, end) { + // The bisection (`VICTORY_PORT_OWNED=2`): the title's heap is driver memory, the card is given copies. + if crate::owned::hands_off() { + return Err((5, "VICTORY_PORT_OWNED=2: driver memory left to copies".into())); + } + return Ok(Region { start, end, heap, owned: true }); + } + if crate::owned::only() { + return Err((5, "VICTORY_PORT_OWNED_ONLY: private memory outside the driver-owned heap left to copies".into())); + } // SAFETY: plain data filled in by the query. let mut info: mem::MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; // SAFETY: a valid out pointer of the right size. @@ -311,7 +324,7 @@ fn open_private(device: &ID3D12Device, at: u64, end: u64) -> Result<Region, (usi "renderer port 1: a stretch of the title's graphics memory, private memory, opened as a host heap where it is" ); } - Ok(Region { start: first, end: first + bytes, heap }) + Ok(Region { start: first, end: first + bytes, heap, owned: false }) } Err(e) => Err((5, format!("refused by the host: {e}"))), } diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index c15ecfc..72b8fe8 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -2174,6 +2174,8 @@ fn activate(physical: &mut Physical, base: usize, bytes: usize) -> bool { return false; } physical.holes.retain(|&at, _| at < base || at >= end); + // Fresh memory, nothing of the title's in it yet: the moment to back it with the driver's (VICTORY_PORT_OWNED). + victory_gpu::title_memory_owned(base, bytes); victory_gpu::title_memory_allocated(base, bytes); victory_gpu::title_memory_unguarded(base, bytes, true); PRIVATE_REGIONS.lock().unwrap_or_else(|e| e.into_inner()).push(PrivateRegion { base, bytes, refused: false }); -- 2.56.0 From b00b0d03bb7fe4a1154c87f86199ec9b603f786f Mon Sep 17 00:00:00 2001 From: GreemSC <[email protected]> Date: Sun, 29 Nov 2026 21:31:20 +0100 Subject: [PATCH 6/7] shadow: VICTORY_WC_COMMITTED_ONLY=<len>,..: only committed allocations of those sizes stay on the card With every write-combined committed allocation left on the card the title crashed in 4 of 5 runs (n31, n37, n38; it reads some back). Only the 20 MB buffer (allocation 0x1420000): runs n47, n47b, n49, n49b, n50 without a crash. Co-Authored-By: Claude Opus 5.5 <[email protected]> (cherry picked from commit 2a6eb6d8ccaa20c38e4f54bc092981826a4abd3d) --- crates/victory-gpu/src/shadow.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index efffc65..1cfc86d 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2234,6 +2234,23 @@ static COMMITTED: RwLock<Vec<(u64, u64)>> = RwLock::new(Vec::new()); /// `crate::resource`'s `resource_attributes`), in memory the kernel watches /// (`VICTORY_OWN_WATCH`): see [`wc_committed`]. pub fn title_memory_committed(at: usize, len: usize) { + // `VICTORY_WC_COMMITTED_ONLY=<len>[,<len>..]` (bytes, 0x.. or decimal): + // only allocations of those sizes (the 20 MB buffer's is 0x1420000), as + // the title may read others back (runs n37, n38 crashed with all of them). + static ONLY: std::sync::OnceLock<Vec<usize>> = std::sync::OnceLock::new(); + let only = ONLY.get_or_init(|| { + std::env::var("VICTORY_WC_COMMITTED_ONLY") + .unwrap_or_default() + .split(',') + .filter_map(|v| { + let v = v.trim(); + v.strip_prefix("0x").map_or_else(|| v.parse().ok(), |h| usize::from_str_radix(h, 16).ok()) + }) + .collect() + }); + if !only.is_empty() && !only.contains(&len) { + return; + } if len != 0 { COMMITTED.write().unwrap_or_else(|e| e.into_inner()).push((at as u64, at.saturating_add(len) as u64)); } -- 2.56.0 From 3658cae9150d9d53a35b9d45e09aa80c0f37c3aa Mon Sep 17 00:00:00 2001 From: GreemSC <[email protected]> Date: Sun, 29 Nov 2026 21:36:13 +0100 Subject: [PATCH 7/7] shadow: provenance of VICTORY_WC_NO_BACK is readmet3xt-lab/foxhound Co-Authored-By: Claude Opus 5.5 <[email protected]> --- crates/victory-gpu/src/shadow.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 1cfc86d..53b0a32 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -2304,7 +2304,7 @@ fn wc_committed() -> bool { /// write-combined title memory stays on the card and is not compared, /// fetched and merged into title memory (`VICTORY_WC_NO_BACK=1`; off by /// default: an experiment; an A/B switch in diagnostics builds). From -/// fxceless/VIctory-NVIDIA 50c15a1. +/// readmet3xt-lab/foxhound 50c15a1 (also in trustno1-coder/VIctory-NVIDIA). /// /// The write-back of shader writes (`Shadow::gpu_writes`: hashes after /// sends, compare passes after the lists, fetches of the pieces that differ @@ -2335,7 +2335,7 @@ fn wc_no_back() -> bool { /// The smallest copy whose shader writes [`wc_no_back`] leaves on the card, /// in bytes (`VICTORY_WC_NO_BACK_MIN_KB`, 1024 unset; 0: all). With every -/// copy left, upstream's cutscenes went near black (fxceless/VIctory-NVIDIA +/// copy left, upstream's cutscenes went near black (readmet3xt-lab/foxhound /// 2f81d0c: small results the title reads back, such as exposure, came back /// stale; 3,245 write-combined copies there, median 4 KB, 82 of 1 MB or /// more) while most of the saving is in a few ranges of hundreds of MB. -- 2.56.0 ``` </details>
Slaktarn700 commented 2026-11-29 22:01:06 +00:00 (Migrated from github.com)
Author
Contributor

Imported from Slaktarn700/SlaktarnVI. Originally posted by Slaktarn700 on 2026-11-29T22:01:06Z.


Thank you for the careful measurements, the in-run A/B and the follow-up with the crash counts, they are very useful. I have kept your series to read against my current tree; several parts of it have moved since 88abc53, and my tree uses the same write notes in other places. I have not run any of it, and I will not merge it as it is: three of the four runs with all allocations crashed, as you say. If an idea holds up here I will test it on its own, off by default, with credit. I have not yet checked whether my frame has the same cost as yours.

<!-- greyfinch-sync:Slaktarn700/SlaktarnVI:comment:7263335596 --> Imported from [Slaktarn700/SlaktarnVI](https://github.com/Slaktarn700/SlaktarnVI/issues/19#issuecomment-7263335596). Originally posted by [Slaktarn700](https://github.com/Slaktarn700) on 2026-11-29T22:01:06Z. --- Thank you for the careful measurements, the in-run A/B and the follow-up with the crash counts, they are very useful. I have kept your series to read against my current tree; several parts of it have moved since 88abc53, and my tree uses the same write notes in other places. I have not run any of it, and I will not merge it as it is: three of the four runs with all allocations crashed, as you say. If an idea holds up here I will test it on its own, off by default, with credit. I have not yet checked whether my frame has the same cost as yours.
Sign in to join this conversation.
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Slaktarn700/SlaktarnVI#19
No description provided.