GPU: drop overlapping write-watch pins on title_memory_remapped (#174) #175

Open
KernelSmoker wants to merge 1 commit from upstream-pr/175 into main
KernelSmoker commented 2026-11-25 19:10:50 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by KernelSmoker on 2026-11-25T19:10:50Z.


Fixes #174.

What

  • crates/victory-gpu/src/watch.rs:
    • Added Guards::drop_pins(from, to) -> bool, which removes remapped block range [from, to) from active writing() pins, splitting any pin that extends outside [from, to) so neighboring still-live blocks stay pinned.
    • Called g.drop_pins(from, to) in title_memory_remapped alongside clearing protected, clean, holes, and aliased, and included dropped_pins in changed so region epochs bump consistently.
    • Added two regression tests:
      • remapping_drops_overlapping_pins_and_keeps_adjacent_ones (pure unit test for disjoint, wholly contained, partial left/right overlap, and middle-split pin ranges)
      • remapped_view_does_not_inherit_pins_from_earlier_writing (maps a 2-block pagefile view, calls writing(), unmaps + calls title_memory_remapped, verifies the pin is cleared, and verifies a fresh view is guarded cleanly rather than staying pinned).

Why

As diagnosed in #174, title_memory_remapped cleared protected, clean, holes, and aliased, but left 2-second writing() pins in g.pins. When a new view was mapped at the same virtual address within 2 seconds (for example in parallel watch::tests runs after kernel_reads_into_guarded_blocks_after_opening), guard() found the stale pin, kept the new view writable, and falsely reported it written on every check.

Dropping only the remapped [from, to) block range ensures an unmapped/remapped virtual range never leaks stale pins onto a newly mapped view, while keeping pins intact on any neighboring blocks outside the remapped range.

Tested

Bazzite Linux 45 (x86_64), Rust 1.98.1, cross-targeting x86_64-pc-windows-gnu (tested under GE-Proton 10-34 / Wine 10.0; not a native Windows 11 run):

  • cargo check --workspace --all-targets --all-features --locked --target x86_64-pc-windows-gnu: passed.
  • cargo clippy -p victory-gpu --no-deps --all-targets --locked --target x86_64-pc-windows-gnu: 0 new warnings in watch.rs.
  • cargo xtask policy --staged: asset policy: 1 files ok.
  • victory_gpu ... watch::tests (default parallel test threads): 30/30 runs passed (9 passed, 0 failed per run).
  • victory_gpu ... watch::tests --test-threads=1: 5/5 runs passed (9 passed, 0 failed per run).

No game files were used and the title was not run for this patch.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:issue:6611765659 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/175). Originally posted by [KernelSmoker](https://github.com/KernelSmoker) on 2026-11-25T19:10:50Z. --- Fixes #174. ## What - `crates/victory-gpu/src/watch.rs`: - Added `Guards::drop_pins(from, to) -> bool`, which removes remapped block range `[from, to)` from active `writing()` pins, splitting any pin that extends outside `[from, to)` so neighboring still-live blocks stay pinned. - Called `g.drop_pins(from, to)` in `title_memory_remapped` alongside clearing `protected`, `clean`, `holes`, and `aliased`, and included `dropped_pins` in `changed` so region epochs bump consistently. - Added two regression tests: - `remapping_drops_overlapping_pins_and_keeps_adjacent_ones` (pure unit test for disjoint, wholly contained, partial left/right overlap, and middle-split pin ranges) - `remapped_view_does_not_inherit_pins_from_earlier_writing` (maps a 2-block pagefile view, calls `writing()`, unmaps + calls `title_memory_remapped`, verifies the pin is cleared, and verifies a fresh view is guarded cleanly rather than staying pinned). ## Why As diagnosed in #174, `title_memory_remapped` cleared `protected`, `clean`, `holes`, and `aliased`, but left 2-second `writing()` pins in `g.pins`. When a new view was mapped at the same virtual address within 2 seconds (for example in parallel `watch::tests` runs after `kernel_reads_into_guarded_blocks_after_opening`), `guard()` found the stale pin, kept the new view writable, and falsely reported it written on every check. Dropping only the remapped `[from, to)` block range ensures an unmapped/remapped virtual range never leaks stale pins onto a newly mapped view, while keeping pins intact on any neighboring blocks outside the remapped range. ## Tested Bazzite Linux 45 (x86_64), Rust 1.98.1, cross-targeting `x86_64-pc-windows-gnu` (tested under GE-Proton 10-34 / Wine 10.0; not a native Windows 11 run): - `cargo check --workspace --all-targets --all-features --locked --target x86_64-pc-windows-gnu`: passed. - `cargo clippy -p victory-gpu --no-deps --all-targets --locked --target x86_64-pc-windows-gnu`: 0 new warnings in `watch.rs`. - `cargo xtask policy --staged`: `asset policy: 1 files ok`. - `victory_gpu ... watch::tests` (default parallel test threads): **30/30 runs passed** (9 passed, 0 failed per run). - `victory_gpu ... watch::tests --test-threads=1`: **5/5 runs passed** (9 passed, 0 failed per run). No game files were used and the title was not run for this patch.
adrianmjim commented 2026-11-25 21:56:41 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by adrianmjim on 2026-11-25T21:56:41Z.


I measured this on native Windows 11 (build 26300) with an RX 7900 XT and Rust 1.98.1. The description's runs were under Wine with watch:: only, and in #174 these tests never failed with watch:: alone. So I ran the full victory-gpu lib test binary with default test threads, for main (000ffdd) and for this branch (66c6d4f), each built in its own tree. That was 140 runs each, interleaved, with the first one in each round alternating (100 in one session, 40 in a second).

The three tests from #174:

  • main: 19 of 139 completed runs had one of them (a_view_mapped_beside_a_guarded_one_makes_it_check_again 12, a_write_through_another_view_is_reported_at_the_guarded_one 5, a_write_is_reported_at_every_checked_view 2). One more main run stopped without a result.
  • this branch: 0 of 140. Both new tests passed in all 140 runs.

Other failures I saw on both trees (this branch / main):

  • pipeline::depth_bounds_test::depth_bounds_control_a_title_draw ("host refused the depth bounds pipeline"): 17 / 11
  • watch::tests::written_pages_are_reported_to_every_asker at before.is_empty(): 11 / 9
  • a few one-off query/queue failures. Each of them has also failed on main, here or in my earlier runs.

frame::tests::waits_end_on_ticks_and_count_frames failed more often on this branch in the full runs: 80 vs 59. In 29 rounds only this branch failed it, and in 8 rounds only main did. The machine was under heavy CPU load from other work during most of these runs, but the two trees were interleaved, so load alone does not explain the 29 against 8. Run on its own (frame::, 60 runs each, interleaved), it failed 34 times here and 35 on main. frame.rs is not touched, and its failing assert (line 252) checks flip ticks 5 ms apart. My guess is timing between the tests running at the same time in the full binary, not a path from the pins to frame, but I have not found what makes the difference.

On the rule: the local experiment in #174 dropped only pins wholly inside the range. This PR also trims pins that reach past the range, which matters more in the title than in the tests. writing() pins every block a kernel read covers, while xmem calls title_memory_remapped once per view, and views can be a single 64 KiB page (the GPU's page mappings). With the wholly-inside rule, a read spanning several views would keep its pin on a remapped one. Here only the remapped blocks are cut out, and neighbouring blocks stay pinned. The floor/ceil edges are the same as for protected, holes and aliased. The caveat from #174 now applies to a few more blocks: a block whose pin is dropped is guarded again at its next check, so an asynchronous read issued before the remap that lands after it could fail. I have not checked whether the title does that.

Other open PRs that touch pins:

  • #67 (pins become a VecDeque): no textual conflict with this PR, but the merge does not build (checked locally with cargo check). self.pins = kept; in drop_pins and pins: vec![...] in the new test are Vec where a VecDeque is expected (E0308). .into() fixes both. drop_pins keeps the order and each piece keeps its until, so #67's dropping of ended pins from the front still holds.
  • #60: the conflicts are in text only (both add a Guards method after pinned and tests at the end of the module). With this PR, the guards().pins.retain(...) at the end of #60's new test is no longer needed.

A minor point about remapped_view_does_not_inherit_pins_from_earlier_writing: between UnmapViewOfFile and the !pinned assert, another test could map a view at the freed address and call writing() there, as kernel_reads_into_guarded_blocks_after_opening does. That would fail the assert. It did not happen in 140 runs.

Not tested: the title, and full runs with --test-threads=1.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:comment:7175738937 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/175#issuecomment-7175738937). Originally posted by [adrianmjim](https://github.com/adrianmjim) on 2026-11-25T21:56:41Z. --- I measured this on native Windows 11 (build 26300) with an RX 7900 XT and Rust 1.98.1. The description's runs were under Wine with `watch::` only, and in #174 these tests never failed with `watch::` alone. So I ran the full `victory-gpu` lib test binary with default test threads, for main (000ffdd) and for this branch (66c6d4f), each built in its own tree. That was 140 runs each, interleaved, with the first one in each round alternating (100 in one session, 40 in a second). The three tests from #174: - main: 19 of 139 completed runs had one of them (`a_view_mapped_beside_a_guarded_one_makes_it_check_again` 12, `a_write_through_another_view_is_reported_at_the_guarded_one` 5, `a_write_is_reported_at_every_checked_view` 2). One more main run stopped without a result. - this branch: 0 of 140. Both new tests passed in all 140 runs. Other failures I saw on both trees (this branch / main): - `pipeline::depth_bounds_test::depth_bounds_control_a_title_draw` ("host refused the depth bounds pipeline"): 17 / 11 - `watch::tests::written_pages_are_reported_to_every_asker` at `before.is_empty()`: 11 / 9 - a few one-off query/queue failures. Each of them has also failed on main, here or in my earlier runs. `frame::tests::waits_end_on_ticks_and_count_frames` failed more often on this branch in the full runs: 80 vs 59. In 29 rounds only this branch failed it, and in 8 rounds only main did. The machine was under heavy CPU load from other work during most of these runs, but the two trees were interleaved, so load alone does not explain the 29 against 8. Run on its own (`frame::`, 60 runs each, interleaved), it failed 34 times here and 35 on main. `frame.rs` is not touched, and its failing assert (line 252) checks flip ticks 5 ms apart. My guess is timing between the tests running at the same time in the full binary, not a path from the pins to `frame`, but I have not found what makes the difference. On the rule: the local experiment in #174 dropped only pins wholly inside the range. This PR also trims pins that reach past the range, which matters more in the title than in the tests. `writing()` pins every block a kernel read covers, while xmem calls `title_memory_remapped` once per view, and views can be a single 64 KiB page (the GPU's page mappings). With the wholly-inside rule, a read spanning several views would keep its pin on a remapped one. Here only the remapped blocks are cut out, and neighbouring blocks stay pinned. The floor/ceil edges are the same as for `protected`, `holes` and `aliased`. The caveat from #174 now applies to a few more blocks: a block whose pin is dropped is guarded again at its next check, so an asynchronous read issued before the remap that lands after it could fail. I have not checked whether the title does that. Other open PRs that touch pins: - #67 (pins become a `VecDeque`): no textual conflict with this PR, but the merge does not build (checked locally with `cargo check`). `self.pins = kept;` in `drop_pins` and `pins: vec![...]` in the new test are `Vec` where a `VecDeque` is expected (E0308). `.into()` fixes both. `drop_pins` keeps the order and each piece keeps its `until`, so #67's dropping of ended pins from the front still holds. - #60: the conflicts are in text only (both add a `Guards` method after `pinned` and tests at the end of the module). With this PR, the `guards().pins.retain(...)` at the end of #60's new test is no longer needed. A minor point about `remapped_view_does_not_inherit_pins_from_earlier_writing`: between `UnmapViewOfFile` and the `!pinned` assert, another test could map a view at the freed address and call `writing()` there, as `kernel_reads_into_guarded_blocks_after_opening` does. That would fail the assert. It did not happen in 140 runs. Not tested: the title, and full runs with `--test-threads=1`.
gut0to commented 2026-11-26 15:56:21 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-26T15:56:21Z.

Review: COMMENTED


AI-assisted review. I checked the changed test code and its stated address-reuse scenario; I did not run the test suite or a game.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review:6077123614 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/175#pullrequestreview-6077123614). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-26T15:56:21Z. **Review:** COMMENTED --- AI-assisted review. I checked the changed test code and its stated address-reuse scenario; I did not run the test suite or a game.
gut0to commented 2026-11-26 15:56:21 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-26T15:56:21Z.

Code review location: crates/victory-gpu/src/watch.rs; line 1263

@@ -1158,4 +1178,105 @@ mod tests {
         unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) };
         title_memory_remapped(view, 2 * BLOCK);
     }
+
+    /// `Guards::drop_pins` removes only the remapped blocks from active pins,
+    /// splitting partially overlapping pins and leaving disjoint ones intact.
+    #[test]
+    fn remapping_drops_overlapping_pins_and_keeps_adjacent_ones() {
+        let until = std::time::Instant::now() + PIN;
+        let mut g = Guards {
+            protected: BTreeSet::new(),
+            clean: BTreeSet::new(),
+            holes: BTreeSet::new(),
+            aliased: BTreeSet::new(),
+            pins: vec![
+                (10, 12, until), // disjoint left
+                (14, 18, until), // right side overlaps [16, 20)
+                (17, 19, until), // wholly inside [16, 20)
+                (19, 23, until), // left side overlaps [16, 20)
+                (15, 22, until), // spans across [16, 20), splits into two
+                (25, 27, until), // disjoint right
+            ],
+        };
+        assert!(!g.drop_pins(30, 32));
+        assert!(g.drop_pins(16, 20));
+        assert_eq!(
+            g.pins,
+            vec![
+                (10, 12, until),
+                (14, 16, until),
+                (20, 23, until),
+                (15, 16, until),
+                (20, 22, until),
+                (25, 27, until),
+            ]
+        );
+        for b in 16..20 {
+            assert!(!g.pinned(b), "remapped block {b} must not stay pinned");
+        }
+        assert!(g.pinned(15));
+        assert!(g.pinned(20));
+    }
+
+    /// Unmapping and remapping a view clears any `writing()` pin on its blocks,
+    /// so a later view mapped at the same address is guarded cleanly instead
+    /// of inheriting the stale pin (#174).
+    #[test]
+    fn remapped_view_does_not_inherit_pins_from_earlier_writing() {
+        use windows_sys::Win32::System::Memory::{
+            CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
+        };
+        // SAFETY: a pagefile section of two blocks, mapped read-write.
+        let (section, view) = unsafe {
+            let section = CreateFileMappingW(
+                -1isize as _,
+                std::ptr::null(),
+                PAGE_READWRITE,
+                0,
+                (2 * BLOCK) as u32,
+                std::ptr::null(),
+            );
+            assert!(!section.is_null());
+            let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize;
+            (section, view)
+        };
+        assert_ne!(view, 0);
+        assert!(guard(view, view + 2 * BLOCK).is_some());
+        writing(view + 100, 13);
+        assert!(guards().pinned(view / BLOCK));
+
+        // SAFETY: our view.
+        unsafe {
+            UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS {
+                Value: view as *mut _,
+            });
+        }
+        title_memory_remapped(view, 2 * BLOCK);
+        assert!(
+            !guards().pinned(view / BLOCK),
+            "pin must not outlive title_memory_remapped"
+        );
+
+        // Map a fresh view; if it lands at the same address, guarding must
+        // protect it rather than reporting it written on every check.
+        // SAFETY: same live pagefile section, mapped read-write.
+        let view2 = unsafe { MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize };

AI-assisted static review: I inspected the changed test and its address-reuse claim; I did not run the test or a game. Could this request the old base with MapViewOfFileEx (and assert view2 == view)? MapViewOfFile may return a different free address, so this test can pass without exercising the stale-pin-at-the-same-address regression it says it covers.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review-comment:4710750016 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/175#discussion_r4710750016). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-26T15:56:21Z. **Code review location:** `crates/victory-gpu/src/watch.rs`; line 1263 ~~~~diff @@ -1158,4 +1178,105 @@ mod tests { unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; title_memory_remapped(view, 2 * BLOCK); } + + /// `Guards::drop_pins` removes only the remapped blocks from active pins, + /// splitting partially overlapping pins and leaving disjoint ones intact. + #[test] + fn remapping_drops_overlapping_pins_and_keeps_adjacent_ones() { + let until = std::time::Instant::now() + PIN; + let mut g = Guards { + protected: BTreeSet::new(), + clean: BTreeSet::new(), + holes: BTreeSet::new(), + aliased: BTreeSet::new(), + pins: vec![ + (10, 12, until), // disjoint left + (14, 18, until), // right side overlaps [16, 20) + (17, 19, until), // wholly inside [16, 20) + (19, 23, until), // left side overlaps [16, 20) + (15, 22, until), // spans across [16, 20), splits into two + (25, 27, until), // disjoint right + ], + }; + assert!(!g.drop_pins(30, 32)); + assert!(g.drop_pins(16, 20)); + assert_eq!( + g.pins, + vec![ + (10, 12, until), + (14, 16, until), + (20, 23, until), + (15, 16, until), + (20, 22, until), + (25, 27, until), + ] + ); + for b in 16..20 { + assert!(!g.pinned(b), "remapped block {b} must not stay pinned"); + } + assert!(g.pinned(15)); + assert!(g.pinned(20)); + } + + /// Unmapping and remapping a view clears any `writing()` pin on its blocks, + /// so a later view mapped at the same address is guarded cleanly instead + /// of inheriting the stale pin (#174). + #[test] + fn remapped_view_does_not_inherit_pins_from_earlier_writing() { + use windows_sys::Win32::System::Memory::{ + CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile, + }; + // SAFETY: a pagefile section of two blocks, mapped read-write. + let (section, view) = unsafe { + let section = CreateFileMappingW( + -1isize as _, + std::ptr::null(), + PAGE_READWRITE, + 0, + (2 * BLOCK) as u32, + std::ptr::null(), + ); + assert!(!section.is_null()); + let view = MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize; + (section, view) + }; + assert_ne!(view, 0); + assert!(guard(view, view + 2 * BLOCK).is_some()); + writing(view + 100, 13); + assert!(guards().pinned(view / BLOCK)); + + // SAFETY: our view. + unsafe { + UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { + Value: view as *mut _, + }); + } + title_memory_remapped(view, 2 * BLOCK); + assert!( + !guards().pinned(view / BLOCK), + "pin must not outlive title_memory_remapped" + ); + + // Map a fresh view; if it lands at the same address, guarding must + // protect it rather than reporting it written on every check. + // SAFETY: same live pagefile section, mapped read-write. + let view2 = unsafe { MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize }; ~~~~ --- AI-assisted static review: I inspected the changed test and its address-reuse claim; I did not run the test or a game. Could this request the old base with MapViewOfFileEx (and assert view2 == view)? MapViewOfFile may return a different free address, so this test can pass without exercising the stale-pin-at-the-same-address regression it says it covers.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/175:upstream-pr/175'
git switch 'upstream-pr/175'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/175'
git switch 'upstream-pr/175'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/175'
git switch 'upstream-pr/175'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/175'
git switch 'main'
git merge --squash 'upstream-pr/175'
git switch 'main'
git merge --ff-only 'upstream-pr/175'
git switch 'main'
git merge 'upstream-pr/175'
git push origin 'main'
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
Belobug/VIctory-Belobug-AMD!175
No description provided.