GPU: a copy into title memory snapshots from the bytes it is about to write #3239

Closed
borosf wants to merge 2 commits from upstream-pr/3241 into main
borosf commented 2026-11-26 14:19:40 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by borosf on 2026-11-26T14:19:40Z.


A host-to-title copy told the write tracker to keep the destination pages it had taken, and the tracker read each of them back out of the process to do it.

What it did per destination page

copy_mapped wraps every title-destination copy in watch::writing, which marks the pages changed and, for each armed page a tracker had taken, calls Changed::save:

let mut bytes = vec![0u8; PAGE].into_boxed_slice();   // 64 KiB allocation
if crate::host::read_into((page * PAGE) as *const u8, &mut bytes) { ... }  // 64 KiB ReadProcessMemory

A 64 KiB allocation, a 64 KiB zeroing and a 64 KiB ReadProcessMemory — a kernel transition — while the guards' lock is held, to snapshot a page whose new content the caller was holding in the very buffer it was about to copy from. Tracked::refreshed then lays those same bytes over the saved page again after the copy.

What it does now

watch::writing_from(at, len, src) hands the tracker the caller's buffer. Incoming::whole_page decides per page:

  • the copy covers the page whole → the page's bytes after the write are the caller's, so the snapshot is that page of the buffer: one memcpy, no kernel read, no zeroing;
  • the copy covers the page in part (the two ends of every copy) → still read back, which is why the read is spared where it is provably pointless rather than removed.

Keep makes the three states explicit — Nothing, ReadBack, From(...) — so the fault handler's own path (watch.rs's vectored handler), the Writing drop and a remap all keep exactly the behaviour they had.

Why the caller's bytes can stand in for the page

track_as takes a range's pages from runtime_pages, which accepts only mapped pool and view pages; g.holders therefore never contains a hole, so no page here can be one whose read-back would have failed and left nothing saved. That is the property the substitution rests on and the reason it needed no VirtualQuery.

Measured

Intel Arc B580, Windows 11, --release, 64 armed pages of a write-watched pool, 20 rounds:

cargo test --release -p victory-gpu --lib --locked -- --exact --ignored --nocapture \
  watch::tests::a_copy_saves_a_page_without_reading_it_back

read back:      4234 ns per page
from the copy:  1392 ns per page

−67 % on the snapshot a copy pays per destination page. Multiplying that by pages per frame is what the frame line's existing saved counter reports; this PR does not claim a frame-time number for the title.

Not changed, deliberately

The guards' lock is still held across the snapshot. Dropping it is not a free win: the comment at changed records why the save must precede any page being opened — once a page is open another thread's write lands without a fault, and a save after it keeps that write as the page's old bytes. What is removed here is the kernel read, not the lock.

Verification

  • cargo clippy -p victory-gpu --all-targets --locked -- -D warnings — clean.
  • cargo clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings — clean.
  • cargo test -p victory-gpu --lib --locked --no-fail-fast — 230 passed, 2 failed, both the known Intel baseline failures pristine main also fails (descriptor::host::tests::dynamic_slots_are_held_until_released, memory::tests::lists_share_a_table_and_copies_keep_their_views, #1744/#1829).
  • New test watch::tests::a_copy_saves_the_bytes_it_is_about_to_write: two whole pages keep the copy's bytes, the partly covered third page keeps what was there before the copy, and a byte written before arming is still in it.
  • rustfmt --edition 2024 --check, hunk counts against main: watch.rs 39/39, host.rs 85/85 — no new formatting hunks.

The other writing callers (shadow.rs's copy-back and texture uploads, list.rs's uploads) hold their bytes too and are the natural follow-up; they are left out here to keep this to the one path with a measured number.

Synthetic tests only; no game data.

Part of the fifteen gaps claimed for this sweep on #1633. AI-assisted.

<!-- greyfinch-sync:Marvisak/VIctory:issue:6628625798 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3241). Originally posted by [borosf](https://github.com/borosf) on 2026-11-26T14:19:40Z. --- A host-to-title copy told the write tracker to keep the destination pages it had taken, and the tracker read each of them back out of the process to do it. ## What it did per destination page `copy_mapped` wraps every title-destination copy in `watch::writing`, which marks the pages changed and, for each armed page a tracker had taken, calls `Changed::save`: ```rust let mut bytes = vec![0u8; PAGE].into_boxed_slice(); // 64 KiB allocation if crate::host::read_into((page * PAGE) as *const u8, &mut bytes) { ... } // 64 KiB ReadProcessMemory ``` A 64 KiB allocation, a 64 KiB zeroing and a 64 KiB `ReadProcessMemory` — a kernel transition — **while the guards' lock is held**, to snapshot a page whose new content the caller was holding in the very buffer it was about to copy from. `Tracked::refreshed` then lays those same bytes over the saved page again after the copy. ## What it does now `watch::writing_from(at, len, src)` hands the tracker the caller's buffer. `Incoming::whole_page` decides per page: - the copy covers the page **whole** → the page's bytes after the write are the caller's, so the snapshot *is* that page of the buffer: one `memcpy`, no kernel read, no zeroing; - the copy covers the page **in part** (the two ends of every copy) → still read back, which is why the read is spared where it is provably pointless rather than removed. `Keep` makes the three states explicit — `Nothing`, `ReadBack`, `From(...)` — so the fault handler's own path (`watch.rs`'s vectored handler), the `Writing` drop and a remap all keep exactly the behaviour they had. ## Why the caller's bytes can stand in for the page `track_as` takes a range's pages from `runtime_pages`, which accepts only mapped pool and view pages; `g.holders` therefore never contains a hole, so no page here can be one whose read-back would have failed and left nothing saved. That is the property the substitution rests on and the reason it needed no `VirtualQuery`. ## Measured Intel Arc B580, Windows 11, `--release`, 64 armed pages of a write-watched pool, 20 rounds: ``` cargo test --release -p victory-gpu --lib --locked -- --exact --ignored --nocapture \ watch::tests::a_copy_saves_a_page_without_reading_it_back read back: 4234 ns per page from the copy: 1392 ns per page ``` **−67 % on the snapshot a copy pays per destination page.** Multiplying that by pages per frame is what the frame line's existing `saved` counter reports; this PR does not claim a frame-time number for the title. ## Not changed, deliberately The guards' lock is still held across the snapshot. Dropping it is not a free win: the comment at `changed` records why the save must precede any page being opened — once a page is open another thread's write lands without a fault, and a save after it keeps that write as the page's old bytes. What is removed here is the kernel read, not the lock. ## Verification - `cargo clippy -p victory-gpu --all-targets --locked -- -D warnings` — clean. - `cargo clippy -p victory-gpu --all-targets --all-features --locked -- -D warnings` — clean. - `cargo test -p victory-gpu --lib --locked --no-fail-fast` — 230 passed, 2 failed, both the known Intel baseline failures pristine `main` also fails (`descriptor::host::tests::dynamic_slots_are_held_until_released`, `memory::tests::lists_share_a_table_and_copies_keep_their_views`, #1744/#1829). - New test `watch::tests::a_copy_saves_the_bytes_it_is_about_to_write`: two whole pages keep the copy's bytes, the partly covered third page keeps what was there before the copy, and a byte written before arming is still in it. - `rustfmt --edition 2024 --check`, hunk counts against `main`: `watch.rs` 39/39, `host.rs` 85/85 — no new formatting hunks. The other `writing` callers (`shadow.rs`'s copy-back and texture uploads, `list.rs`'s uploads) hold their bytes too and are the natural follow-up; they are left out here to keep this to the one path with a measured number. Synthetic tests only; no game data. Part of the fifteen gaps claimed for this sweep on #1633. AI-assisted.
upstream-sync closed this pull request 2026-11-26 15:02:11 +00:00
Dukestar69 commented 2026-11-26 15:02:12 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by Dukestar69 on 2026-11-26T14:33:21Z.

Review: COMMENTED


Reviewed the diff and ran local verification on Windows 11 x64 (cargo test -p victory-gpu --lib watch:: -- --test-threads=1: 16 passed, 1 ignored; cargo clippy -p victory-gpu --all-targets -- -D warnings: clean; cargo xtask policy: 191 files ok).

I cannot approve this as-is because there are two correctness/soundness issues with saving src (the incoming bytes) as the tracker's saved snapshot:

  1. Inverts the 3-way merge in shadow.rs (merge_writeback) and clobbers the copy's own writes:
    Changed::save records the pre-write baseline (efore) matching what the GPU shadow (host) started with before the shader ran. In crates/victory-gpu/src/shadow.rs (copy_back_page, lines 515-523), merge_writeback(&mut title, host, before) decides which bytes the GPU modified by testing host[i] != before[i] and copying host[i] into itle[i].
    If efore is instead set to the new incoming bytes src, then for every byte i that copy_mapped changed (src[i] != old[i]) and the GPU did not touch (host[i] == old[i]), host[i] != before[i] evaluates to rue — so merge_writeback treats old[i] as a GPU write and overwrites the newly copied byte in itle back to old[i].
  2. Unsound userspace dereference of src in copy_mapped:
    copy_mapped explicitly uses ReadProcessMemory (
    ead(src, dst, len)) with a 64 KiB / 4 KiB fallback specifically because src is not guaranteed to be mapped/readable across all len bytes (see host.rs lines 2474-2476 and 2503-2530). Calling unsafe { std::slice::from_raw_parts(src, PAGE) } inside Changed::save dereferences src directly without ReadProcessMemory, which will fault/crash if src contains an unmapped or PAGE_NOACCESS page (and if
    ead fails and itle_dst && !committed(dst, len) returns early, dst was never even written).

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

<!-- greyfinch-sync:Marvisak/VIctory:review:6075895875 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3241#pullrequestreview-6075895875). Originally posted by [Dukestar69](https://github.com/Dukestar69) on 2026-11-26T14:33:21Z. **Review:** COMMENTED --- Reviewed the diff and ran local verification on Windows 11 x64 (cargo test -p victory-gpu --lib watch:: -- --test-threads=1: 16 passed, 1 ignored; cargo clippy -p victory-gpu --all-targets -- -D warnings: clean; cargo xtask policy: 191 files ok). I cannot approve this as-is because there are two correctness/soundness issues with saving src (the incoming bytes) as the tracker's saved snapshot: 1. **Inverts the 3-way merge in shadow.rs (merge_writeback) and clobbers the copy's own writes:** Changed::save records the **pre-write** baseline (efore) matching what the GPU shadow (host) started with before the shader ran. In crates/victory-gpu/src/shadow.rs (copy_back_page, lines 515-523), merge_writeback(&mut title, host, before) decides which bytes the GPU modified by testing host[i] != before[i] and copying host[i] into itle[i]. If efore is instead set to the **new** incoming bytes src, then for every byte i that copy_mapped changed (src[i] != old[i]) and the GPU did *not* touch (host[i] == old[i]), host[i] != before[i] evaluates to rue — so merge_writeback treats old[i] as a GPU write and overwrites the newly copied byte in itle back to old[i]. 2. **Unsound userspace dereference of src in copy_mapped:** copy_mapped explicitly uses ReadProcessMemory ( ead(src, dst, len)) with a 64 KiB / 4 KiB fallback specifically because src is not guaranteed to be mapped/readable across all len bytes (see host.rs lines 2474-2476 and 2503-2530). Calling unsafe { std::slice::from_raw_parts(src, PAGE) } inside Changed::save dereferences src directly without ReadProcessMemory, which will fault/crash if src contains an unmapped or PAGE_NOACCESS page (and if ead fails and itle_dst && !committed(dst, len) returns early, dst was never even written). Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
borosf commented 2026-11-26 15:02:33 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by borosf on 2026-11-26T14:43:24Z.


Closing as unsound — the review is correct on both points, and I verified both against the code before reverting:

1. It clobbers the copy's own writes in the 3-way merge. merge_writeback's own oracle test (shadow.rs:40-62) defines old as the pre-copy baseline: host[i] == old[i] → keep the title's byte (which the copy just wrote), else take the host's. Tracked::refreshed — the only thing that lays copy bytes over saved — is called solely in the title→host direction (Shadow::copy, shadow.rs:688, title_dst = false). For a title_dst = true Step::Copy, saved must therefore remain the pre-write page bytes. With saved = src, every byte the copy changed and the GPU did not touch (host[i] == true_old[i], old[i] = src[i]) satisfies host[i] != old[i] and gets written back as the pre-copy byte. The copy's write is reverted.

2. src is not safe to dereference. read() uses ReadProcessMemory with a 64 KiB/4 KiB fallback precisely because src may contain unmapped pages (host.rs:2517-2530); std::slice::from_raw_parts(src, PAGE) in Changed::save faults on those. A page inside [at, at+len) being in g.holders says nothing about src at that offset.

Both are structural, not fixable by validating the pointer: the merge needs pre-write bytes, which src cannot provide. Reverted at 0c78456efe2515c09437d6979f19ec837d0e0cff (branch now equals main plus the revert).

Finding worth keeping (measured on Intel Arc B580, --release, 64 armed pages, 20 rounds): the snapshot a title_dst copy pays per destination page is 4,234 ns when read back via ReadProcessMemory (64 KiB alloc + zero + kernel read, under the guards' lock). Any fix must keep saved = pre-write bytes and not dereference src — e.g. snapshot from a validated copy of src made only after read reports the range whole, accepting that the save then follows the write for those pages (which the merge tolerates only where the copy covers the page, since the title byte is already the copy's). That design needs its own review; I am not claiming it here.

Synthetic tests only; no game data.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7195228009 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3241#issuecomment-7195228009). Originally posted by [borosf](https://github.com/borosf) on 2026-11-26T14:43:24Z. --- Closing as unsound — the review is correct on both points, and I verified both against the code before reverting: **1. It clobbers the copy's own writes in the 3-way merge.** `merge_writeback`'s own oracle test (shadow.rs:40-62) defines `old` as the pre-copy baseline: `host[i] == old[i]` → keep the title's byte (which the copy just wrote), else take the host's. `Tracked::refreshed` — the only thing that lays copy bytes over `saved` — is called solely in the title→host direction (`Shadow::copy`, shadow.rs:688, `title_dst = false`). For a `title_dst = true` `Step::Copy`, `saved` must therefore remain the **pre-write** page bytes. With `saved = src`, every byte the copy changed and the GPU did not touch (`host[i] == true_old[i]`, `old[i] = src[i]`) satisfies `host[i] != old[i]` and gets written back as the pre-copy byte. The copy's write is reverted. **2. `src` is not safe to dereference.** `read()` uses `ReadProcessMemory` with a 64 KiB/4 KiB fallback precisely because `src` may contain unmapped pages (host.rs:2517-2530); `std::slice::from_raw_parts(src, PAGE)` in `Changed::save` faults on those. A page inside `[at, at+len)` being in `g.holders` says nothing about `src` at that offset. Both are structural, not fixable by validating the pointer: the merge needs pre-write bytes, which `src` cannot provide. Reverted at `0c78456efe2515c09437d6979f19ec837d0e0cff` (branch now equals `main` plus the revert). **Finding worth keeping** (measured on Intel Arc B580, `--release`, 64 armed pages, 20 rounds): the snapshot a `title_dst` copy pays per destination page is **4,234 ns** when read back via `ReadProcessMemory` (64 KiB alloc + zero + kernel read, under the guards' lock). Any fix must keep `saved` = pre-write bytes *and* not dereference `src` — e.g. snapshot from a validated copy of `src` made only after `read` reports the range whole, accepting that the save then follows the write for those pages (which the merge tolerates only where the copy covers the page, since the title byte is already the copy's). That design needs its own review; I am not claiming it here. Synthetic tests only; no game data.
borosf commented 2026-11-26 15:02:33 +00:00 (Migrated from github.com)

Imported from Marvisak/VIctory. Originally posted by borosf on 2026-11-26T14:43:25Z.


Reverted as unsound (see comment): the src-bytes snapshot breaks merge_writeback's baseline and dereferences a possibly-unmapped src. Revert pushed at 0c78456.

<!-- greyfinch-sync:Marvisak/VIctory:comment:7195228503 --> Imported from [Marvisak/VIctory](https://github.com/Marvisak/VIctory/pull/3241#issuecomment-7195228503). Originally posted by [borosf](https://github.com/borosf) on 2026-11-26T14:43:25Z. --- Reverted as unsound (see comment): the src-bytes snapshot breaks merge_writeback's baseline and dereferences a possibly-unmapped src. Revert pushed at 0c78456.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
Marvisak/VIctory!3239
No description provided.