Copy-back undoes title writes and can lose shader writes: findings and source patch #690

Open
opened 2026-11-26 03:49:02 +00:00 by github-bot · 1 comment
Owner

@⁠Speartone on GitHub · 2026-11-25 04:34 UTC · original

Source patch and findings. Author: Speartone. Based on c96b4f2; the patch's second half is in the first comment.

copy_back, relay_merge, card_merge and card_merge_relay read a stretch of title memory, merge what shaders changed and write the whole stretch back. Two losses follow, both reproduced with synthetic data on c96b4f2:

  • what the title's threads write in the stretch meanwhile is undone;
  • where another thread guards the block again before the kernel write, it fails silently and what shaders wrote is lost.

With the patch only changed bytes are stored. A store that faults ends at that page. A lock from the read to the store keeps the runtime's mappings and the title's VirtualFree, UnmapViewOfFile and XMemFree out. VICTORY_EXACT_BACK=0 gives the old path.

Based on Marvisak/VIctory#721 and Marvisak/VIctory#1024 (Dufftwt), which cover copy_back; the other three paths exist only in this fork.

Tests (synthetic), this patch on an RTX 5080: victory-gpu 126 and victory-hle 98 pass. The same copy-back code beside a page-write change: victory-gpu 126 on AMD RDNA2; WARP 125, with one failure (depth_bounds_pipeline_...) the base has too; victory-shader 214; stress 0 title writes undone and 0 shader bytes lost (base: 23,709-80,993 and 622-1,460 per path); 34 of 34 mutations that change behaviour caught. Three existing tracker tests now tell the tracker before they unmap.

Cost (Ryzen 7 7700X, 1,000 pieces of 64 KiB): -3 to +33 %; about twice without AVX-512 where changed and unchanged bytes alternate.

Limits: frees by direct system call or inside the host's heaps cannot crash it, but the address can be reused within microseconds. A title exception handler installed ahead of ours sees our store's fault first. Actual GTA VI gameplay has not been tested; whether this affects the missing walls is unknown.

AI-assisted: analysis, code, tests and text by Claude Code (Claude Opus 5.5). No game data.

Patch, part 1 of 2
diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs
index b384328..b3fc6fd 100644
--- a/crates/victory-gpu/src/host.rs
+++ b/crates/victory-gpu/src/host.rs
@@ -2787,6 +2787,12 @@ fn hand_back(back: &[Declared]) {
 }
 
 impl Host {
+    /// The lock under which submissions are prepared, one at a time.
+    #[cfg(test)]
+    pub(crate) fn submission(&self) -> std::sync::MutexGuard<'_, u64> {
+        self.submitted.lock().unwrap_or_else(|e| e.into_inner())
+    }
+
     /// Whether the host runs mesh shaders at shader model 6.6 (translated
     /// mesh shaders need both); logged once.
     pub(crate) fn mesh_shaders(&self) -> bool {
diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs
index db53f11..200c2ee 100644
--- a/crates/victory-gpu/src/lib.rs
+++ b/crates/victory-gpu/src/lib.rs
@@ -38,6 +38,8 @@ pub mod object;
 pub mod pipeline;
 #[cfg(windows)]
 mod primitive;
+#[cfg(windows)]
+mod putback;
 pub mod query;
 pub mod queue;
 pub mod resource;
@@ -62,5 +64,7 @@ pub use host::on_failure;
 pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view};
 #[cfg(windows)]
 pub use watch::{
-    title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write,
+    putting_back as title_memory_putting_back, title_memory_reading, title_memory_releasing,
+    title_memory_remapped, title_memory_remapping,
+    writing as kernel_will_write,
 };
diff --git a/crates/victory-gpu/src/putback.rs b/crates/victory-gpu/src/putback.rs
new file mode 100644
index 0000000..d898f38
--- /dev/null
+++ b/crates/victory-gpu/src/putback.rs
@@ -0,0 +1,665 @@
+//! What shaders wrote, on its way into title memory.
+//!
+//! The copy-back of a submission reads a stretch of title memory, puts the
+//! bytes shaders changed into what it read and writes the result back. The
+//! title's threads run meanwhile. Written back whole, the stretch undoes
+//! whatever they wrote in it since the read: a constant, a pointer, an
+//! entry of a table (upstream issue 721: a title thread's pointer read back
+//! as null, two threads spinning in a hash table). Only the bytes shaders
+//! changed are stored here, so every other byte of the stretch stays the
+//! title's. After upstream's pull request 1024 (Dufftwt), which does so for
+//! `Shadow::copy_back`; here for the relay and for copies in the card's
+//! memory as well.
+//!
+//! A call into the kernel for each run of changed bytes cost over a second
+//! a frame (upstream 721, 1024: scattered writes make thousands of runs a
+//! piece), so the bytes are stored from here, and two things keep that
+//! safe. No question to Windows could: its answer is old when the store
+//! comes.
+//!
+//! - The stores are one routine's ([`put`]), and a fault in it that the
+//!   guards do not answer (`crate::watch`) makes it stop at that page
+//!   instead of ending the process: memory that is unmapped, decommitted or
+//!   read-only by then is left alone, as the kernel's write leaves it.
+//! - [`crate::watch::putting_back`] is held from before title memory is
+//!   read until the bytes are in, and the runtime takes it alone while it
+//!   maps, unmaps or frees title memory: the stretch that is stored into
+//!   shows the memory that was read. (Memory the title gives up by a system
+//!   call the runtime does not take over is covered by the first only.)
+//!
+//! `VICTORY_EXACT_BACK=0` writes stretches whole through the kernel, as
+//! before, and takes no lock.
+
+use std::sync::OnceLock;
+
+use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT;
+
+/// Whether only the bytes shaders changed go back into title memory (on by
+/// default; `VICTORY_EXACT_BACK=0` writes whole stretches, as before).
+pub(crate) fn on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var("VICTORY_EXACT_BACK").map_or(true, |v| v.trim() != "0"))
+}
+
+/// The kernel's page: what a fault leaves out.
+const PAGE: usize = 4096;
+
+// victory_put_changed(to, now, was, end of now) -> where in `now` it ended:
+// stores into `to` each byte of `now` that is not `was`'s, sixteen at a time
+// where all of them differ. victory_put_changed_wide is the same with
+// AVX-512's masked stores (bytes of which some changed and some did not, as
+// floats rewritten by shaders are, cost the first several times as much).
+// Leaves that use no stack and only registers a callee may: wherever their
+// one kind of fault (a store into `to`) happens, the `_out` of each is a way
+// out of it (`stop`).
+std::arch::global_asm!(
+    ".globl victory_put_changed_wide",
+    ".globl victory_put_changed_wide_out",
+    ".p2align 4",
+    "victory_put_changed_wide:",
+    "sub rcx, rdx",
+    "sub r8, rdx",
+    "2:",
+    "mov r10, r9",
+    "sub r10, rdx",
+    "cmp r10, 64",
+    "jb 4f",
+    "vmovdqu64 zmm0, [rdx]",
+    "vpcmpneqb k1, zmm0, [rdx + r8]",
+    "kortestq k1, k1",
+    "jz 3f",
+    "jc 5f",
+    "vmovdqu8 [rdx + rcx]{{k1}}, zmm0",
+    "3:",
+    "add rdx, 64",
+    "jmp 2b",
+    "5:",
+    "vmovdqu64 [rdx + rcx], zmm0",
+    "add rdx, 64",
+    "jmp 2b",
+    // The last 63 at most: what a mask leaves out is not looked at.
+    "4:",
+    "mov r11, -1",
+    "bzhi r11, r11, r10",
+    "kmovq k2, r11",
+    "vmovdqu8 zmm0{{k2}}{{z}}, [rdx]",
+    "vpcmpneqb k1{{k2}}, zmm0, [rdx + r8]",
+    "vmovdqu8 [rdx + rcx]{{k1}}, zmm0",
+    "mov rdx, r9",
+    "victory_put_changed_wide_out:",
+    "vzeroupper",
+    "mov rax, rdx",
+    "ret",
+    ".globl victory_put_changed",
+    ".globl victory_put_changed_out",
+    ".globl victory_put_changed_end",
+    ".p2align 4",
+    "victory_put_changed:",
+    "sub rcx, rdx",
+    "sub r8, rdx",
+    "lea r10, [rdx + 16]",
+    "cmp r10, r9",
+    "ja 4f",
+    // Sixteen bytes: which of them differ?
+    "2:",
+    "movdqu xmm0, [rdx]",
+    "movdqu xmm1, [rdx + r8]",
+    "pcmpeqb xmm1, xmm0",
+    "pmovmskb r10d, xmm1",
+    "xor r10d, 0xffff",
+    "jz 3f",
+    "cmp r10d, 0xffff",
+    "jne 6f",
+    "movdqu [rdx + rcx], xmm0",
+    "3:",
+    "add rdx, 16",
+    "lea r10, [rdx + 16]",
+    "cmp r10, r9",
+    "jbe 2b",
+    // The last fifteen at most, one by one.
+    "4:",
+    "cmp rdx, r9",
+    "jae victory_put_changed_out",
+    "mov al, [rdx]",
+    "cmp al, [rdx + r8]",
+    "je 5f",
+    "mov [rdx + rcx], al",
+    "5:",
+    "inc rdx",
+    "jmp 4b",
+    // Some of the sixteen: each of those.
+    "6:",
+    "bsf r11d, r10d",
+    "add r11, rdx",
+    "mov al, [r11]",
+    "mov [r11 + rcx], al",
+    "lea eax, [r10 - 1]",
+    "and r10d, eax",
+    "jnz 6b",
+    "jmp 3b",
+    "victory_put_changed_out:",
+    "mov rax, rdx",
+    "ret",
+    "victory_put_changed_end:",
+);
+
+unsafe extern "C" {
+    fn victory_put_changed_wide(
+        to: *mut u8,
+        now: *const u8,
+        was: *const u8,
+        end: *const u8,
+    ) -> *const u8;
+    fn victory_put_changed(
+        to: *mut u8,
+        now: *const u8,
+        was: *const u8,
+        end: *const u8,
+    ) -> *const u8;
+    static victory_put_changed_wide_out: u8;
+    static victory_put_changed_out: u8;
+    static victory_put_changed_end: u8;
+}
+
+/// Whether this processor has what `victory_put_changed_wide` uses.
+fn wide() -> bool {
+    static WIDE: OnceLock<bool> = OnceLock::new();
+    *WIDE.get_or_init(|| {
+        is_x86_feature_detected!("avx512f")
+            && is_x86_feature_detected!("avx512bw")
+            && is_x86_feature_detected!("bmi2")
+    })
+}
+
+/// Stores into title memory from `at` on the bytes of `now` that are not
+/// `was`'s, and no other byte: `was` is title memory as it was read, `now`
+/// the same with what shaders wrote put in. Pages that cannot be written
+/// are left alone, from the first byte of them that could not be. Returns
+/// how many.
+pub(crate) fn put(at: usize, now: &[u8], was: &[u8]) -> usize {
+    put_with(wide(), at, now, was)
+}
+
+/// [`put`], by the `wide` routine or the other.
+fn put_with(wide: bool, at: usize, now: &[u8], was: &[u8]) -> usize {
+    assert_eq!(now.len(), was.len());
+    crate::watch::install();
+    let routine = if wide {
+        victory_put_changed_wide
+    } else {
+        victory_put_changed
+    };
+    let (mut from, mut left_out) = (0, 0);
+    while from < now.len() {
+        let n = (PAGE - (at + from) % PAGE).min(now.len() - from);
+        // SAFETY: both slices hold `n` bytes from `from` on, and the
+        // processor has what the routine uses. The destination is title
+        // memory, one page of it or less; if it cannot be written the store
+        // faults, and `stop` ends the routine.
+        unsafe {
+            let (now, was) = (now.as_ptr().add(from), was.as_ptr().add(from));
+            let end = now.add(n);
+            left_out += usize::from(routine((at + from) as *mut u8, now, was, end) < end);
+        }
+        from += n;
+    }
+    left_out
+}
+
+/// An exception nobody answered: if it is the [`put`] routine's, the
+/// routine ends there. Whether it was.
+pub(crate) fn stop(context: &mut CONTEXT) -> bool {
+    // The wide routine, then the other.
+    let (wide, narrow, end) = (
+        victory_put_changed_wide as *const () as u64,
+        victory_put_changed as *const () as u64,
+        &raw const victory_put_changed_end as u64,
+    );
+    if !(wide..end).contains(&context.Rip) {
+        return false;
+    }
+    context.Rip = if context.Rip < narrow {
+        &raw const victory_put_changed_wide_out as u64
+    } else {
+        &raw const victory_put_changed_out as u64
+    };
+    true
+}
+
+/// `merged`, title memory as it was read (`was`) with what shaders wrote
+/// put in, goes back to `at`: the bytes that changed. Their guards are
+/// opened first. Returns the stretch's length, as what is written back is
+/// counted.
+pub(crate) fn back(at: usize, merged: &[u8], was: &[u8]) -> usize {
+    debug_assert!(crate::watch::is_putting_back(), "read and stored in one go");
+    crate::watch::writing(at, merged.len());
+    put(at, merged, was);
+    merged.len()
+}
+
+#[cfg(test)]
+mod tests {
+    use super::{put, put_with};
+    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed};
+    use std::time::Duration;
+    use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE};
+    use windows_sys::Win32::System::Memory::{
+        CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_DECOMMIT, MEM_PRESERVE_PLACEHOLDER,
+        MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, MEM_RESERVE_PLACEHOLDER,
+        MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, MapViewOfFile3, PAGE_GUARD, PAGE_NOACCESS,
+        PAGE_READONLY, PAGE_READWRITE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree,
+        VirtualProtect,
+    };
+    use windows_sys::Win32::System::Threading::GetCurrentProcess;
+
+    const P: usize = 4096;
+    const BLOCK: usize = 64 << 10;
+
+    /// Says stop when it goes, also when a test fails.
+    struct Stop<'a>(&'a AtomicBool);
+    impl Drop for Stop<'_> {
+        fn drop(&mut self) {
+            self.0.store(true, Relaxed);
+        }
+    }
+
+    /// Memory of our own, freed on drop.
+    struct Own(usize);
+    impl Own {
+        fn new(len: usize) -> Own {
+            // SAFETY: a fresh allocation.
+            let at = unsafe {
+                VirtualAlloc(
+                    std::ptr::null(),
+                    len,
+                    MEM_RESERVE | MEM_COMMIT,
+                    PAGE_READWRITE,
+                )
+            } as usize;
+            assert_ne!(at, 0);
+            Own(at)
+        }
+        fn protect(&self, at: usize, len: usize, kind: u32) {
+            let mut old = 0;
+            // SAFETY: pages of ours.
+            assert_ne!(
+                unsafe { VirtualProtect((self.0 + at) as *const _, len, kind, &mut old) },
+                0
+            );
+        }
+        fn peek(&self, at: usize) -> u8 {
+            // SAFETY: the tests ask inside readable pages.
+            unsafe { ((self.0 + at) as *const u8).read_volatile() }
+        }
+    }
+    impl Drop for Own {
+        fn drop(&mut self) {
+            // SAFETY: our allocation.
+            unsafe { VirtualFree(self.0 as *mut _, 0, MEM_RELEASE) };
+        }
+    }
+
+    /// Each routine this processor runs.
+    fn routines() -> impl Iterator<Item = bool> {
+        [false, true]
+            .into_iter()
+            .filter(|&wide| !wide || super::wide())
+    }
+
+    struct Random(u64);
+    impl Random {
+        fn next(&mut self) -> u64 {
+            self.0 ^= self.0 << 13;
+            self.0 ^= self.0 >> 7;
+            self.0 ^= self.0 << 17;
+            self.0
+        }
+    }
+
+    /// Whatever the length, the alignment and the pattern: the bytes that
+    /// differ arrive, and no other byte of the destination changes, though
+    /// all of them are other ones by now.
+    #[test]
+    fn the_bytes_that_differ_are_stored_and_no_other() {
+        let own = Own::new(4 * P);
+        let mut random = Random(0x9e37_79b9_7f4a_7c15);
+        for round in 0..6000usize {
+            let len = if round % 50 == 0 {
+                2 * P + (random.next() % 600) as usize
+            } else {
+                (random.next() % 140) as usize
+            };
+            let shift = P - 70 + (random.next() % 140) as usize;
+            let density = random.next() % 9;
+            let was: Vec<u8> = (0..len).map(|_| random.next() as u8).collect();
+            let mut now = was.clone();
+            let mut i = 0;
+            while i < len {
+                // Runs of changed and of unchanged bytes, short and long.
+                let run = 1 + (random.next() % if density < 3 { 3 } else { 40 }) as usize;
+                if random.next() % 9 < density {
+                    for b in &mut now[i..(i + run).min(len)] {
+                        *b = b.wrapping_add(1 + (random.next() % 255) as u8);
+                    }
+                }
+                i += run;
+            }
+            // The title wrote every byte meanwhile, and around the stretch.
+            let title: Vec<u8> = (0..len + 64).map(|_| random.next() as u8).collect();
+            // SAFETY: inside our pages.
+            let seen = unsafe {
+                std::ptr::copy_nonoverlapping(
+                    title.as_ptr(),
+                    (own.0 + shift - 32) as *mut u8,
+                    title.len(),
+                );
+                assert_eq!(
+                    put_with(round % 2 == 0 && super::wide(), own.0 + shift, &now, &was),
+                    0
+                );
+                std::slice::from_raw_parts((own.0 + shift - 32) as *const u8, title.len())
+            };
+            for (i, &b) in seen.iter().enumerate() {
+                let at = i.wrapping_sub(32);
+                let wanted = if at < len && now[at] != was[at] {
+                    now[at]
+                } else {
+                    title[i]
+                };
+                assert_eq!(
+                    b, wanted,
+                    "byte {i} of round {round}, {len} bytes at {shift:#x}"
+                );
+            }
+        }
+    }
+
+    /// Pages that are decommitted, read-only, not to be touched or guarded
+    /// are left alone, the others get their bytes, wherever in the sixteen
+    /// bytes a page begins.
+    #[test]
+    fn pages_that_cannot_be_written_are_left_alone() {
+        for (shift, wide) in [0usize, 1, 8, 15, 63]
+            .into_iter()
+            .flat_map(|s| routines().map(move |w| (s, w)))
+        {
+            for mixed in [false, true] {
+                let own = Own::new(10 * P);
+                // SAFETY: our pages.
+                assert_ne!(
+                    unsafe { VirtualFree((own.0 + 2 * P) as *mut _, P, MEM_DECOMMIT) },
+                    0
+                );
+                own.protect(4 * P, P, PAGE_READONLY);
+                own.protect(5 * P, P, PAGE_NOACCESS);
+                own.protect(7 * P, P, PAGE_READWRITE | PAGE_GUARD);
+                let len = 9 * P;
+                let was = vec![0u8; len];
+                let now: Vec<u8> = (0..len)
+                    .map(|i| if mixed && i % 2 == 1 { 0 } else { 0x5a })
+                    .collect();
+                assert_eq!(
+                    put_with(wide, own.0 + shift, &now, &was),
+                    4,
+                    "mixed {mixed} shift {shift} wide {wide}"
+                );
+                // Every byte of the others, to the edges of the holes.
+                for page in [0, 1, 3, 6, 8] {
+                    for at in (page * P).max(shift)..(page + 1) * P {
+                        assert_eq!(
+                            own.peek(at),
+                            now[at - shift],
+                            "mixed {mixed} shift {shift} byte {at:#x}"
+                        );
+                    }
+                }
+                assert!(
+                    (4 * P..5 * P).all(|at| own.peek(at) == 0),
+                    "the read-only page"
+                );
+            }
+        }
+    }
+
+    /// Memory that is decommitted, protected and given back by another
+    /// thread while bytes are stored: nothing ends, and what is there when
+    /// the threads rest takes its bytes.
+    #[test]
+    fn memory_that_goes_away_under_the_stores_ends_nothing() {
+        let own = Own::new(16 * P);
+        let stop = AtomicBool::new(false);
+        let left_out = std::thread::scope(|s| {
+            s.spawn(|| {
+                let mut random = Random(77);
+                while !stop.load(Relaxed) {
+                    let at = own.0 + (random.next() % 16) as usize * P;
+                    let mut old = 0;
+                    // SAFETY: pages of ours, which only `put` touches.
+                    unsafe {
+                        match random.next() % 3 {
+                            0 => {
+                                VirtualFree(at as *mut _, P, MEM_DECOMMIT);
+                            }
+                            1 => {
+                                VirtualProtect(at as *const _, P, PAGE_READONLY, &mut old);
+                            }
+                            _ => {
+                                VirtualAlloc(at as *const _, P, MEM_COMMIT, PAGE_READWRITE);
+                                VirtualProtect(at as *const _, P, PAGE_READWRITE, &mut old);
+                            }
+                        }
+                    }
+                }
+            });
+            let _stop = Stop(&stop);
+            let workers: Vec<_> = (0..3u8)
+                .map(|w| {
+                    let at = own.0;
+                    s.spawn(move || {
+                        let was = vec![0u8; 16 * P - 24];
+                        let now: Vec<u8> = (0..was.len())
+                            .map(|i| if i % 3 == 0 { 0 } else { w + 1 })
+                            .collect();
+                        (0..1500)
+                            .map(|i| put_with(i % 2 == 0 && super::wide(), at + 24, &now, &was))
+                            .sum::<usize>()
+                    })
+                })
+                .collect();
+            workers
+                .into_iter()
+                .map(|w| w.join().unwrap())
+                .sum::<usize>()
+        });
+        assert!(left_out > 100, "no page was ever away: {left_out}");
+        // SAFETY: our pages.
+        unsafe {
+            assert!(!VirtualAlloc(own.0 as *const _, 16 * P, MEM_COMMIT, PAGE_READWRITE).is_null());
+        }
+        own.protect(0, 16 * P, PAGE_READWRITE);
+        assert_eq!(put(own.0, &[9; 16 * P], &[0; 16 * P]), 0);
+        assert!((0..16 * P).all(|i| own.peek(i) == 9));
+    }
+
+    /// Two sections shown in turn at one address, changed as the runtime
+    /// changes mappings. What is put back after a read of one goes into
+    /// that one, never into the one shown since.
+    #[test]
+    fn bytes_go_into_the_memory_that_was_read() {
+        if !super::on() {
+            return; // the locks are not taken then
+        }
+        // SAFETY: a placeholder of ours and two sections, the lone views of
+        // which stay until the end of the process.
+        let (at, sections, views) = unsafe {
+            let at = VirtualAlloc2(
+                GetCurrentProcess(),
+                std::ptr::null(),
+                BLOCK,
+                MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
+                PAGE_NOACCESS,
+                std::ptr::null_mut(),
+                0,
+            ) as usize;
+            assert_ne!(at, 0);
+            let sections: [HANDLE; 2] = std::array::from_fn(|_| {
+                CreateFileMappingW(
+                    INVALID_HANDLE_VALUE,
+                    std::ptr::null(),
+                    PAGE_READWRITE,
+                    0,
+                    BLOCK as u32,
+                    std::ptr::null(),
+                )
+            });
+            let views =
+                sections.map(|s| MapViewOfFile(s, FILE_MAP_WRITE, 0, 0, BLOCK).Value as usize);
+            (at, sections, views)
+        };
+        for (which, view) in views.iter().enumerate() {
+            assert_ne!(*view, 0);
+            // SAFETY: our view. Its first byte says which it is.
+            unsafe { (*view as *mut u8).write_volatile(which as u8 + 1) };
+        }
+        let show = |which: usize| {
+            // SAFETY: the placeholder takes the view.
+            let view = unsafe {
+                MapViewOfFile3(
+                    sections[which],
+                    GetCurrentProcess(),
+                    at as *const _,
+                    0,
+                    BLOCK,
+                    MEM_REPLACE_PLACEHOLDER,
+                    PAGE_READWRITE,
+                    std::ptr::null_mut(),
+                    0,
+                )
+            };
+            assert_eq!(view.Value as usize, at);
+        };
+        let hide = || {
+            let view = MEMORY_MAPPED_VIEW_ADDRESS {
+                Value: at as *mut _,
+            };
+            // SAFETY: the view shown there.
+            assert_ne!(
+                unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) },
+                0
+            );
+        };
+        show(0);
+        let (stop, into) = (
+            AtomicBool::new(false),
+            [AtomicUsize::new(0), AtomicUsize::new(0)],
+        );
+        std::thread::scope(|s| {
+            for _ in 0..3 {
+                s.spawn(|| {
+                    let mut title = vec![0u8; BLOCK];
+                    while !stop.load(Relaxed) {
+                        let _shown = crate::watch::putting_back();
+                        assert!(
+                            crate::host::read_into(at as *const u8, &mut title),
+                            "shown while it is read"
+                        );
+                        let was = title.clone();
+                        let which = title[0];
+                        // "The shaders": the number of the memory they saw.
+                        title[4096..8192].fill(which);
+                        assert_eq!(super::back(at, &title, &was), BLOCK);
+                        into[usize::from(which) - 1].fetch_add(1, Relaxed);
+                    }
+                });
+            }
+            let _stop = Stop(&stop);
+            for turn in 0..3000 {
+                let which = turn % 2;
+                let _changing = crate::watch::title_memory_remapping();
+                crate::watch::title_memory_remapped(at, BLOCK);
+                hide();
+                std::hint::spin_loop();
+                show(1 - which);
+                drop(_changing);
+                if turn % 8 == 0 {
+                    std::thread::sleep(Duration::from_micros(50));
+                }
+            }
+        });
+        let into = into.map(|n| n.into_inner());
+        assert!(into[0] > 50 && into[1] > 50, "{into:?}");
+        for (which, view) in views.iter().enumerate() {
+            // SAFETY: our view.
+            let bytes = unsafe { std::slice::from_raw_parts((*view + 4096) as *const u8, 4096) };
+            assert!(
+                bytes.iter().all(|&b| b == which as u8 + 1),
+                "section {which} holds another's bytes: {}",
+                bytes[0]
+            );
+        }
+        crate::watch::title_memory_remapped(at, BLOCK);
+        hide();
+        // SAFETY: our placeholder and sections.
+        unsafe {
+            VirtualFree(at as *mut _, 0, MEM_RELEASE);
+            for section in sections {
+                CloseHandle(section);
+            }
+        }
+    }
+
+    /// Whether `f` comes back: within a fifth of a second if it is to wait,
+    /// within ten if it is not (other tests keep the processor busy).
+    fn returns(within: Duration, f: impl FnOnce() + Send + 'static) -> bool {
+        let (done, came) = std::sync::mpsc::channel();
+        std::thread::spawn(move || {
+            f();
+            let _ = done.send(());
+        });
+        came.recv_timeout(within).is_ok()
+    }
+
+    /// While bytes are on their way, memory is neither mapped nor given up;
+    /// while it is, none set out; and a mapping that waits for a reader of
+    /// title memory keeps nobody from putting bytes back, or a reader that
+    /// waits for such work would wait for good.
+    #[test]
+    fn mapping_and_putting_back_wait_for_each_other_and_nothing_else_does() {
+        if !super::on() {
+            return; // the locks are not taken then
+        }
+        let putting = crate::watch::putting_back();
+        assert!(!returns(Duration::from_millis(200), || drop(
+            crate::watch::title_memory_releasing()
+        )));
+        assert!(!returns(Duration::from_millis(200), || drop(
+            crate::watch::title_memory_remapping()
+        )));
+        drop(putting);
+        assert!(returns(Duration::from_secs(10), || drop(
+            crate::watch::title_memory_releasing()
+        )));
+        assert!(returns(Duration::from_secs(10), || drop(
+            crate::watch::title_memory_remapping()
+        )));
+        let releasing = crate::watch::title_memory_releasing();
+        assert!(!returns(Duration::from_millis(200), || drop(
+            crate::watch::putting_back()
+        )));
+        drop(releasing);
+        let reading = crate::watch::title_memory_reading();
+        assert!(!returns(Duration::from_millis(200), || drop(
+            crate::watch::title_memory_remapping()
+        )));
+        assert!(
+            returns(Duration::from_secs(10), || drop(
+                crate::watch::putting_back()
+            )),
+            "behind a mapping that waits"
+        );
+        drop(reading);
+        assert!(returns(Duration::from_secs(10), || drop(
+            crate::watch::title_memory_remapping()
+        )));
+    }
+}
diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs
index 60089a7..a906a94 100644
--- a/crates/victory-gpu/src/watch.rs
+++ b/crates/victory-gpu/src/watch.rs
@@ -586,6 +586,14 @@ pub fn writing(at: usize, len: usize) {
     crate::descriptor::host::remapped(at, len);
 }
 
+/// How many pages of view memory `[at, at + len)` a host copy's refresh
+/// would find written since the last such question; `None` if the memory is
+/// not a view.
+#[cfg(test)]
+pub(crate) fn title_memory_written_pages(at: usize, len: usize) -> Option<usize> {
+    guard(at, at.saturating_add(len)).map(|pages| pages.len())
+}
+
 /// Held shared by a read of title memory in place, and alone by the runtime
 /// while it changes what title memory shows.
 ///
@@ -601,16 +609,61 @@ pub fn writing(at: usize, len: usize) {
 /// does.
 static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(());
 
+/// Held shared while what shaders wrote is put into title memory, from the
+/// read of title memory on ([`putting_back`]), and alone while title memory
+/// is mapped, unmapped or freed.
+///
+/// Not [`MAPPING`], whose readers wait for other threads' work while they
+/// hold it (a texture's refresh is shared out): the copy-back is such work,
+/// and would wait behind a mapping that waits for its readers. Taken after
+/// `MAPPING` where both are, and whoever holds this one shared waits for
+/// nothing but the guards.
+static PUTTING: std::sync::RwLock<()> = std::sync::RwLock::new(());
+
+/// What a thread holds that puts what shaders wrote into title memory
+/// ([`putting_back`]).
+#[doc(hidden)]
+pub struct PuttingBack(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>);
+
+/// Until what it returns is dropped, the runtime maps, unmaps and frees no
+/// title memory: what is stored into is what was read. Not to be taken
+/// twice by one thread, nor held while waiting for another. (Public for the
+/// runtime's tests.)
+#[doc(hidden)]
+pub fn putting_back() -> PuttingBack {
+    PuttingBack(PUTTING.read().unwrap_or_else(|e| e.into_inner()))
+}
+
+/// Whether some thread holds [`putting_back`].
+pub(crate) fn is_putting_back() -> bool {
+    PUTTING.try_write().is_err()
+}
+
+/// What the runtime holds while the title gives memory up
+/// ([`title_memory_releasing`]).
+pub struct Releasing(#[allow(dead_code)] Option<std::sync::RwLockWriteGuard<'static, ()>>);
+
+/// The title is about to free or unmap memory of its own (its `VirtualFree`,
+/// `UnmapViewOfFile`): until what it returns is dropped, nothing shaders
+/// wrote is on its way into title memory.
+pub fn title_memory_releasing() -> Releasing {
+    Releasing(crate::putback::on().then(|| PUTTING.write().unwrap_or_else(|e| e.into_inner())))
+}
+
 /// What the runtime holds while it changes what title memory shows
 /// ([`title_memory_remapping`]).
-pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>);
+pub struct Remapping(
+    #[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>,
+    #[allow(dead_code)] Releasing,
+);
 
 /// The runtime is about to map, unmap or move physical pages of title
 /// memory: until what it returns is dropped, no read of title memory in
 /// place is under way and none begins ([`title_memory_reading`]). Taken
 /// around the whole change, the unmapping and the mapping again.
 pub fn title_memory_remapping() -> Remapping {
-    Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner()))
+    let changing = MAPPING.write().unwrap_or_else(|e| e.into_inner());
+    Remapping(changing, title_memory_releasing())
 }
 
 /// What a read of title memory in place holds ([`title_memory_reading`]).
@@ -661,8 +714,10 @@ pub fn title_memory_remapped(at: usize, len: usize) {
 
 /// Registers the handler that takes writes to guarded blocks, once, ahead
 /// of the crash reporter's.
-fn install() {
-    use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
+pub(crate) fn install() {
+    use windows_sys::Win32::Foundation::{
+        EXCEPTION_ACCESS_VIOLATION, EXCEPTION_GUARD_PAGE, EXCEPTION_IN_PAGE_ERROR, NTSTATUS,
+    };
     use windows_sys::Win32::System::Diagnostics::Debug::{
         AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH,
         EXCEPTION_POINTERS,
@@ -671,12 +726,23 @@ fn install() {
         // SAFETY: the system passes the exception being dispatched.
         let r = unsafe { &*(*info).ExceptionRecord };
         const WRITE: usize = 1;
-        if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
-            || r.NumberParameters < 2
-            || r.ExceptionInformation[0] != WRITE
-        {
+        if r.NumberParameters < 2 || r.ExceptionInformation[0] != WRITE {
             return EXCEPTION_CONTINUE_SEARCH;
         }
+        // Our own store of what shaders wrote, into memory that cannot be
+        // written: it ends there (`crate::putback`).
+        // SAFETY: the context of the thread the exception is dispatched on.
+        let not_guarded = || match crate::putback::stop(unsafe { &mut *(*info).ContextRecord }) {
+            true => EXCEPTION_CONTINUE_EXECUTION,
+            false => EXCEPTION_CONTINUE_SEARCH,
+        };
+        const GUARD_PAGE: NTSTATUS = EXCEPTION_GUARD_PAGE as NTSTATUS;
+        const IN_PAGE_ERROR: NTSTATUS = EXCEPTION_IN_PAGE_ERROR as NTSTATUS;
+        match r.ExceptionCode {
+            EXCEPTION_ACCESS_VIOLATION => {}
+            GUARD_PAGE | IN_PAGE_ERROR => return not_guarded(),
+            _ => return EXCEPTION_CONTINUE_SEARCH,
+        }
         let at = r.ExceptionInformation[1];
         // Held across both checks: another thread may have opened the block
         // since this one faulted, and a copy may have guarded it again since
@@ -690,7 +756,7 @@ fn install() {
         if writable(at) {
             EXCEPTION_CONTINUE_EXECUTION
         } else {
-            EXCEPTION_CONTINUE_SEARCH
+            not_guarded()
         }
     }
     static ONCE: std::sync::Once = std::sync::Once::new();
@@ -801,6 +867,9 @@ mod tests {
             guard(view, view + 2 * BLOCK),
             Some((view / PAGE..view / PAGE + 1).collect())
         );
+        // Told first, as the runtime does: once the view is gone another
+        // test's may come at its address.
+        title_memory_remapped(view, 2 * BLOCK);
         // SAFETY: our view.
         unsafe {
             UnmapViewOfFile(
@@ -809,7 +878,6 @@ mod tests {
                 },
             )
         };
-        title_memory_remapped(view, 2 * BLOCK);
     }
 
     #[test]
@@ -950,6 +1018,7 @@ mod tests {
         let mut local = [0u8; 16];
         let at = local.as_mut_ptr() as usize;
         assert!(!is_view(at, at + local.len()));
+        title_memory_remapped(p, 3 * BLOCK);
         // SAFETY: our views and placeholder.
         unsafe {
             UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
@@ -959,7 +1028,6 @@ mod tests {
             }
             windows_sys::Win32::Foundation::CloseHandle(section);
         }
-        title_memory_remapped(p, 3 * BLOCK);
     }
 
     /// Blocks of a placeholder between views are reported once, then not
@@ -1034,6 +1102,7 @@ mod tests {
         title_memory_remapped(p + BLOCK, BLOCK);
         assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect()));
         assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new()));
+        title_memory_remapped(p, 3 * BLOCK);
         // SAFETY: our views and placeholder.
         unsafe {
             UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER);
@@ -1043,7 +1112,6 @@ mod tests {
             }
             windows_sys::Win32::Foundation::CloseHandle(section);
         }
-        title_memory_remapped(p, 3 * BLOCK);
     }
 
     /// A write or mapping that runs past the end of the address space (a

🤖 Generated with Claude Code

**@⁠Speartone** on GitHub · 2026-11-25 04:34 UTC · [original](https://github.com/fxceless/victory-fork/issues/690) Source patch and findings. Author: Speartone. Based on `c96b4f2`; the patch's second half is in the first comment. `copy_back`, `relay_merge`, `card_merge` and `card_merge_relay` read a stretch of title memory, merge what shaders changed and write the whole stretch back. Two losses follow, both reproduced with synthetic data on c96b4f2: - what the title's threads write in the stretch meanwhile is undone; - where another thread guards the block again before the kernel write, it fails silently and what shaders wrote is lost. With the patch only changed bytes are stored. A store that faults ends at that page. A lock from the read to the store keeps the runtime's mappings and the title's VirtualFree, UnmapViewOfFile and XMemFree out. `VICTORY_EXACT_BACK=0` gives the old path. Based on Marvisak/VIctory#721 and Marvisak/VIctory#1024 (Dufftwt), which cover copy_back; the other three paths exist only in this fork. **Tests (synthetic)**, this patch on an RTX 5080: victory-gpu 126 and victory-hle 98 pass. The same copy-back code beside a page-write change: victory-gpu 126 on AMD RDNA2; WARP 125, with one failure (`depth_bounds_pipeline_...`) the base has too; victory-shader 214; stress 0 title writes undone and 0 shader bytes lost (base: 23,709-80,993 and 622-1,460 per path); 34 of 34 mutations that change behaviour caught. Three existing tracker tests now tell the tracker before they unmap. **Cost** (Ryzen 7 7700X, 1,000 pieces of 64 KiB): -3 to +33 %; about twice without AVX-512 where changed and unchanged bytes alternate. **Limits:** frees by direct system call or inside the host's heaps cannot crash it, but the address can be reused within microseconds. A title exception handler installed ahead of ours sees our store's fault first. Actual GTA VI gameplay has not been tested; whether this affects the missing walls is unknown. AI-assisted: analysis, code, tests and text by Claude Code (Claude Opus 5.5). No game data. <details><summary>Patch, part 1 of 2</summary> ````diff diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index b384328..b3fc6fd 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -2787,6 +2787,12 @@ fn hand_back(back: &[Declared]) { } impl Host { + /// The lock under which submissions are prepared, one at a time. + #[cfg(test)] + pub(crate) fn submission(&self) -> std::sync::MutexGuard<'_, u64> { + self.submitted.lock().unwrap_or_else(|e| e.into_inner()) + } + /// Whether the host runs mesh shaders at shader model 6.6 (translated /// mesh shaders need both); logged once. pub(crate) fn mesh_shaders(&self) -> bool { diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index db53f11..200c2ee 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -38,6 +38,8 @@ pub mod object; pub mod pipeline; #[cfg(windows)] mod primitive; +#[cfg(windows)] +mod putback; pub mod query; pub mod queue; pub mod resource; @@ -62,5 +64,7 @@ pub use host::on_failure; pub use inplace::{title_memory_freeing, title_memory_section, title_memory_view}; #[cfg(windows)] pub use watch::{ - title_memory_reading, title_memory_remapped, title_memory_remapping, writing as kernel_will_write, + putting_back as title_memory_putting_back, title_memory_reading, title_memory_releasing, + title_memory_remapped, title_memory_remapping, + writing as kernel_will_write, }; diff --git a/crates/victory-gpu/src/putback.rs b/crates/victory-gpu/src/putback.rs new file mode 100644 index 0000000..d898f38 --- /dev/null +++ b/crates/victory-gpu/src/putback.rs @@ -0,0 +1,665 @@ +//! What shaders wrote, on its way into title memory. +//! +//! The copy-back of a submission reads a stretch of title memory, puts the +//! bytes shaders changed into what it read and writes the result back. The +//! title's threads run meanwhile. Written back whole, the stretch undoes +//! whatever they wrote in it since the read: a constant, a pointer, an +//! entry of a table (upstream issue 721: a title thread's pointer read back +//! as null, two threads spinning in a hash table). Only the bytes shaders +//! changed are stored here, so every other byte of the stretch stays the +//! title's. After upstream's pull request 1024 (Dufftwt), which does so for +//! `Shadow::copy_back`; here for the relay and for copies in the card's +//! memory as well. +//! +//! A call into the kernel for each run of changed bytes cost over a second +//! a frame (upstream 721, 1024: scattered writes make thousands of runs a +//! piece), so the bytes are stored from here, and two things keep that +//! safe. No question to Windows could: its answer is old when the store +//! comes. +//! +//! - The stores are one routine's ([`put`]), and a fault in it that the +//! guards do not answer (`crate::watch`) makes it stop at that page +//! instead of ending the process: memory that is unmapped, decommitted or +//! read-only by then is left alone, as the kernel's write leaves it. +//! - [`crate::watch::putting_back`] is held from before title memory is +//! read until the bytes are in, and the runtime takes it alone while it +//! maps, unmaps or frees title memory: the stretch that is stored into +//! shows the memory that was read. (Memory the title gives up by a system +//! call the runtime does not take over is covered by the first only.) +//! +//! `VICTORY_EXACT_BACK=0` writes stretches whole through the kernel, as +//! before, and takes no lock. + +use std::sync::OnceLock; + +use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT; + +/// Whether only the bytes shaders changed go back into title memory (on by +/// default; `VICTORY_EXACT_BACK=0` writes whole stretches, as before). +pub(crate) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var("VICTORY_EXACT_BACK").map_or(true, |v| v.trim() != "0")) +} + +/// The kernel's page: what a fault leaves out. +const PAGE: usize = 4096; + +// victory_put_changed(to, now, was, end of now) -> where in `now` it ended: +// stores into `to` each byte of `now` that is not `was`'s, sixteen at a time +// where all of them differ. victory_put_changed_wide is the same with +// AVX-512's masked stores (bytes of which some changed and some did not, as +// floats rewritten by shaders are, cost the first several times as much). +// Leaves that use no stack and only registers a callee may: wherever their +// one kind of fault (a store into `to`) happens, the `_out` of each is a way +// out of it (`stop`). +std::arch::global_asm!( + ".globl victory_put_changed_wide", + ".globl victory_put_changed_wide_out", + ".p2align 4", + "victory_put_changed_wide:", + "sub rcx, rdx", + "sub r8, rdx", + "2:", + "mov r10, r9", + "sub r10, rdx", + "cmp r10, 64", + "jb 4f", + "vmovdqu64 zmm0, [rdx]", + "vpcmpneqb k1, zmm0, [rdx + r8]", + "kortestq k1, k1", + "jz 3f", + "jc 5f", + "vmovdqu8 [rdx + rcx]{{k1}}, zmm0", + "3:", + "add rdx, 64", + "jmp 2b", + "5:", + "vmovdqu64 [rdx + rcx], zmm0", + "add rdx, 64", + "jmp 2b", + // The last 63 at most: what a mask leaves out is not looked at. + "4:", + "mov r11, -1", + "bzhi r11, r11, r10", + "kmovq k2, r11", + "vmovdqu8 zmm0{{k2}}{{z}}, [rdx]", + "vpcmpneqb k1{{k2}}, zmm0, [rdx + r8]", + "vmovdqu8 [rdx + rcx]{{k1}}, zmm0", + "mov rdx, r9", + "victory_put_changed_wide_out:", + "vzeroupper", + "mov rax, rdx", + "ret", + ".globl victory_put_changed", + ".globl victory_put_changed_out", + ".globl victory_put_changed_end", + ".p2align 4", + "victory_put_changed:", + "sub rcx, rdx", + "sub r8, rdx", + "lea r10, [rdx + 16]", + "cmp r10, r9", + "ja 4f", + // Sixteen bytes: which of them differ? + "2:", + "movdqu xmm0, [rdx]", + "movdqu xmm1, [rdx + r8]", + "pcmpeqb xmm1, xmm0", + "pmovmskb r10d, xmm1", + "xor r10d, 0xffff", + "jz 3f", + "cmp r10d, 0xffff", + "jne 6f", + "movdqu [rdx + rcx], xmm0", + "3:", + "add rdx, 16", + "lea r10, [rdx + 16]", + "cmp r10, r9", + "jbe 2b", + // The last fifteen at most, one by one. + "4:", + "cmp rdx, r9", + "jae victory_put_changed_out", + "mov al, [rdx]", + "cmp al, [rdx + r8]", + "je 5f", + "mov [rdx + rcx], al", + "5:", + "inc rdx", + "jmp 4b", + // Some of the sixteen: each of those. + "6:", + "bsf r11d, r10d", + "add r11, rdx", + "mov al, [r11]", + "mov [r11 + rcx], al", + "lea eax, [r10 - 1]", + "and r10d, eax", + "jnz 6b", + "jmp 3b", + "victory_put_changed_out:", + "mov rax, rdx", + "ret", + "victory_put_changed_end:", +); + +unsafe extern "C" { + fn victory_put_changed_wide( + to: *mut u8, + now: *const u8, + was: *const u8, + end: *const u8, + ) -> *const u8; + fn victory_put_changed( + to: *mut u8, + now: *const u8, + was: *const u8, + end: *const u8, + ) -> *const u8; + static victory_put_changed_wide_out: u8; + static victory_put_changed_out: u8; + static victory_put_changed_end: u8; +} + +/// Whether this processor has what `victory_put_changed_wide` uses. +fn wide() -> bool { + static WIDE: OnceLock<bool> = OnceLock::new(); + *WIDE.get_or_init(|| { + is_x86_feature_detected!("avx512f") + && is_x86_feature_detected!("avx512bw") + && is_x86_feature_detected!("bmi2") + }) +} + +/// Stores into title memory from `at` on the bytes of `now` that are not +/// `was`'s, and no other byte: `was` is title memory as it was read, `now` +/// the same with what shaders wrote put in. Pages that cannot be written +/// are left alone, from the first byte of them that could not be. Returns +/// how many. +pub(crate) fn put(at: usize, now: &[u8], was: &[u8]) -> usize { + put_with(wide(), at, now, was) +} + +/// [`put`], by the `wide` routine or the other. +fn put_with(wide: bool, at: usize, now: &[u8], was: &[u8]) -> usize { + assert_eq!(now.len(), was.len()); + crate::watch::install(); + let routine = if wide { + victory_put_changed_wide + } else { + victory_put_changed + }; + let (mut from, mut left_out) = (0, 0); + while from < now.len() { + let n = (PAGE - (at + from) % PAGE).min(now.len() - from); + // SAFETY: both slices hold `n` bytes from `from` on, and the + // processor has what the routine uses. The destination is title + // memory, one page of it or less; if it cannot be written the store + // faults, and `stop` ends the routine. + unsafe { + let (now, was) = (now.as_ptr().add(from), was.as_ptr().add(from)); + let end = now.add(n); + left_out += usize::from(routine((at + from) as *mut u8, now, was, end) < end); + } + from += n; + } + left_out +} + +/// An exception nobody answered: if it is the [`put`] routine's, the +/// routine ends there. Whether it was. +pub(crate) fn stop(context: &mut CONTEXT) -> bool { + // The wide routine, then the other. + let (wide, narrow, end) = ( + victory_put_changed_wide as *const () as u64, + victory_put_changed as *const () as u64, + &raw const victory_put_changed_end as u64, + ); + if !(wide..end).contains(&context.Rip) { + return false; + } + context.Rip = if context.Rip < narrow { + &raw const victory_put_changed_wide_out as u64 + } else { + &raw const victory_put_changed_out as u64 + }; + true +} + +/// `merged`, title memory as it was read (`was`) with what shaders wrote +/// put in, goes back to `at`: the bytes that changed. Their guards are +/// opened first. Returns the stretch's length, as what is written back is +/// counted. +pub(crate) fn back(at: usize, merged: &[u8], was: &[u8]) -> usize { + debug_assert!(crate::watch::is_putting_back(), "read and stored in one go"); + crate::watch::writing(at, merged.len()); + put(at, merged, was); + merged.len() +} + +#[cfg(test)] +mod tests { + use super::{put, put_with}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed}; + use std::time::Duration; + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_DECOMMIT, MEM_PRESERVE_PLACEHOLDER, + MEM_RELEASE, MEM_REPLACE_PLACEHOLDER, MEM_RESERVE, MEM_RESERVE_PLACEHOLDER, + MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, MapViewOfFile3, PAGE_GUARD, PAGE_NOACCESS, + PAGE_READONLY, PAGE_READWRITE, UnmapViewOfFile2, VirtualAlloc, VirtualAlloc2, VirtualFree, + VirtualProtect, + }; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + + const P: usize = 4096; + const BLOCK: usize = 64 << 10; + + /// Says stop when it goes, also when a test fails. + struct Stop<'a>(&'a AtomicBool); + impl Drop for Stop<'_> { + fn drop(&mut self) { + self.0.store(true, Relaxed); + } + } + + /// Memory of our own, freed on drop. + struct Own(usize); + impl Own { + fn new(len: usize) -> Own { + // SAFETY: a fresh allocation. + let at = unsafe { + VirtualAlloc( + std::ptr::null(), + len, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ) + } as usize; + assert_ne!(at, 0); + Own(at) + } + fn protect(&self, at: usize, len: usize, kind: u32) { + let mut old = 0; + // SAFETY: pages of ours. + assert_ne!( + unsafe { VirtualProtect((self.0 + at) as *const _, len, kind, &mut old) }, + 0 + ); + } + fn peek(&self, at: usize) -> u8 { + // SAFETY: the tests ask inside readable pages. + unsafe { ((self.0 + at) as *const u8).read_volatile() } + } + } + impl Drop for Own { + fn drop(&mut self) { + // SAFETY: our allocation. + unsafe { VirtualFree(self.0 as *mut _, 0, MEM_RELEASE) }; + } + } + + /// Each routine this processor runs. + fn routines() -> impl Iterator<Item = bool> { + [false, true] + .into_iter() + .filter(|&wide| !wide || super::wide()) + } + + struct Random(u64); + impl Random { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + } + + /// Whatever the length, the alignment and the pattern: the bytes that + /// differ arrive, and no other byte of the destination changes, though + /// all of them are other ones by now. + #[test] + fn the_bytes_that_differ_are_stored_and_no_other() { + let own = Own::new(4 * P); + let mut random = Random(0x9e37_79b9_7f4a_7c15); + for round in 0..6000usize { + let len = if round % 50 == 0 { + 2 * P + (random.next() % 600) as usize + } else { + (random.next() % 140) as usize + }; + let shift = P - 70 + (random.next() % 140) as usize; + let density = random.next() % 9; + let was: Vec<u8> = (0..len).map(|_| random.next() as u8).collect(); + let mut now = was.clone(); + let mut i = 0; + while i < len { + // Runs of changed and of unchanged bytes, short and long. + let run = 1 + (random.next() % if density < 3 { 3 } else { 40 }) as usize; + if random.next() % 9 < density { + for b in &mut now[i..(i + run).min(len)] { + *b = b.wrapping_add(1 + (random.next() % 255) as u8); + } + } + i += run; + } + // The title wrote every byte meanwhile, and around the stretch. + let title: Vec<u8> = (0..len + 64).map(|_| random.next() as u8).collect(); + // SAFETY: inside our pages. + let seen = unsafe { + std::ptr::copy_nonoverlapping( + title.as_ptr(), + (own.0 + shift - 32) as *mut u8, + title.len(), + ); + assert_eq!( + put_with(round % 2 == 0 && super::wide(), own.0 + shift, &now, &was), + 0 + ); + std::slice::from_raw_parts((own.0 + shift - 32) as *const u8, title.len()) + }; + for (i, &b) in seen.iter().enumerate() { + let at = i.wrapping_sub(32); + let wanted = if at < len && now[at] != was[at] { + now[at] + } else { + title[i] + }; + assert_eq!( + b, wanted, + "byte {i} of round {round}, {len} bytes at {shift:#x}" + ); + } + } + } + + /// Pages that are decommitted, read-only, not to be touched or guarded + /// are left alone, the others get their bytes, wherever in the sixteen + /// bytes a page begins. + #[test] + fn pages_that_cannot_be_written_are_left_alone() { + for (shift, wide) in [0usize, 1, 8, 15, 63] + .into_iter() + .flat_map(|s| routines().map(move |w| (s, w))) + { + for mixed in [false, true] { + let own = Own::new(10 * P); + // SAFETY: our pages. + assert_ne!( + unsafe { VirtualFree((own.0 + 2 * P) as *mut _, P, MEM_DECOMMIT) }, + 0 + ); + own.protect(4 * P, P, PAGE_READONLY); + own.protect(5 * P, P, PAGE_NOACCESS); + own.protect(7 * P, P, PAGE_READWRITE | PAGE_GUARD); + let len = 9 * P; + let was = vec![0u8; len]; + let now: Vec<u8> = (0..len) + .map(|i| if mixed && i % 2 == 1 { 0 } else { 0x5a }) + .collect(); + assert_eq!( + put_with(wide, own.0 + shift, &now, &was), + 4, + "mixed {mixed} shift {shift} wide {wide}" + ); + // Every byte of the others, to the edges of the holes. + for page in [0, 1, 3, 6, 8] { + for at in (page * P).max(shift)..(page + 1) * P { + assert_eq!( + own.peek(at), + now[at - shift], + "mixed {mixed} shift {shift} byte {at:#x}" + ); + } + } + assert!( + (4 * P..5 * P).all(|at| own.peek(at) == 0), + "the read-only page" + ); + } + } + } + + /// Memory that is decommitted, protected and given back by another + /// thread while bytes are stored: nothing ends, and what is there when + /// the threads rest takes its bytes. + #[test] + fn memory_that_goes_away_under_the_stores_ends_nothing() { + let own = Own::new(16 * P); + let stop = AtomicBool::new(false); + let left_out = std::thread::scope(|s| { + s.spawn(|| { + let mut random = Random(77); + while !stop.load(Relaxed) { + let at = own.0 + (random.next() % 16) as usize * P; + let mut old = 0; + // SAFETY: pages of ours, which only `put` touches. + unsafe { + match random.next() % 3 { + 0 => { + VirtualFree(at as *mut _, P, MEM_DECOMMIT); + } + 1 => { + VirtualProtect(at as *const _, P, PAGE_READONLY, &mut old); + } + _ => { + VirtualAlloc(at as *const _, P, MEM_COMMIT, PAGE_READWRITE); + VirtualProtect(at as *const _, P, PAGE_READWRITE, &mut old); + } + } + } + } + }); + let _stop = Stop(&stop); + let workers: Vec<_> = (0..3u8) + .map(|w| { + let at = own.0; + s.spawn(move || { + let was = vec![0u8; 16 * P - 24]; + let now: Vec<u8> = (0..was.len()) + .map(|i| if i % 3 == 0 { 0 } else { w + 1 }) + .collect(); + (0..1500) + .map(|i| put_with(i % 2 == 0 && super::wide(), at + 24, &now, &was)) + .sum::<usize>() + }) + }) + .collect(); + workers + .into_iter() + .map(|w| w.join().unwrap()) + .sum::<usize>() + }); + assert!(left_out > 100, "no page was ever away: {left_out}"); + // SAFETY: our pages. + unsafe { + assert!(!VirtualAlloc(own.0 as *const _, 16 * P, MEM_COMMIT, PAGE_READWRITE).is_null()); + } + own.protect(0, 16 * P, PAGE_READWRITE); + assert_eq!(put(own.0, &[9; 16 * P], &[0; 16 * P]), 0); + assert!((0..16 * P).all(|i| own.peek(i) == 9)); + } + + /// Two sections shown in turn at one address, changed as the runtime + /// changes mappings. What is put back after a read of one goes into + /// that one, never into the one shown since. + #[test] + fn bytes_go_into_the_memory_that_was_read() { + if !super::on() { + return; // the locks are not taken then + } + // SAFETY: a placeholder of ours and two sections, the lone views of + // which stay until the end of the process. + let (at, sections, views) = unsafe { + let at = VirtualAlloc2( + GetCurrentProcess(), + std::ptr::null(), + BLOCK, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) as usize; + assert_ne!(at, 0); + let sections: [HANDLE; 2] = std::array::from_fn(|_| { + CreateFileMappingW( + INVALID_HANDLE_VALUE, + std::ptr::null(), + PAGE_READWRITE, + 0, + BLOCK as u32, + std::ptr::null(), + ) + }); + let views = + sections.map(|s| MapViewOfFile(s, FILE_MAP_WRITE, 0, 0, BLOCK).Value as usize); + (at, sections, views) + }; + for (which, view) in views.iter().enumerate() { + assert_ne!(*view, 0); + // SAFETY: our view. Its first byte says which it is. + unsafe { (*view as *mut u8).write_volatile(which as u8 + 1) }; + } + let show = |which: usize| { + // SAFETY: the placeholder takes the view. + let view = unsafe { + MapViewOfFile3( + sections[which], + GetCurrentProcess(), + at as *const _, + 0, + BLOCK, + MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ) + }; + assert_eq!(view.Value as usize, at); + }; + let hide = || { + let view = MEMORY_MAPPED_VIEW_ADDRESS { + Value: at as *mut _, + }; + // SAFETY: the view shown there. + assert_ne!( + unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }, + 0 + ); + }; + show(0); + let (stop, into) = ( + AtomicBool::new(false), + [AtomicUsize::new(0), AtomicUsize::new(0)], + ); + std::thread::scope(|s| { + for _ in 0..3 { + s.spawn(|| { + let mut title = vec![0u8; BLOCK]; + while !stop.load(Relaxed) { + let _shown = crate::watch::putting_back(); + assert!( + crate::host::read_into(at as *const u8, &mut title), + "shown while it is read" + ); + let was = title.clone(); + let which = title[0]; + // "The shaders": the number of the memory they saw. + title[4096..8192].fill(which); + assert_eq!(super::back(at, &title, &was), BLOCK); + into[usize::from(which) - 1].fetch_add(1, Relaxed); + } + }); + } + let _stop = Stop(&stop); + for turn in 0..3000 { + let which = turn % 2; + let _changing = crate::watch::title_memory_remapping(); + crate::watch::title_memory_remapped(at, BLOCK); + hide(); + std::hint::spin_loop(); + show(1 - which); + drop(_changing); + if turn % 8 == 0 { + std::thread::sleep(Duration::from_micros(50)); + } + } + }); + let into = into.map(|n| n.into_inner()); + assert!(into[0] > 50 && into[1] > 50, "{into:?}"); + for (which, view) in views.iter().enumerate() { + // SAFETY: our view. + let bytes = unsafe { std::slice::from_raw_parts((*view + 4096) as *const u8, 4096) }; + assert!( + bytes.iter().all(|&b| b == which as u8 + 1), + "section {which} holds another's bytes: {}", + bytes[0] + ); + } + crate::watch::title_memory_remapped(at, BLOCK); + hide(); + // SAFETY: our placeholder and sections. + unsafe { + VirtualFree(at as *mut _, 0, MEM_RELEASE); + for section in sections { + CloseHandle(section); + } + } + } + + /// Whether `f` comes back: within a fifth of a second if it is to wait, + /// within ten if it is not (other tests keep the processor busy). + fn returns(within: Duration, f: impl FnOnce() + Send + 'static) -> bool { + let (done, came) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + f(); + let _ = done.send(()); + }); + came.recv_timeout(within).is_ok() + } + + /// While bytes are on their way, memory is neither mapped nor given up; + /// while it is, none set out; and a mapping that waits for a reader of + /// title memory keeps nobody from putting bytes back, or a reader that + /// waits for such work would wait for good. + #[test] + fn mapping_and_putting_back_wait_for_each_other_and_nothing_else_does() { + if !super::on() { + return; // the locks are not taken then + } + let putting = crate::watch::putting_back(); + assert!(!returns(Duration::from_millis(200), || drop( + crate::watch::title_memory_releasing() + ))); + assert!(!returns(Duration::from_millis(200), || drop( + crate::watch::title_memory_remapping() + ))); + drop(putting); + assert!(returns(Duration::from_secs(10), || drop( + crate::watch::title_memory_releasing() + ))); + assert!(returns(Duration::from_secs(10), || drop( + crate::watch::title_memory_remapping() + ))); + let releasing = crate::watch::title_memory_releasing(); + assert!(!returns(Duration::from_millis(200), || drop( + crate::watch::putting_back() + ))); + drop(releasing); + let reading = crate::watch::title_memory_reading(); + assert!(!returns(Duration::from_millis(200), || drop( + crate::watch::title_memory_remapping() + ))); + assert!( + returns(Duration::from_secs(10), || drop( + crate::watch::putting_back() + )), + "behind a mapping that waits" + ); + drop(reading); + assert!(returns(Duration::from_secs(10), || drop( + crate::watch::title_memory_remapping() + ))); + } +} diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 60089a7..a906a94 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -586,6 +586,14 @@ pub fn writing(at: usize, len: usize) { crate::descriptor::host::remapped(at, len); } +/// How many pages of view memory `[at, at + len)` a host copy's refresh +/// would find written since the last such question; `None` if the memory is +/// not a view. +#[cfg(test)] +pub(crate) fn title_memory_written_pages(at: usize, len: usize) -> Option<usize> { + guard(at, at.saturating_add(len)).map(|pages| pages.len()) +} + /// Held shared by a read of title memory in place, and alone by the runtime /// while it changes what title memory shows. /// @@ -601,16 +609,61 @@ pub fn writing(at: usize, len: usize) { /// does. static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); +/// Held shared while what shaders wrote is put into title memory, from the +/// read of title memory on ([`putting_back`]), and alone while title memory +/// is mapped, unmapped or freed. +/// +/// Not [`MAPPING`], whose readers wait for other threads' work while they +/// hold it (a texture's refresh is shared out): the copy-back is such work, +/// and would wait behind a mapping that waits for its readers. Taken after +/// `MAPPING` where both are, and whoever holds this one shared waits for +/// nothing but the guards. +static PUTTING: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +/// What a thread holds that puts what shaders wrote into title memory +/// ([`putting_back`]). +#[doc(hidden)] +pub struct PuttingBack(#[allow(dead_code)] std::sync::RwLockReadGuard<'static, ()>); + +/// Until what it returns is dropped, the runtime maps, unmaps and frees no +/// title memory: what is stored into is what was read. Not to be taken +/// twice by one thread, nor held while waiting for another. (Public for the +/// runtime's tests.) +#[doc(hidden)] +pub fn putting_back() -> PuttingBack { + PuttingBack(PUTTING.read().unwrap_or_else(|e| e.into_inner())) +} + +/// Whether some thread holds [`putting_back`]. +pub(crate) fn is_putting_back() -> bool { + PUTTING.try_write().is_err() +} + +/// What the runtime holds while the title gives memory up +/// ([`title_memory_releasing`]). +pub struct Releasing(#[allow(dead_code)] Option<std::sync::RwLockWriteGuard<'static, ()>>); + +/// The title is about to free or unmap memory of its own (its `VirtualFree`, +/// `UnmapViewOfFile`): until what it returns is dropped, nothing shaders +/// wrote is on its way into title memory. +pub fn title_memory_releasing() -> Releasing { + Releasing(crate::putback::on().then(|| PUTTING.write().unwrap_or_else(|e| e.into_inner()))) +} + /// What the runtime holds while it changes what title memory shows /// ([`title_memory_remapping`]). -pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>); +pub struct Remapping( + #[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>, + #[allow(dead_code)] Releasing, +); /// The runtime is about to map, unmap or move physical pages of title /// memory: until what it returns is dropped, no read of title memory in /// place is under way and none begins ([`title_memory_reading`]). Taken /// around the whole change, the unmapping and the mapping again. pub fn title_memory_remapping() -> Remapping { - Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner())) + let changing = MAPPING.write().unwrap_or_else(|e| e.into_inner()); + Remapping(changing, title_memory_releasing()) } /// What a read of title memory in place holds ([`title_memory_reading`]). @@ -661,8 +714,10 @@ pub fn title_memory_remapped(at: usize, len: usize) { /// Registers the handler that takes writes to guarded blocks, once, ahead /// of the crash reporter's. -fn install() { - use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +pub(crate) fn install() { + use windows_sys::Win32::Foundation::{ + EXCEPTION_ACCESS_VIOLATION, EXCEPTION_GUARD_PAGE, EXCEPTION_IN_PAGE_ERROR, NTSTATUS, + }; use windows_sys::Win32::System::Diagnostics::Debug::{ AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, @@ -671,12 +726,23 @@ fn install() { // SAFETY: the system passes the exception being dispatched. let r = unsafe { &*(*info).ExceptionRecord }; const WRITE: usize = 1; - if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS - || r.NumberParameters < 2 - || r.ExceptionInformation[0] != WRITE - { + if r.NumberParameters < 2 || r.ExceptionInformation[0] != WRITE { return EXCEPTION_CONTINUE_SEARCH; } + // Our own store of what shaders wrote, into memory that cannot be + // written: it ends there (`crate::putback`). + // SAFETY: the context of the thread the exception is dispatched on. + let not_guarded = || match crate::putback::stop(unsafe { &mut *(*info).ContextRecord }) { + true => EXCEPTION_CONTINUE_EXECUTION, + false => EXCEPTION_CONTINUE_SEARCH, + }; + const GUARD_PAGE: NTSTATUS = EXCEPTION_GUARD_PAGE as NTSTATUS; + const IN_PAGE_ERROR: NTSTATUS = EXCEPTION_IN_PAGE_ERROR as NTSTATUS; + match r.ExceptionCode { + EXCEPTION_ACCESS_VIOLATION => {} + GUARD_PAGE | IN_PAGE_ERROR => return not_guarded(), + _ => return EXCEPTION_CONTINUE_SEARCH, + } let at = r.ExceptionInformation[1]; // Held across both checks: another thread may have opened the block // since this one faulted, and a copy may have guarded it again since @@ -690,7 +756,7 @@ fn install() { if writable(at) { EXCEPTION_CONTINUE_EXECUTION } else { - EXCEPTION_CONTINUE_SEARCH + not_guarded() } } static ONCE: std::sync::Once = std::sync::Once::new(); @@ -801,6 +867,9 @@ mod tests { guard(view, view + 2 * BLOCK), Some((view / PAGE..view / PAGE + 1).collect()) ); + // Told first, as the runtime does: once the view is gone another + // test's may come at its address. + title_memory_remapped(view, 2 * BLOCK); // SAFETY: our view. unsafe { UnmapViewOfFile( @@ -809,7 +878,6 @@ mod tests { }, ) }; - title_memory_remapped(view, 2 * BLOCK); } #[test] @@ -950,6 +1018,7 @@ mod tests { let mut local = [0u8; 16]; let at = local.as_mut_ptr() as usize; assert!(!is_view(at, at + local.len())); + title_memory_remapped(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -959,7 +1028,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// Blocks of a placeholder between views are reported once, then not @@ -1034,6 +1102,7 @@ mod tests { title_memory_remapped(p + BLOCK, BLOCK); assert_eq!(guard(p, p + 3 * BLOCK), Some(pages(1).collect())); assert_eq!(guard(p, p + 3 * BLOCK), Some(Vec::new())); + title_memory_remapped(p, 3 * BLOCK); // SAFETY: our views and placeholder. unsafe { UnmapViewOfFile2(GetCurrentProcess(), first, MEM_PRESERVE_PLACEHOLDER); @@ -1043,7 +1112,6 @@ mod tests { } windows_sys::Win32::Foundation::CloseHandle(section); } - title_memory_remapped(p, 3 * BLOCK); } /// A write or mapping that runs past the end of the address space (a ```` </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code)
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 03:49:02 +00:00
Author
Owner

@⁠Speartone on GitHub · 2026-11-25 04:34 UTC · original

Part 2 of 2 of the patch (apply both; AI-assisted, as above).

Patch, part 2 of 2
diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs
index da412f8..be368bf 100644
--- a/crates/victory-gpu/src/shadow.rs
+++ b/crates/victory-gpu/src/shadow.rs
@@ -575,6 +575,28 @@ fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool {
     differs != 0
 }
 
+/// [`merge_piece`] with title memory left as it was read, in `title`, and
+/// the result in `merged`: what differs between the two goes back
+/// (`crate::putback`).
+fn merge_apart(now: &[u8], held: &mut [u8], title: &[u8], merged: &mut [u8]) -> bool {
+    let mut differs = 0u8;
+    for (((n, h), t), m) in now.iter().zip(held.iter_mut()).zip(title).zip(merged.iter_mut()) {
+        let wrote = if *n != *h { 0xffu8 } else { 0 };
+        *m = (*t & !wrote) | (*n & wrote);
+        differs |= *m ^ *t;
+        *h = (*h & !wrote) | (*n & wrote);
+    }
+    differs != 0
+}
+
+/// Two stretches of `n` bytes of scratch memory, holding anything.
+fn apart(scratch: &mut Vec<u8>, n: usize) -> (&mut [u8], &mut [u8]) {
+    if scratch.len() < 2 * n {
+        scratch.resize(2 * n, 0);
+    }
+    scratch[..2 * n].split_at_mut(n)
+}
+
 /// `[from, to)` without the ranges of `skip`, in order.
 fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
     skip.sort_unstable();
@@ -1928,7 +1950,12 @@ impl Shadow {
                 self.changed(at, at + n);
             }
             let mut title = vec![0u8; PIECE];
+            let exact = crate::putback::on();
+            let mut scratch = Vec::new();
             for (at, n) in differing {
+                // What title memory shows stays as it is from the read of it
+                // below until the shaders' bytes are in.
+                let _shown = exact.then(crate::watch::putting_back);
                 // SAFETY: inside the mapping; only the submitting thread
                 // writes it.
                 let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
@@ -1943,6 +1970,24 @@ impl Shadow {
                 let last = last_difference(host, old).unwrap_or(first);
                 let (at, n) = (at + first, last + 1 - first);
                 let (host, old) = (&mut host[first..=last], &old[first..=last]);
+                if exact {
+                    let (was, merged) = apart(&mut scratch, n);
+                    if !crate::host::read_into((start + at) as *const u8, was) {
+                        continue;
+                    }
+                    // As below, the result beside what was read.
+                    let mut differs = 0u8;
+                    for (((t, m), h), o) in was.iter().zip(merged.iter_mut()).zip(host.iter_mut()).zip(old) {
+                        let gpu = if *h != *o { 0xffu8 } else { 0 };
+                        *m = (*t & !gpu) | (*h & gpu);
+                        differs |= *m ^ *t;
+                        *h = *m;
+                    }
+                    if differs != 0 {
+                        written += crate::putback::back(start + at, merged, was);
+                    }
+                    continue;
+                }
                 let title = &mut title[..n];
                 if !crate::host::read_into((start + at) as *const u8, title) {
                     continue;
@@ -2041,6 +2086,15 @@ impl Shadow {
         let last = last_difference(now, held).unwrap_or(first);
         let (at, n) = (at + first, last + 1 - first);
         let (now, held) = (&now[first..=last], &mut held[first..=last]);
+        if crate::putback::on() {
+            // As below; as in `copy_back_with`.
+            let _shown = crate::watch::putting_back();
+            let (was, merged) = apart(title, n);
+            if !crate::host::read_into((start + at) as *const u8, was) || !merge_apart(now, held, was, merged) {
+                return 0;
+            }
+            return crate::putback::back(start + at, merged, was);
+        }
         title.clear();
         title.resize(n, 0);
         // Title memory not there: looked at again when the next flight
@@ -2564,9 +2618,30 @@ impl Shadow {
         let last = last_difference(gpu, old).unwrap_or(first);
         let (at, n) = (at + first, last + 1 - first);
         let (gpu, old) = (&gpu[first..=last], &mut old[first..=last]);
+        let mut written = 0;
+        if crate::putback::on() {
+            // As below; as in `copy_back_with`.
+            let _shown = crate::watch::putting_back();
+            let (was, merged) = apart(title, n);
+            if crate::host::read_into((start + at) as *const u8, was) {
+                let mut differs = 0u8;
+                for (((t, m), g), o) in was.iter().zip(merged.iter_mut()).zip(gpu).zip(old.iter_mut()) {
+                    let wrote = if *g != *o { 0xffu8 } else { 0 };
+                    *m = (*t & !wrote) | (*g & wrote);
+                    differs |= *m ^ *t;
+                    *o = *m;
+                }
+                if differs != 0 {
+                    written = crate::putback::back(start + at, merged, was);
+                }
+            } else {
+                old.copy_from_slice(gpu);
+            }
+            self.card_changed(at, at + n);
+            return written;
+        }
         title.clear();
         title.resize(n, 0);
-        let mut written = 0;
         if crate::host::read_into((start + at) as *const u8, title) {
             // As in `copy_back`: the card's byte where it is not what it
             // was before the submission, else the title's.
@@ -2641,6 +2716,26 @@ impl Shadow {
                 .filter(|&(a, b)| a < at + n && b > at)
                 .collect()
         };
+        if crate::putback::on() {
+            // As below; as in `copy_back_with`.
+            let _shown = crate::watch::putting_back();
+            let (was, merged) = apart(title, n);
+            let mapped = crate::host::read_into((start + at) as *const u8, was);
+            let mut changed = false;
+            let mut kept = 0;
+            for (a, b) in outside(at, at + n, skip) {
+                let (a, b) = (a - at, b - at);
+                // What is left out goes back as it was read: not at all.
+                merged[kept..a].copy_from_slice(&was[kept..a]);
+                changed |= merge_apart(&gpu[a..b], &mut held[a..b], &was[a..b], &mut merged[a..b]);
+                kept = b;
+            }
+            merged[kept..].copy_from_slice(&was[kept..]);
+            if !mapped || !changed {
+                return 0;
+            }
+            return crate::putback::back(start + at, merged, was);
+        }
         title.clear();
         title.resize(n, 0);
         let mapped = crate::host::read_into((start + at) as *const u8, title);
@@ -3197,3 +3292,517 @@ pub(crate) fn near(va: u64) -> String {
     }
     text
 }
+
+/// The four ways what shaders wrote goes into title memory, beside a title
+/// that writes meanwhile.
+#[cfg(test)]
+mod back_tests {
+    use super::*;
+    use std::sync::atomic::{AtomicBool, AtomicUsize};
+    use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
+    use windows_sys::Win32::System::Memory::{
+        CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE,
+        VirtualAlloc, VirtualFree,
+    };
+    const P: usize = 64 << 10;
+    /// Not a copy in the card's memory, whose smallest is 1 MiB; and one.
+    const LENS: [usize; 2] = [12 * P, 32 * P];
+
+    /// Says stop when it goes, also when a test fails.
+    struct Stop<'a>(&'a AtomicBool);
+    impl Drop for Stop<'_> {
+        fn drop(&mut self) {
+            self.0.store(true, Ordering::Relaxed);
+        }
+    }
+
+    /// Write-watched title memory, or a view of a section; kept.
+    fn title(len: usize, view: bool) -> usize {
+        // SAFETY: fresh memory, left as it is.
+        let at = unsafe {
+            if view {
+                let section =
+                    CreateFileMappingW(INVALID_HANDLE_VALUE, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
+                let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize;
+                CloseHandle(section);
+                at
+            } else {
+                VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | 0x20_0000, PAGE_READWRITE) as usize
+            }
+        };
+        assert_ne!(at, 0);
+        at
+    }
+
+    /// The copy of `len` bytes of fresh title memory; `None` without a host,
+    /// or where one in the card's memory is asked for and not to be had.
+    fn copy(len: usize, view: bool, carded: bool) -> Option<(usize, Arc<Shadow>)> {
+        let start = title(len, view);
+        register(start, start as u64, len as u64);
+        let shadow = find(start as u64, len as u64)?;
+        if shadow.carded() != carded {
+            println!("no copy {} the card's memory here", if carded { "in" } else { "outside" });
+            return None;
+        }
+        Some((start, shadow))
+    }
+
+    /// Shaders of a submission may write all of the copy: as a submission
+    /// is prepared, under its lock, the snapshots taken with the others'.
+    fn declare(shadow: &Shadow, start: usize, len: usize) {
+        let _one = host().expect("a host").submission();
+        shadow.writing(start, len);
+        take_snapshots();
+    }
+
+    #[derive(Clone, Copy, Debug, PartialEq)]
+    enum Way {
+        Waited,
+        Relay,
+        Card,
+        CardRelay,
+    }
+    const WAYS: [Way; 4] = [Way::Waited, Way::Relay, Way::Card, Way::CardRelay];
+
+    impl Way {
+        fn carded(self) -> bool {
+            matches!(self, Way::Card | Way::CardRelay)
+        }
+        fn len(self) -> usize {
+            LENS[usize::from(self.carded())]
+        }
+        /// One submission: the copy brought up to date, `wrote` (by offset)
+        /// changed by its shaders, and what they wrote put back.
+        fn run(self, shadow: &Shadow, start: usize, len: usize, wrote: impl Fn(usize) -> Option<u8>) {
+            shadow.update(start, len);
+            let (mut now, mut scratch) = (Vec::new(), Vec::new());
+            if self.carded() {
+                for p in 0..len / P {
+                    // SAFETY: inside the mapping of the copy's CPU side.
+                    let mut gpu = unsafe { std::slice::from_raw_parts(shadow.data.add(p * P), P) }.to_vec();
+                    for (i, b) in gpu.iter_mut().enumerate() {
+                        *b = wrote(p * P + i).unwrap_or(*b);
+                    }
+                    if self == Way::CardRelay {
+                        // As if the title's bytes had gone up before the fetch.
+                        shadow.card.as_ref().unwrap().dirty.lock().unwrap().clear();
+                        shadow.card_merge_relay(p * P, &gpu, u64::MAX, &mut scratch);
+                    } else {
+                        shadow.card_merge(p * P, &gpu, &mut scratch);
+                    }
+                }
+                return;
+            }
+            declare(shadow, start, len);
+            for i in 0..len {
+                if let Some(b) = wrote(i) {
+                    // SAFETY: inside the copy's mapping.
+                    unsafe { shadow.data.add(i).write_volatile(b) };
+                }
+            }
+            if self == Way::Relay {
+                for p in 0..len / P {
+                    shadow.relay_merge(p * P, P, &mut now, &mut scratch);
+                }
+            } else {
+                shadow.copy_back(start, len);
+            }
+            shadow.copy_back_done(&[(start, start + len)]);
+        }
+    }
+
+    /// A title thread writes words no shader wrote while what shaders wrote
+    /// around them goes back, by each way: how often a word it wrote is
+    /// found with an older value. (writes, undone)
+    fn undone(way: Way, view: bool) -> Option<(usize, usize)> {
+        let len = way.len();
+        let (start, shadow) = copy(len, view, way.carded())?;
+        let (stop, wrote, lost) = (AtomicBool::new(false), AtomicUsize::new(0), AtomicUsize::new(0));
+        std::thread::scope(|s| {
+            s.spawn(|| {
+                // A word of each 64 bytes, but the first and last of a piece.
+                let slots: Vec<usize> =
+                    (0..len / 64).filter(|i| i % 1024 != 0 && i % 1024 != 1023).map(|i| start + i * 64 + 16).collect();
+                let mut last = vec![0u32; slots.len()];
+                let mut n = 0u32;
+                while !stop.load(Ordering::Relaxed) {
+                    for (at, last) in slots.iter().zip(&mut last) {
+                        n = n.wrapping_add(1);
+                        // SAFETY: words of title memory.
+                        unsafe {
+                            let p = *at as *mut u32;
+                            if p.read_volatile() != *last {
+                                lost.fetch_add(1, Ordering::Relaxed);
+                            }
+                            p.write_volatile(n);
+                        }
+                        *last = n;
+                    }
+                    wrote.fetch_add(slots.len(), Ordering::Relaxed);
+                }
+            });
+            let _stop = Stop(&stop);
+            for round in 1..9u8 {
+                // The first and the last byte of each piece, so that the
+                // stretch is all of it, and one byte beside each word.
+                way.run(&shadow, start, len, |i| match i % P {
+                    0 | 0xffff => Some(round),
+                    _ if i % 64 == 40 => Some(round),
+                    _ => None,
+                });
+                // SAFETY: title memory.
+                let there = |i: usize| unsafe { ((start + i) as *const u8).read_volatile() };
+                for p in 0..len / P {
+                    assert_eq!(there(p * P), round, "{way:?}: what shaders wrote, piece {p}");
+                    assert_eq!(there(p * P + 0xffff), round, "{way:?}: what shaders wrote, piece {p}");
+                    assert_eq!(there(p * P + 64 * 77 + 40), round, "{way:?}: what shaders wrote, piece {p}");
+                }
+            }
+        });
+        Some((wrote.into_inner(), lost.into_inner()))
+    }
+
+    #[test]
+    fn what_the_title_writes_during_a_copy_back_stays() {
+        for way in WAYS {
+            for view in [false, true] {
+                if let Some((wrote, undone)) = undone(way, view) {
+                    println!("{way:?}, view {view}: {wrote} title writes, {undone} undone");
+                    assert!(wrote > 1000);
+                    if crate::putback::on() {
+                        assert_eq!(undone, 0, "{way:?}, view {view}");
+                    }
+                }
+            }
+        }
+    }
+
+    /// With a title that rests, title memory and the copy end as the merge
+    /// says, whatever shaders wrote: their bytes where they wrote, the
+    /// title's elsewhere, also where the title wrote after the copy was
+    /// brought up to date.
+    #[test]
+    fn title_memory_ends_with_the_shaders_bytes_and_its_own() {
+        for way in WAYS {
+            let len = way.len();
+            let Some((start, shadow)) = copy(len, false, way.carded()) else {
+                continue;
+            };
+            let mut seed = 0x1234_5678_9abc_def1u64 ^ len as u64;
+            let mut random = || {
+                seed ^= seed << 13;
+                seed ^= seed >> 7;
+                seed ^= seed << 17;
+                seed
+            };
+            let mut wanted: Vec<u8> = vec![0; len];
+            for round in 0..6 {
+                for _ in 0..4000 {
+                    let (at, b) = (random() as usize % len, random() as u8);
+                    // SAFETY: title memory.
+                    unsafe { ((start + at) as *mut u8).write_volatile(b) };
+                    wanted[at] = b;
+                }
+                // Sparse, runs, and all of it, by piece.
+                let kind: Vec<u64> = (0..len / P).map(|_| random() % 4).collect();
+                let salt = random() as u8 | 1;
+                let wrote = |i: usize| {
+                    let j = (i as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 40;
+                    match kind[i / P] {
+                        0 => None,
+                        1 => j.is_multiple_of(61).then_some(j as u8 ^ salt),
+                        2 => (i / 24 % 3 == round % 3).then_some(j as u8 ^ salt),
+                        _ => Some(j as u8 ^ salt),
+                    }
+                };
+                for (i, w) in wanted.iter_mut().enumerate() {
+                    *w = wrote(i).unwrap_or(*w);
+                }
+                way.run(&shadow, start, len, wrote);
+                // SAFETY: title memory, at rest.
+                let there = unsafe { std::slice::from_raw_parts(start as *const u8, len) };
+                if let Some(i) = there.iter().zip(&wanted).position(|(a, b)| a != b) {
+                    panic!("{way:?} round {round}: byte {i:#x} is {:#x}, not {:#x}", there[i], wanted[i]);
+                }
+                shadow.update(start, len);
+                // SAFETY: inside the copy's mapping (its CPU side).
+                let held = unsafe { std::slice::from_raw_parts(shadow.data as *const u8, len) };
+                if !way.carded() || way == Way::Card {
+                    assert!(held == &wanted[..], "{way:?} round {round}: the copy");
+                }
+            }
+        }
+    }
+
+    /// Another thread brings a copy of the same view memory up to date, and
+    /// so makes it read-only again, between the opening of its guards and
+    /// the store: what shaders wrote arrives all the same.
+    #[test]
+    fn what_shaders_wrote_arrives_in_memory_that_is_guarded_again() {
+        for way in WAYS {
+            let len = way.len();
+            let Some((start, shadow)) = copy(len, true, way.carded()) else {
+                continue;
+            };
+            let stop = AtomicBool::new(false);
+            let lost = std::thread::scope(|s| {
+                s.spawn(|| {
+                    while !stop.load(Ordering::Relaxed) {
+                        assert!(crate::watch::title_memory_written_pages(start, len).is_some());
+                    }
+                });
+                let _stop = Stop(&stop);
+                let mut lost = 0;
+                for round in 1..25u8 {
+                    way.run(&shadow, start, len, |i| i.is_multiple_of(4099).then_some(round));
+                    for i in (0..len).step_by(4099) {
+                        // SAFETY: title memory.
+                        lost += usize::from(unsafe { ((start + i) as *const u8).read_volatile() } != round);
+                    }
+                }
+                lost
+            });
+            println!("{way:?}: {lost} bytes shaders wrote did not arrive");
+            if crate::putback::on() {
+                assert_eq!(lost, 0, "{way:?}");
+            }
+        }
+    }
+
+    /// A write that goes round the title's own view reaches the copy once
+    /// it is told (`crate::watch::writing`).
+    #[test]
+    fn a_write_round_the_view_reaches_the_copy_once_told() {
+        let len = LENS[0];
+        // SAFETY: a section of ours seen at two addresses.
+        let (a, b) = unsafe {
+            let section =
+                CreateFileMappingW(INVALID_HANDLE_VALUE, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
+            let views = [(); 2].map(|()| MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize);
+            CloseHandle(section);
+            (views[0], views[1])
+        };
+        register(a, a as u64, len as u64);
+        let Some(shadow) = find(a as u64, len as u64) else {
+            return; // no host
+        };
+        shadow.update(a, len);
+        let at = 5 * P + 9;
+        // SAFETY: the other view, and the copy's mapping.
+        unsafe {
+            ((b + at) as *mut u8).write_volatile(7);
+            crate::watch::writing(a + at, 1);
+            shadow.update(a, len);
+            assert_eq!(shadow.data.add(at).read_volatile(), 7);
+        }
+    }
+
+    /// The merge beside title memory does what the merge into it does.
+    #[test]
+    fn the_two_merges_agree() {
+        let mut seed = 0xabcd_ef01_2345_6789u64;
+        let mut random = move || {
+            seed ^= seed << 13;
+            seed ^= seed >> 7;
+            seed ^= seed << 17;
+            // Few values, so that bytes are often the same.
+            (seed >> 33) as u8 & 3
+        };
+        for n in (0..200).chain([4096]) {
+            let (now, held, title): (Vec<u8>, Vec<u8>, Vec<u8>) =
+                ((0..n).map(|_| random()).collect(), (0..n).map(|_| random()).collect(), (0..n).map(|_| random()).collect());
+            let (mut held_a, mut title_a) = (held.clone(), title.clone());
+            let (mut held_b, mut merged) = (held.clone(), vec![0xee; n]);
+            let changed = merge_piece(&now, &mut held_a, &mut title_a);
+            assert_eq!(merge_apart(&now, &mut held_b, &title, &mut merged), changed);
+            assert_eq!((held_a, title_a), (held_b, merged));
+        }
+    }
+
+    /// Bytes of a card copy's CPU side the card has not received are left
+    /// out of the relay's merge, whatever the scratch memory held.
+    #[test]
+    fn bytes_still_to_go_up_are_left_out() {
+        let Some((start, shadow)) = copy(LENS[1], false, true) else {
+            return;
+        };
+        shadow.update(start, LENS[1]);
+        let card = shadow.card.as_ref().unwrap();
+        *card.dirty.lock().unwrap() = vec![(100, 5000), (9000, 9001)];
+        *card.sent.lock().unwrap() = vec![(20_000, 21_000, 7), (30_000, 31_000, 5), (60_000, 65_530, 6)];
+        let mut scratch = vec![0xee; 3 * P];
+        shadow.card_merge_relay(0, &[5; P], 5, &mut scratch);
+        // And one whose end is left out.
+        *card.dirty.lock().unwrap() = vec![(P + 600, P + 1000)];
+        scratch.fill(0xee);
+        shadow.card_merge_relay(P, &[5; 1000], 9, &mut scratch);
+        for i in 0..1000 {
+            // SAFETY: title memory.
+            let there = unsafe { ((start + P + i) as *const u8).read_volatile() };
+            assert_eq!(there, if i < 600 { 5 } else { 0 }, "byte {i} of the second");
+        }
+        let left = |i: usize| {
+            (100..5000).contains(&i) || i == 9000 || (20_000..21_000).contains(&i) || (60_000..65_530).contains(&i)
+        };
+        for i in 0..P {
+            // SAFETY: title memory, and the mapping of the copy's CPU side.
+            let (there, held) = unsafe { (((start + i) as *const u8).read_volatile(), shadow.data.add(i).read_volatile()) };
+            let wanted = if left(i) { 0 } else { 5 };
+            assert_eq!((there, held), (wanted, wanted), "byte {i}");
+        }
+    }
+
+    /// What the title wrote since the copy was brought up to date comes into
+    /// the copy with the merge (not the relay's, which leaves it to the
+    /// refresh), and a card copy sends the merge's result up.
+    #[test]
+    fn the_copy_takes_the_titles_bytes_with_the_merge() {
+        for way in [Way::Waited, Way::Card] {
+            let len = way.len();
+            let Some((start, shadow)) = copy(len, false, way.carded()) else {
+                continue;
+            };
+            shadow.update(start, len);
+            // SAFETY: title memory, and the copy's mapping.
+            let write = |at: usize, b: u8| unsafe { ((start + at) as *mut u8).write_volatile(b) };
+            let held = |at: usize| unsafe { shadow.data.add(at).read_volatile() };
+            if way == Way::Waited {
+                declare(&shadow, start, len);
+                // SAFETY: inside the copy's mapping.
+                unsafe {
+                    shadow.data.add(10).write_volatile(1);
+                    shadow.data.add(30).write_volatile(3);
+                }
+                write(20, 2);
+                shadow.copy_back(start, len);
+                shadow.copy_back_done(&[(start, start + len)]);
+            } else {
+                let mut gpu = vec![0u8; P];
+                (gpu[10], gpu[30]) = (1, 3);
+                write(20, 2);
+                shadow.card.as_ref().unwrap().dirty.lock().unwrap().clear();
+                shadow.card_merge(0, &gpu, &mut Vec::new());
+                assert_eq!(*shadow.card.as_ref().unwrap().dirty.lock().unwrap(), [(10, 31)], "sent up");
+            }
+            assert_eq!([held(10), held(20), held(30)], [1, 2, 3], "{way:?}: the copy");
+            // SAFETY: title memory.
+            let there = unsafe { std::slice::from_raw_parts(start as *const u8, 40) };
+            assert_eq!([there[10], there[20], there[30]], [1, 2, 3], "{way:?}: title memory");
+        }
+    }
+
+    /// Title memory a page of which the title made read-only: that page is
+    /// left alone, the rest takes what shaders wrote. (After upstream's
+    /// pull request 1024.)
+    #[test]
+    fn a_page_the_title_made_read_only_is_left_alone() {
+        use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
+        for way in WAYS {
+            let len = way.len();
+            let Some((start, shadow)) = copy(len, false, way.carded()) else {
+                continue;
+            };
+            shadow.update(start, len);
+            let mut old = 0;
+            // SAFETY: a page of ours.
+            assert_ne!(unsafe { VirtualProtect((start + 3 * P) as *const _, 4096, PAGE_READONLY, &mut old) }, 0);
+            way.run(&shadow, start, len, |_| Some(1));
+            for i in 0..len {
+                // SAFETY: title memory.
+                let there = unsafe { ((start + i) as *const u8).read_volatile() };
+                let wanted = u8::from(!(3 * P..3 * P + 4096).contains(&i));
+                assert_eq!(there, wanted, "{way:?} byte {i:#x}");
+            }
+        }
+    }
+
+    /// How long a copy-back takes: `cargo test --release ... back_speed --
+    /// --ignored --nocapture`, with and without `VICTORY_EXACT_BACK=0`.
+    #[test]
+    #[ignore = "a measurement"]
+    fn back_speed() {
+        type Wrote = fn(usize) -> Option<u8>;
+        // A frame's worth: 1,000 pieces, what shaders wrote in each.
+        const PIECES: usize = 1000;
+        let patterns: [(&str, Wrote); 7] = [
+            ("every byte", |i| Some((i >> 7) as u8 | 1)),
+            ("three bytes of four", |i| (i % 4 != 3).then_some((i >> 7) as u8 | 1)),
+            ("every second byte", |i| (i % 2 == 0).then_some(1)),
+            ("16 bytes of 64", |i| (i % 64 < 16).then_some(1)),
+            ("4 bytes of 64", |i| (i % 64 < 4).then_some(1)),
+            ("4 bytes of 1024", |i| (i % 1024 < 4).then_some(1)),
+            ("4 bytes of a piece", |i| (i % P < 4).then_some(1)),
+        ];
+        for way in WAYS {
+            let len = if way.carded() { PIECES * P } else { 15 * P };
+            let copies = if way.carded() { 1 } else { PIECES / 15 };
+            let made: Vec<(usize, Arc<Shadow>)> = (0..copies).filter_map(|_| copy(len, false, way.carded())).collect();
+            if made.len() < copies {
+                continue;
+            }
+            for (name, wrote) in patterns {
+                let gpu: Vec<u8> = (0..len).map(|i| wrote(i).unwrap_or(0)).collect();
+                let mut times: Vec<f64> = (0..15)
+                    .map(|_| {
+                        // Title memory back to zeros, and the copy with it.
+                        for (start, shadow) in &made {
+                            // SAFETY: title memory.
+                            unsafe { std::ptr::write_bytes(*start as *mut u8, 0, len) };
+                            shadow.update(*start, len);
+                            if !way.carded() {
+                                declare(shadow, *start, len);
+                                // SAFETY: the copy's mapping.
+                                unsafe { std::ptr::copy_nonoverlapping(gpu.as_ptr(), shadow.data, len) };
+                            } else {
+                                shadow.card.as_ref().unwrap().dirty.lock().unwrap().clear();
+                            }
+                        }
+                        let (mut now, mut scratch) = (Vec::new(), Vec::new());
+                        let mut took = std::time::Duration::ZERO;
+                        for (start, shadow) in &made {
+                            let found: Vec<(usize, usize)> = (0..len / P).map(|p| (p * P, P)).collect();
+                            let began = std::time::Instant::now();
+                            match way {
+                                Way::Waited => {
+                                    shadow.copy_back_with(*start, len, Some(found));
+                                }
+                                Way::Relay => {
+                                    for (at, n) in found {
+                                        shadow.relay_merge(at, n, &mut now, &mut scratch);
+                                    }
+                                }
+                                Way::Card => {
+                                    for (at, n) in found {
+                                        shadow.card_merge(at, &gpu[at..at + n], &mut scratch);
+                                    }
+                                }
+                                Way::CardRelay => {
+                                    for (at, n) in found {
+                                        shadow.card_merge_relay(at, &gpu[at..at + n], u64::MAX, &mut scratch);
+                                    }
+                                }
+                            }
+                            took += began.elapsed();
+                        }
+                        for (start, shadow) in &made {
+                            shadow.copy_back_done(&[(*start, *start + len)]);
+                        }
+                        took.as_secs_f64() * 1e3 * PIECES as f64 / (copies * len / P) as f64
+                    })
+                    .collect();
+                times.sort_by(f64::total_cmp);
+                println!(
+                    "{} {way:?} | {name} | {:.2} ms per 1,000 pieces (best {:.2}, worst {:.2})",
+                    if crate::putback::on() { "exact" } else { "whole" },
+                    times[times.len() / 2],
+                    times[0],
+                    times[times.len() - 1]
+                );
+            }
+            for (start, _) in made {
+                // SAFETY: memory of `title`'s.
+                unsafe { VirtualFree(start as *mut _, 0, MEM_RELEASE) };
+            }
+        }
+    }
+}
diff --git a/crates/victory-hle/src/modules/memory.rs b/crates/victory-hle/src/modules/memory.rs
new file mode 100644
index 0000000..1c094ea
--- /dev/null
+++ b/crates/victory-hle/src/modules/memory.rs
@@ -0,0 +1,172 @@
+//! The title's own frees and unmappings of memory: the host's, but not
+//! while the GPU side puts what shaders wrote into title memory
+//! (`victory_gpu::title_memory_releasing`). Between its read of a stretch
+//! and its store into it, the stretch must not become other memory at the
+//! same address.
+//!
+//! The title's imports of these and its lookups by name come here; a free
+//! from inside the host (its heaps) or by a direct system call does not.
+#![allow(non_snake_case)]
+// Title code calls these through its import table, passing pointers the real
+// API would trust.
+#![allow(clippy::not_unsafe_ptr_arg_deref)]
+
+use std::ffi::c_void;
+
+use super::files::host;
+use crate::{HleModule, hle_export};
+
+pub extern "system" fn VirtualFree(address: *mut c_void, size: usize, kind: u32) -> i32 {
+    let _releasing = victory_gpu::title_memory_releasing();
+    host!("kernel32.dll", "VirtualFree": extern "system" fn(*mut c_void, usize, u32) -> i32)(
+        address, size, kind,
+    )
+}
+
+pub extern "system" fn VirtualFreeEx(
+    process: *mut c_void,
+    address: *mut c_void,
+    size: usize,
+    kind: u32,
+) -> i32 {
+    let _releasing = victory_gpu::title_memory_releasing();
+    host!("kernel32.dll", "VirtualFreeEx": extern "system" fn(*mut c_void, *mut c_void, usize, u32) -> i32)(
+        process, address, size, kind,
+    )
+}
+
+pub extern "system" fn UnmapViewOfFile(address: *const c_void) -> i32 {
+    let _releasing = victory_gpu::title_memory_releasing();
+    host!("kernel32.dll", "UnmapViewOfFile": extern "system" fn(*const c_void) -> i32)(address)
+}
+
+pub extern "system" fn UnmapViewOfFileEx(address: *const c_void, flags: u32) -> i32 {
+    let _releasing = victory_gpu::title_memory_releasing();
+    host!("kernel32.dll", "UnmapViewOfFileEx": extern "system" fn(*const c_void, u32) -> i32)(
+        address, flags,
+    )
+}
+
+pub extern "system" fn UnmapViewOfFile2(
+    process: *mut c_void,
+    address: *const c_void,
+    flags: u32,
+) -> i32 {
+    let _releasing = victory_gpu::title_memory_releasing();
+    host!("kernelbase.dll", "UnmapViewOfFile2": extern "system" fn(*mut c_void, *const c_void, u32) -> i32)(
+        process, address, flags,
+    )
+}
+
+pub(crate) fn module() -> HleModule {
+    HleModule {
+        name: "memory",
+        dlls: &["kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-*"],
+        exports: vec![
+            hle_export!(VirtualFree),
+            hle_export!(VirtualFreeEx),
+            hle_export!(UnmapViewOfFile),
+            hle_export!(UnmapViewOfFileEx),
+            hle_export!(UnmapViewOfFile2),
+        ],
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use windows_sys::Win32::Foundation::{GetLastError, SetLastError};
+    use windows_sys::Win32::System::Memory::{
+        MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc,
+    };
+
+    /// The host's answers and errors come through, and the title's imports
+    /// and lookups by name end here, from each of the DLLs that have them.
+    #[test]
+    fn frees_go_to_the_host() {
+        for dll in [
+            "KERNEL32.dll",
+            "kernelbase.dll",
+            "api-ms-win-core-memory-l1-1-0.dll",
+        ] {
+            assert_eq!(
+                crate::registry::lookup(dll, "VirtualFree"),
+                Some(VirtualFree as *const () as usize)
+            );
+            assert_eq!(
+                crate::registry::lookup(dll, "UnmapViewOfFile"),
+                Some(UnmapViewOfFile as *const () as usize)
+            );
+            assert_eq!(
+                crate::registry::lookup(dll, "VirtualAlloc"),
+                None,
+                "the host's own"
+            );
+        }
+        // SAFETY: memory of our own, and an address that holds none.
+        unsafe {
+            let p = VirtualAlloc(
+                std::ptr::null(),
+                0x1000,
+                MEM_RESERVE | MEM_COMMIT,
+                PAGE_READWRITE,
+            );
+            assert!(!p.is_null());
+            assert_eq!(
+                VirtualFree(p, 0x1000, MEM_RELEASE),
+                0,
+                "a size with a release"
+            );
+            assert_eq!(GetLastError(), 87);
+            assert_ne!(VirtualFree(p, 0, MEM_RELEASE), 0);
+            SetLastError(0);
+            assert_eq!(VirtualFree(p, 0, MEM_RELEASE), 0, "free already");
+            assert_eq!(GetLastError(), 487);
+            assert_eq!(UnmapViewOfFile(p), 0);
+            assert_eq!(GetLastError(), 487);
+        }
+    }
+
+    /// Each of them waits for bytes on their way into title memory.
+    #[test]
+    fn frees_wait_for_what_shaders_wrote() {
+        let waits = |free: fn() -> i32| {
+            let putting = victory_gpu::title_memory_putting_back();
+            let (done, came) = std::sync::mpsc::channel();
+            let thread = std::thread::spawn(move || {
+                free();
+                let _ = done.send(());
+            });
+            let early = came
+                .recv_timeout(std::time::Duration::from_millis(50))
+                .is_ok();
+            drop(putting);
+            thread.join().unwrap();
+            !early
+        };
+        let expected = std::env::var("VICTORY_EXACT_BACK").map_or(true, |v| v.trim() != "0");
+        const NULL: *mut c_void = std::ptr::null_mut();
+        let frees: [fn() -> i32; 6] = [
+            || VirtualFree(NULL, 0, MEM_RELEASE),
+            || VirtualFreeEx(-1isize as _, NULL, 0, MEM_RELEASE),
+            || UnmapViewOfFile(NULL),
+            || UnmapViewOfFileEx(NULL, 0),
+            || UnmapViewOfFile2(-1isize as _, NULL, 0),
+            || {
+                super::super::xmem::XMemFreeDefault(
+                    FREED.load(std::sync::atomic::Ordering::Relaxed) as _,
+                    ATTRIBUTES,
+                );
+                0
+            },
+        ];
+        static FREED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
+        const ATTRIBUTES: u64 = super::super::xmem::ALLOC_32BIT;
+        let p = super::super::xmem::XMemAllocDefault(0x1_0000, ATTRIBUTES);
+        assert!(!p.is_null());
+        FREED.store(p as usize, std::sync::atomic::Ordering::Relaxed);
+        for (i, free) in frees.into_iter().enumerate() {
+            assert_eq!(waits(free), expected, "{i}");
+        }
+    }
+}
diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs
index 51e3590..2c0cfa9 100644
--- a/crates/victory-hle/src/modules/mod.rs
+++ b/crates/victory-hle/src/modules/mod.rs
@@ -25,6 +25,8 @@ pub mod lifecycle;
 #[cfg(windows)]
 pub mod media;
 #[cfg(windows)]
+pub mod memory;
+#[cfg(windows)]
 pub mod net;
 pub mod speech;
 pub mod storage;
@@ -67,6 +69,8 @@ pub(crate) fn all() -> Vec<HleModule> {
     #[cfg(windows)]
     all.push(net::module());
     #[cfg(windows)]
+    all.push(memory::module());
+    #[cfg(windows)]
     all.push(xmem::module());
     #[cfg(windows)]
     all.push(xsystem::module());
diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs
index 5f717bf..ddd5809 100644
--- a/crates/victory-hle/src/modules/xmem.rs
+++ b/crates/victory-hle/src/modules/xmem.rs
@@ -206,7 +206,7 @@ pub extern "system" fn XMemVirtualQuery(
 // `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up
 // from 2), then the memory type, then bit 33: a 32-bit address.
 const ALIGNMENT_SHIFT: u64 = 24;
-const ALLOC_32BIT: u64 = 1 << 33;
+pub(crate) const ALLOC_32BIT: u64 = 1 << 33;
 /// Our block header: the block's size and alignment, just below the
 /// pointer handed out.
 const HEADER: usize = 2 * size_of::<usize>();
@@ -318,6 +318,7 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) {
     // whole reservation, or a header-prefixed block.
     unsafe {
         if attributes & ALLOC_32BIT != 0 {
+            let _releasing = victory_gpu::title_memory_releasing();
             VirtualFree(address, 0, MEM_RELEASE);
             return;
         }
**@⁠Speartone** on GitHub · 2026-11-25 04:34 UTC · [original](https://github.com/fxceless/victory-fork/issues/690#issuecomment-7152969210) Part 2 of 2 of the patch (apply both; AI-assisted, as above). <details><summary>Patch, part 2 of 2</summary> ````diff diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index da412f8..be368bf 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -575,6 +575,28 @@ fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { differs != 0 } +/// [`merge_piece`] with title memory left as it was read, in `title`, and +/// the result in `merged`: what differs between the two goes back +/// (`crate::putback`). +fn merge_apart(now: &[u8], held: &mut [u8], title: &[u8], merged: &mut [u8]) -> bool { + let mut differs = 0u8; + for (((n, h), t), m) in now.iter().zip(held.iter_mut()).zip(title).zip(merged.iter_mut()) { + let wrote = if *n != *h { 0xffu8 } else { 0 }; + *m = (*t & !wrote) | (*n & wrote); + differs |= *m ^ *t; + *h = (*h & !wrote) | (*n & wrote); + } + differs != 0 +} + +/// Two stretches of `n` bytes of scratch memory, holding anything. +fn apart(scratch: &mut Vec<u8>, n: usize) -> (&mut [u8], &mut [u8]) { + if scratch.len() < 2 * n { + scratch.resize(2 * n, 0); + } + scratch[..2 * n].split_at_mut(n) +} + /// `[from, to)` without the ranges of `skip`, in order. fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { skip.sort_unstable(); @@ -1928,7 +1950,12 @@ impl Shadow { self.changed(at, at + n); } let mut title = vec![0u8; PIECE]; + let exact = crate::putback::on(); + let mut scratch = Vec::new(); for (at, n) in differing { + // What title memory shows stays as it is from the read of it + // below until the shaders' bytes are in. + let _shown = exact.then(crate::watch::putting_back); // SAFETY: inside the mapping; only the submitting thread // writes it. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; @@ -1943,6 +1970,24 @@ impl Shadow { let last = last_difference(host, old).unwrap_or(first); let (at, n) = (at + first, last + 1 - first); let (host, old) = (&mut host[first..=last], &old[first..=last]); + if exact { + let (was, merged) = apart(&mut scratch, n); + if !crate::host::read_into((start + at) as *const u8, was) { + continue; + } + // As below, the result beside what was read. + let mut differs = 0u8; + for (((t, m), h), o) in was.iter().zip(merged.iter_mut()).zip(host.iter_mut()).zip(old) { + let gpu = if *h != *o { 0xffu8 } else { 0 }; + *m = (*t & !gpu) | (*h & gpu); + differs |= *m ^ *t; + *h = *m; + } + if differs != 0 { + written += crate::putback::back(start + at, merged, was); + } + continue; + } let title = &mut title[..n]; if !crate::host::read_into((start + at) as *const u8, title) { continue; @@ -2041,6 +2086,15 @@ impl Shadow { let last = last_difference(now, held).unwrap_or(first); let (at, n) = (at + first, last + 1 - first); let (now, held) = (&now[first..=last], &mut held[first..=last]); + if crate::putback::on() { + // As below; as in `copy_back_with`. + let _shown = crate::watch::putting_back(); + let (was, merged) = apart(title, n); + if !crate::host::read_into((start + at) as *const u8, was) || !merge_apart(now, held, was, merged) { + return 0; + } + return crate::putback::back(start + at, merged, was); + } title.clear(); title.resize(n, 0); // Title memory not there: looked at again when the next flight @@ -2564,9 +2618,30 @@ impl Shadow { let last = last_difference(gpu, old).unwrap_or(first); let (at, n) = (at + first, last + 1 - first); let (gpu, old) = (&gpu[first..=last], &mut old[first..=last]); + let mut written = 0; + if crate::putback::on() { + // As below; as in `copy_back_with`. + let _shown = crate::watch::putting_back(); + let (was, merged) = apart(title, n); + if crate::host::read_into((start + at) as *const u8, was) { + let mut differs = 0u8; + for (((t, m), g), o) in was.iter().zip(merged.iter_mut()).zip(gpu).zip(old.iter_mut()) { + let wrote = if *g != *o { 0xffu8 } else { 0 }; + *m = (*t & !wrote) | (*g & wrote); + differs |= *m ^ *t; + *o = *m; + } + if differs != 0 { + written = crate::putback::back(start + at, merged, was); + } + } else { + old.copy_from_slice(gpu); + } + self.card_changed(at, at + n); + return written; + } title.clear(); title.resize(n, 0); - let mut written = 0; if crate::host::read_into((start + at) as *const u8, title) { // As in `copy_back`: the card's byte where it is not what it // was before the submission, else the title's. @@ -2641,6 +2716,26 @@ impl Shadow { .filter(|&(a, b)| a < at + n && b > at) .collect() }; + if crate::putback::on() { + // As below; as in `copy_back_with`. + let _shown = crate::watch::putting_back(); + let (was, merged) = apart(title, n); + let mapped = crate::host::read_into((start + at) as *const u8, was); + let mut changed = false; + let mut kept = 0; + for (a, b) in outside(at, at + n, skip) { + let (a, b) = (a - at, b - at); + // What is left out goes back as it was read: not at all. + merged[kept..a].copy_from_slice(&was[kept..a]); + changed |= merge_apart(&gpu[a..b], &mut held[a..b], &was[a..b], &mut merged[a..b]); + kept = b; + } + merged[kept..].copy_from_slice(&was[kept..]); + if !mapped || !changed { + return 0; + } + return crate::putback::back(start + at, merged, was); + } title.clear(); title.resize(n, 0); let mapped = crate::host::read_into((start + at) as *const u8, title); @@ -3197,3 +3292,517 @@ pub(crate) fn near(va: u64) -> String { } text } + +/// The four ways what shaders wrote goes into title memory, beside a title +/// that writes meanwhile. +#[cfg(test)] +mod back_tests { + use super::*; + use std::sync::atomic::{AtomicBool, AtomicUsize}; + use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE}; + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, + VirtualAlloc, VirtualFree, + }; + const P: usize = 64 << 10; + /// Not a copy in the card's memory, whose smallest is 1 MiB; and one. + const LENS: [usize; 2] = [12 * P, 32 * P]; + + /// Says stop when it goes, also when a test fails. + struct Stop<'a>(&'a AtomicBool); + impl Drop for Stop<'_> { + fn drop(&mut self) { + self.0.store(true, Ordering::Relaxed); + } + } + + /// Write-watched title memory, or a view of a section; kept. + fn title(len: usize, view: bool) -> usize { + // SAFETY: fresh memory, left as it is. + let at = unsafe { + if view { + let section = + CreateFileMappingW(INVALID_HANDLE_VALUE, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null()); + let at = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize; + CloseHandle(section); + at + } else { + VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | 0x20_0000, PAGE_READWRITE) as usize + } + }; + assert_ne!(at, 0); + at + } + + /// The copy of `len` bytes of fresh title memory; `None` without a host, + /// or where one in the card's memory is asked for and not to be had. + fn copy(len: usize, view: bool, carded: bool) -> Option<(usize, Arc<Shadow>)> { + let start = title(len, view); + register(start, start as u64, len as u64); + let shadow = find(start as u64, len as u64)?; + if shadow.carded() != carded { + println!("no copy {} the card's memory here", if carded { "in" } else { "outside" }); + return None; + } + Some((start, shadow)) + } + + /// Shaders of a submission may write all of the copy: as a submission + /// is prepared, under its lock, the snapshots taken with the others'. + fn declare(shadow: &Shadow, start: usize, len: usize) { + let _one = host().expect("a host").submission(); + shadow.writing(start, len); + take_snapshots(); + } + + #[derive(Clone, Copy, Debug, PartialEq)] + enum Way { + Waited, + Relay, + Card, + CardRelay, + } + const WAYS: [Way; 4] = [Way::Waited, Way::Relay, Way::Card, Way::CardRelay]; + + impl Way { + fn carded(self) -> bool { + matches!(self, Way::Card | Way::CardRelay) + } + fn len(self) -> usize { + LENS[usize::from(self.carded())] + } + /// One submission: the copy brought up to date, `wrote` (by offset) + /// changed by its shaders, and what they wrote put back. + fn run(self, shadow: &Shadow, start: usize, len: usize, wrote: impl Fn(usize) -> Option<u8>) { + shadow.update(start, len); + let (mut now, mut scratch) = (Vec::new(), Vec::new()); + if self.carded() { + for p in 0..len / P { + // SAFETY: inside the mapping of the copy's CPU side. + let mut gpu = unsafe { std::slice::from_raw_parts(shadow.data.add(p * P), P) }.to_vec(); + for (i, b) in gpu.iter_mut().enumerate() { + *b = wrote(p * P + i).unwrap_or(*b); + } + if self == Way::CardRelay { + // As if the title's bytes had gone up before the fetch. + shadow.card.as_ref().unwrap().dirty.lock().unwrap().clear(); + shadow.card_merge_relay(p * P, &gpu, u64::MAX, &mut scratch); + } else { + shadow.card_merge(p * P, &gpu, &mut scratch); + } + } + return; + } + declare(shadow, start, len); + for i in 0..len { + if let Some(b) = wrote(i) { + // SAFETY: inside the copy's mapping. + unsafe { shadow.data.add(i).write_volatile(b) }; + } + } + if self == Way::Relay { + for p in 0..len / P { + shadow.relay_merge(p * P, P, &mut now, &mut scratch); + } + } else { + shadow.copy_back(start, len); + } + shadow.copy_back_done(&[(start, start + len)]); + } + } + + /// A title thread writes words no shader wrote while what shaders wrote + /// around them goes back, by each way: how often a word it wrote is + /// found with an older value. (writes, undone) + fn undone(way: Way, view: bool) -> Option<(usize, usize)> { + let len = way.len(); + let (start, shadow) = copy(len, view, way.carded())?; + let (stop, wrote, lost) = (AtomicBool::new(false), AtomicUsize::new(0), AtomicUsize::new(0)); + std::thread::scope(|s| { + s.spawn(|| { + // A word of each 64 bytes, but the first and last of a piece. + let slots: Vec<usize> = + (0..len / 64).filter(|i| i % 1024 != 0 && i % 1024 != 1023).map(|i| start + i * 64 + 16).collect(); + let mut last = vec![0u32; slots.len()]; + let mut n = 0u32; + while !stop.load(Ordering::Relaxed) { + for (at, last) in slots.iter().zip(&mut last) { + n = n.wrapping_add(1); + // SAFETY: words of title memory. + unsafe { + let p = *at as *mut u32; + if p.read_volatile() != *last { + lost.fetch_add(1, Ordering::Relaxed); + } + p.write_volatile(n); + } + *last = n; + } + wrote.fetch_add(slots.len(), Ordering::Relaxed); + } + }); + let _stop = Stop(&stop); + for round in 1..9u8 { + // The first and the last byte of each piece, so that the + // stretch is all of it, and one byte beside each word. + way.run(&shadow, start, len, |i| match i % P { + 0 | 0xffff => Some(round), + _ if i % 64 == 40 => Some(round), + _ => None, + }); + // SAFETY: title memory. + let there = |i: usize| unsafe { ((start + i) as *const u8).read_volatile() }; + for p in 0..len / P { + assert_eq!(there(p * P), round, "{way:?}: what shaders wrote, piece {p}"); + assert_eq!(there(p * P + 0xffff), round, "{way:?}: what shaders wrote, piece {p}"); + assert_eq!(there(p * P + 64 * 77 + 40), round, "{way:?}: what shaders wrote, piece {p}"); + } + } + }); + Some((wrote.into_inner(), lost.into_inner())) + } + + #[test] + fn what_the_title_writes_during_a_copy_back_stays() { + for way in WAYS { + for view in [false, true] { + if let Some((wrote, undone)) = undone(way, view) { + println!("{way:?}, view {view}: {wrote} title writes, {undone} undone"); + assert!(wrote > 1000); + if crate::putback::on() { + assert_eq!(undone, 0, "{way:?}, view {view}"); + } + } + } + } + } + + /// With a title that rests, title memory and the copy end as the merge + /// says, whatever shaders wrote: their bytes where they wrote, the + /// title's elsewhere, also where the title wrote after the copy was + /// brought up to date. + #[test] + fn title_memory_ends_with_the_shaders_bytes_and_its_own() { + for way in WAYS { + let len = way.len(); + let Some((start, shadow)) = copy(len, false, way.carded()) else { + continue; + }; + let mut seed = 0x1234_5678_9abc_def1u64 ^ len as u64; + let mut random = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + let mut wanted: Vec<u8> = vec![0; len]; + for round in 0..6 { + for _ in 0..4000 { + let (at, b) = (random() as usize % len, random() as u8); + // SAFETY: title memory. + unsafe { ((start + at) as *mut u8).write_volatile(b) }; + wanted[at] = b; + } + // Sparse, runs, and all of it, by piece. + let kind: Vec<u64> = (0..len / P).map(|_| random() % 4).collect(); + let salt = random() as u8 | 1; + let wrote = |i: usize| { + let j = (i as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 40; + match kind[i / P] { + 0 => None, + 1 => j.is_multiple_of(61).then_some(j as u8 ^ salt), + 2 => (i / 24 % 3 == round % 3).then_some(j as u8 ^ salt), + _ => Some(j as u8 ^ salt), + } + }; + for (i, w) in wanted.iter_mut().enumerate() { + *w = wrote(i).unwrap_or(*w); + } + way.run(&shadow, start, len, wrote); + // SAFETY: title memory, at rest. + let there = unsafe { std::slice::from_raw_parts(start as *const u8, len) }; + if let Some(i) = there.iter().zip(&wanted).position(|(a, b)| a != b) { + panic!("{way:?} round {round}: byte {i:#x} is {:#x}, not {:#x}", there[i], wanted[i]); + } + shadow.update(start, len); + // SAFETY: inside the copy's mapping (its CPU side). + let held = unsafe { std::slice::from_raw_parts(shadow.data as *const u8, len) }; + if !way.carded() || way == Way::Card { + assert!(held == &wanted[..], "{way:?} round {round}: the copy"); + } + } + } + } + + /// Another thread brings a copy of the same view memory up to date, and + /// so makes it read-only again, between the opening of its guards and + /// the store: what shaders wrote arrives all the same. + #[test] + fn what_shaders_wrote_arrives_in_memory_that_is_guarded_again() { + for way in WAYS { + let len = way.len(); + let Some((start, shadow)) = copy(len, true, way.carded()) else { + continue; + }; + let stop = AtomicBool::new(false); + let lost = std::thread::scope(|s| { + s.spawn(|| { + while !stop.load(Ordering::Relaxed) { + assert!(crate::watch::title_memory_written_pages(start, len).is_some()); + } + }); + let _stop = Stop(&stop); + let mut lost = 0; + for round in 1..25u8 { + way.run(&shadow, start, len, |i| i.is_multiple_of(4099).then_some(round)); + for i in (0..len).step_by(4099) { + // SAFETY: title memory. + lost += usize::from(unsafe { ((start + i) as *const u8).read_volatile() } != round); + } + } + lost + }); + println!("{way:?}: {lost} bytes shaders wrote did not arrive"); + if crate::putback::on() { + assert_eq!(lost, 0, "{way:?}"); + } + } + } + + /// A write that goes round the title's own view reaches the copy once + /// it is told (`crate::watch::writing`). + #[test] + fn a_write_round_the_view_reaches_the_copy_once_told() { + let len = LENS[0]; + // SAFETY: a section of ours seen at two addresses. + let (a, b) = unsafe { + let section = + CreateFileMappingW(INVALID_HANDLE_VALUE, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null()); + let views = [(); 2].map(|()| MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value as usize); + CloseHandle(section); + (views[0], views[1]) + }; + register(a, a as u64, len as u64); + let Some(shadow) = find(a as u64, len as u64) else { + return; // no host + }; + shadow.update(a, len); + let at = 5 * P + 9; + // SAFETY: the other view, and the copy's mapping. + unsafe { + ((b + at) as *mut u8).write_volatile(7); + crate::watch::writing(a + at, 1); + shadow.update(a, len); + assert_eq!(shadow.data.add(at).read_volatile(), 7); + } + } + + /// The merge beside title memory does what the merge into it does. + #[test] + fn the_two_merges_agree() { + let mut seed = 0xabcd_ef01_2345_6789u64; + let mut random = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + // Few values, so that bytes are often the same. + (seed >> 33) as u8 & 3 + }; + for n in (0..200).chain([4096]) { + let (now, held, title): (Vec<u8>, Vec<u8>, Vec<u8>) = + ((0..n).map(|_| random()).collect(), (0..n).map(|_| random()).collect(), (0..n).map(|_| random()).collect()); + let (mut held_a, mut title_a) = (held.clone(), title.clone()); + let (mut held_b, mut merged) = (held.clone(), vec![0xee; n]); + let changed = merge_piece(&now, &mut held_a, &mut title_a); + assert_eq!(merge_apart(&now, &mut held_b, &title, &mut merged), changed); + assert_eq!((held_a, title_a), (held_b, merged)); + } + } + + /// Bytes of a card copy's CPU side the card has not received are left + /// out of the relay's merge, whatever the scratch memory held. + #[test] + fn bytes_still_to_go_up_are_left_out() { + let Some((start, shadow)) = copy(LENS[1], false, true) else { + return; + }; + shadow.update(start, LENS[1]); + let card = shadow.card.as_ref().unwrap(); + *card.dirty.lock().unwrap() = vec![(100, 5000), (9000, 9001)]; + *card.sent.lock().unwrap() = vec![(20_000, 21_000, 7), (30_000, 31_000, 5), (60_000, 65_530, 6)]; + let mut scratch = vec![0xee; 3 * P]; + shadow.card_merge_relay(0, &[5; P], 5, &mut scratch); + // And one whose end is left out. + *card.dirty.lock().unwrap() = vec![(P + 600, P + 1000)]; + scratch.fill(0xee); + shadow.card_merge_relay(P, &[5; 1000], 9, &mut scratch); + for i in 0..1000 { + // SAFETY: title memory. + let there = unsafe { ((start + P + i) as *const u8).read_volatile() }; + assert_eq!(there, if i < 600 { 5 } else { 0 }, "byte {i} of the second"); + } + let left = |i: usize| { + (100..5000).contains(&i) || i == 9000 || (20_000..21_000).contains(&i) || (60_000..65_530).contains(&i) + }; + for i in 0..P { + // SAFETY: title memory, and the mapping of the copy's CPU side. + let (there, held) = unsafe { (((start + i) as *const u8).read_volatile(), shadow.data.add(i).read_volatile()) }; + let wanted = if left(i) { 0 } else { 5 }; + assert_eq!((there, held), (wanted, wanted), "byte {i}"); + } + } + + /// What the title wrote since the copy was brought up to date comes into + /// the copy with the merge (not the relay's, which leaves it to the + /// refresh), and a card copy sends the merge's result up. + #[test] + fn the_copy_takes_the_titles_bytes_with_the_merge() { + for way in [Way::Waited, Way::Card] { + let len = way.len(); + let Some((start, shadow)) = copy(len, false, way.carded()) else { + continue; + }; + shadow.update(start, len); + // SAFETY: title memory, and the copy's mapping. + let write = |at: usize, b: u8| unsafe { ((start + at) as *mut u8).write_volatile(b) }; + let held = |at: usize| unsafe { shadow.data.add(at).read_volatile() }; + if way == Way::Waited { + declare(&shadow, start, len); + // SAFETY: inside the copy's mapping. + unsafe { + shadow.data.add(10).write_volatile(1); + shadow.data.add(30).write_volatile(3); + } + write(20, 2); + shadow.copy_back(start, len); + shadow.copy_back_done(&[(start, start + len)]); + } else { + let mut gpu = vec![0u8; P]; + (gpu[10], gpu[30]) = (1, 3); + write(20, 2); + shadow.card.as_ref().unwrap().dirty.lock().unwrap().clear(); + shadow.card_merge(0, &gpu, &mut Vec::new()); + assert_eq!(*shadow.card.as_ref().unwrap().dirty.lock().unwrap(), [(10, 31)], "sent up"); + } + assert_eq!([held(10), held(20), held(30)], [1, 2, 3], "{way:?}: the copy"); + // SAFETY: title memory. + let there = unsafe { std::slice::from_raw_parts(start as *const u8, 40) }; + assert_eq!([there[10], there[20], there[30]], [1, 2, 3], "{way:?}: title memory"); + } + } + + /// Title memory a page of which the title made read-only: that page is + /// left alone, the rest takes what shaders wrote. (After upstream's + /// pull request 1024.) + #[test] + fn a_page_the_title_made_read_only_is_left_alone() { + use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect}; + for way in WAYS { + let len = way.len(); + let Some((start, shadow)) = copy(len, false, way.carded()) else { + continue; + }; + shadow.update(start, len); + let mut old = 0; + // SAFETY: a page of ours. + assert_ne!(unsafe { VirtualProtect((start + 3 * P) as *const _, 4096, PAGE_READONLY, &mut old) }, 0); + way.run(&shadow, start, len, |_| Some(1)); + for i in 0..len { + // SAFETY: title memory. + let there = unsafe { ((start + i) as *const u8).read_volatile() }; + let wanted = u8::from(!(3 * P..3 * P + 4096).contains(&i)); + assert_eq!(there, wanted, "{way:?} byte {i:#x}"); + } + } + } + + /// How long a copy-back takes: `cargo test --release ... back_speed -- + /// --ignored --nocapture`, with and without `VICTORY_EXACT_BACK=0`. + #[test] + #[ignore = "a measurement"] + fn back_speed() { + type Wrote = fn(usize) -> Option<u8>; + // A frame's worth: 1,000 pieces, what shaders wrote in each. + const PIECES: usize = 1000; + let patterns: [(&str, Wrote); 7] = [ + ("every byte", |i| Some((i >> 7) as u8 | 1)), + ("three bytes of four", |i| (i % 4 != 3).then_some((i >> 7) as u8 | 1)), + ("every second byte", |i| (i % 2 == 0).then_some(1)), + ("16 bytes of 64", |i| (i % 64 < 16).then_some(1)), + ("4 bytes of 64", |i| (i % 64 < 4).then_some(1)), + ("4 bytes of 1024", |i| (i % 1024 < 4).then_some(1)), + ("4 bytes of a piece", |i| (i % P < 4).then_some(1)), + ]; + for way in WAYS { + let len = if way.carded() { PIECES * P } else { 15 * P }; + let copies = if way.carded() { 1 } else { PIECES / 15 }; + let made: Vec<(usize, Arc<Shadow>)> = (0..copies).filter_map(|_| copy(len, false, way.carded())).collect(); + if made.len() < copies { + continue; + } + for (name, wrote) in patterns { + let gpu: Vec<u8> = (0..len).map(|i| wrote(i).unwrap_or(0)).collect(); + let mut times: Vec<f64> = (0..15) + .map(|_| { + // Title memory back to zeros, and the copy with it. + for (start, shadow) in &made { + // SAFETY: title memory. + unsafe { std::ptr::write_bytes(*start as *mut u8, 0, len) }; + shadow.update(*start, len); + if !way.carded() { + declare(shadow, *start, len); + // SAFETY: the copy's mapping. + unsafe { std::ptr::copy_nonoverlapping(gpu.as_ptr(), shadow.data, len) }; + } else { + shadow.card.as_ref().unwrap().dirty.lock().unwrap().clear(); + } + } + let (mut now, mut scratch) = (Vec::new(), Vec::new()); + let mut took = std::time::Duration::ZERO; + for (start, shadow) in &made { + let found: Vec<(usize, usize)> = (0..len / P).map(|p| (p * P, P)).collect(); + let began = std::time::Instant::now(); + match way { + Way::Waited => { + shadow.copy_back_with(*start, len, Some(found)); + } + Way::Relay => { + for (at, n) in found { + shadow.relay_merge(at, n, &mut now, &mut scratch); + } + } + Way::Card => { + for (at, n) in found { + shadow.card_merge(at, &gpu[at..at + n], &mut scratch); + } + } + Way::CardRelay => { + for (at, n) in found { + shadow.card_merge_relay(at, &gpu[at..at + n], u64::MAX, &mut scratch); + } + } + } + took += began.elapsed(); + } + for (start, shadow) in &made { + shadow.copy_back_done(&[(*start, *start + len)]); + } + took.as_secs_f64() * 1e3 * PIECES as f64 / (copies * len / P) as f64 + }) + .collect(); + times.sort_by(f64::total_cmp); + println!( + "{} {way:?} | {name} | {:.2} ms per 1,000 pieces (best {:.2}, worst {:.2})", + if crate::putback::on() { "exact" } else { "whole" }, + times[times.len() / 2], + times[0], + times[times.len() - 1] + ); + } + for (start, _) in made { + // SAFETY: memory of `title`'s. + unsafe { VirtualFree(start as *mut _, 0, MEM_RELEASE) }; + } + } + } +} diff --git a/crates/victory-hle/src/modules/memory.rs b/crates/victory-hle/src/modules/memory.rs new file mode 100644 index 0000000..1c094ea --- /dev/null +++ b/crates/victory-hle/src/modules/memory.rs @@ -0,0 +1,172 @@ +//! The title's own frees and unmappings of memory: the host's, but not +//! while the GPU side puts what shaders wrote into title memory +//! (`victory_gpu::title_memory_releasing`). Between its read of a stretch +//! and its store into it, the stretch must not become other memory at the +//! same address. +//! +//! The title's imports of these and its lookups by name come here; a free +//! from inside the host (its heaps) or by a direct system call does not. +#![allow(non_snake_case)] +// Title code calls these through its import table, passing pointers the real +// API would trust. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +use std::ffi::c_void; + +use super::files::host; +use crate::{HleModule, hle_export}; + +pub extern "system" fn VirtualFree(address: *mut c_void, size: usize, kind: u32) -> i32 { + let _releasing = victory_gpu::title_memory_releasing(); + host!("kernel32.dll", "VirtualFree": extern "system" fn(*mut c_void, usize, u32) -> i32)( + address, size, kind, + ) +} + +pub extern "system" fn VirtualFreeEx( + process: *mut c_void, + address: *mut c_void, + size: usize, + kind: u32, +) -> i32 { + let _releasing = victory_gpu::title_memory_releasing(); + host!("kernel32.dll", "VirtualFreeEx": extern "system" fn(*mut c_void, *mut c_void, usize, u32) -> i32)( + process, address, size, kind, + ) +} + +pub extern "system" fn UnmapViewOfFile(address: *const c_void) -> i32 { + let _releasing = victory_gpu::title_memory_releasing(); + host!("kernel32.dll", "UnmapViewOfFile": extern "system" fn(*const c_void) -> i32)(address) +} + +pub extern "system" fn UnmapViewOfFileEx(address: *const c_void, flags: u32) -> i32 { + let _releasing = victory_gpu::title_memory_releasing(); + host!("kernel32.dll", "UnmapViewOfFileEx": extern "system" fn(*const c_void, u32) -> i32)( + address, flags, + ) +} + +pub extern "system" fn UnmapViewOfFile2( + process: *mut c_void, + address: *const c_void, + flags: u32, +) -> i32 { + let _releasing = victory_gpu::title_memory_releasing(); + host!("kernelbase.dll", "UnmapViewOfFile2": extern "system" fn(*mut c_void, *const c_void, u32) -> i32)( + process, address, flags, + ) +} + +pub(crate) fn module() -> HleModule { + HleModule { + name: "memory", + dlls: &["kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-*"], + exports: vec![ + hle_export!(VirtualFree), + hle_export!(VirtualFreeEx), + hle_export!(UnmapViewOfFile), + hle_export!(UnmapViewOfFileEx), + hle_export!(UnmapViewOfFile2), + ], + } +} + +#[cfg(test)] +mod tests { + use super::*; + use windows_sys::Win32::Foundation::{GetLastError, SetLastError}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, + }; + + /// The host's answers and errors come through, and the title's imports + /// and lookups by name end here, from each of the DLLs that have them. + #[test] + fn frees_go_to_the_host() { + for dll in [ + "KERNEL32.dll", + "kernelbase.dll", + "api-ms-win-core-memory-l1-1-0.dll", + ] { + assert_eq!( + crate::registry::lookup(dll, "VirtualFree"), + Some(VirtualFree as *const () as usize) + ); + assert_eq!( + crate::registry::lookup(dll, "UnmapViewOfFile"), + Some(UnmapViewOfFile as *const () as usize) + ); + assert_eq!( + crate::registry::lookup(dll, "VirtualAlloc"), + None, + "the host's own" + ); + } + // SAFETY: memory of our own, and an address that holds none. + unsafe { + let p = VirtualAlloc( + std::ptr::null(), + 0x1000, + MEM_RESERVE | MEM_COMMIT, + PAGE_READWRITE, + ); + assert!(!p.is_null()); + assert_eq!( + VirtualFree(p, 0x1000, MEM_RELEASE), + 0, + "a size with a release" + ); + assert_eq!(GetLastError(), 87); + assert_ne!(VirtualFree(p, 0, MEM_RELEASE), 0); + SetLastError(0); + assert_eq!(VirtualFree(p, 0, MEM_RELEASE), 0, "free already"); + assert_eq!(GetLastError(), 487); + assert_eq!(UnmapViewOfFile(p), 0); + assert_eq!(GetLastError(), 487); + } + } + + /// Each of them waits for bytes on their way into title memory. + #[test] + fn frees_wait_for_what_shaders_wrote() { + let waits = |free: fn() -> i32| { + let putting = victory_gpu::title_memory_putting_back(); + let (done, came) = std::sync::mpsc::channel(); + let thread = std::thread::spawn(move || { + free(); + let _ = done.send(()); + }); + let early = came + .recv_timeout(std::time::Duration::from_millis(50)) + .is_ok(); + drop(putting); + thread.join().unwrap(); + !early + }; + let expected = std::env::var("VICTORY_EXACT_BACK").map_or(true, |v| v.trim() != "0"); + const NULL: *mut c_void = std::ptr::null_mut(); + let frees: [fn() -> i32; 6] = [ + || VirtualFree(NULL, 0, MEM_RELEASE), + || VirtualFreeEx(-1isize as _, NULL, 0, MEM_RELEASE), + || UnmapViewOfFile(NULL), + || UnmapViewOfFileEx(NULL, 0), + || UnmapViewOfFile2(-1isize as _, NULL, 0), + || { + super::super::xmem::XMemFreeDefault( + FREED.load(std::sync::atomic::Ordering::Relaxed) as _, + ATTRIBUTES, + ); + 0 + }, + ]; + static FREED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + const ATTRIBUTES: u64 = super::super::xmem::ALLOC_32BIT; + let p = super::super::xmem::XMemAllocDefault(0x1_0000, ATTRIBUTES); + assert!(!p.is_null()); + FREED.store(p as usize, std::sync::atomic::Ordering::Relaxed); + for (i, free) in frees.into_iter().enumerate() { + assert_eq!(waits(free), expected, "{i}"); + } + } +} diff --git a/crates/victory-hle/src/modules/mod.rs b/crates/victory-hle/src/modules/mod.rs index 51e3590..2c0cfa9 100644 --- a/crates/victory-hle/src/modules/mod.rs +++ b/crates/victory-hle/src/modules/mod.rs @@ -25,6 +25,8 @@ pub mod lifecycle; #[cfg(windows)] pub mod media; #[cfg(windows)] +pub mod memory; +#[cfg(windows)] pub mod net; pub mod speech; pub mod storage; @@ -67,6 +69,8 @@ pub(crate) fn all() -> Vec<HleModule> { #[cfg(windows)] all.push(net::module()); #[cfg(windows)] + all.push(memory::module()); + #[cfg(windows)] all.push(xmem::module()); #[cfg(windows)] all.push(xsystem::module()); diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index 5f717bf..ddd5809 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -206,7 +206,7 @@ pub extern "system" fn XMemVirtualQuery( // `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up // from 2), then the memory type, then bit 33: a 32-bit address. const ALIGNMENT_SHIFT: u64 = 24; -const ALLOC_32BIT: u64 = 1 << 33; +pub(crate) const ALLOC_32BIT: u64 = 1 << 33; /// Our block header: the block's size and alignment, just below the /// pointer handed out. const HEADER: usize = 2 * size_of::<usize>(); @@ -318,6 +318,7 @@ pub extern "system" fn XMemFreeDefault(address: *mut c_void, attributes: u64) { // whole reservation, or a header-prefixed block. unsafe { if attributes & ALLOC_32BIT != 0 { + let _releasing = victory_gpu::title_memory_releasing(); VirtualFree(address, 0, MEM_RELEASE); return; } ```` </details>
This discussion has been locked. Commenting is limited to contributors.
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.

Dependencies

No dependencies set

Reference
github/fxceless--victory-fork#690
No description provided.