VICTORY_WC_NO_BACK=1: shaders' writes into write-combined title memory stay on the card (with a read census) #477

Open
icecreammule277-dot wants to merge 7 commits from upstream-pr/477 into a-publier
icecreammule277-dot commented 2026-11-27 05:19:54 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by icecreammule277-dot on 2026-11-27T05:19:54Z.


AI-assisted (Claude Code). Numbers and log lines only.

Builds on #476: its first two commits are that PR. Adds VICTORY_WC_NO_BACK=1 (off by default). Shaders' writes into title memory the title asked for as write-combined stay on the card. They aren't declared as written, so there's no snapshot, no compare and no copy-back. A census switch checks that the title doesn't read them.

Why

#476 showed that all of the copy-back in a heavy scene goes into write-combined memory. On the console the CPU writes such memory but doesn't read it back. This follows the console's own model: what the GPU wrote stays where the GPU wrote it. It's the same idea as fxceless/victory-fork issue #1169 and PR #1178 (lazy copy-back), but much narrower: no fault handler, and it's chosen by the protection the title asked for.

What it does

  • Which ranges stay on the card: a declared write (from lists or picked views) of 64 KiB or more (VICTORY_WC_NO_BACK_MIN_KB) that lies wholly in write-combined title memory. Its copy must also be in the card's memory and known to be write-watched.
    • Anything else is copied back as before: unwatched memory (a refresh couldn't tell what the CPU wrote) and copies in host memory (which hold the shaders' bytes themselves).
  • Refreshes:
    • The range is noted as the card's on its copy (Shadow::card_owns).
    • Where the memory is watched, pages the CPU writes still go up.
    • Where a refresh can't tell (memory not watched), the card's ranges are left out and counted. In the A/B below that count was 0.
  • VICTORY_WC_KEEP_STORES=1 (off): copies holding such ranges send up only the dwords the title changed, through the existing keep_stores path. A part the CPU writes only in part otherwise goes up whole, with older title bytes next to the CPU's. The trade-off is that exact sending misses a value written over the same value. It's separate because neither side has evidence yet.
  • VICTORY_WC_CENSUS=1 (diagnostics, needs VICTORY_WC_NO_BACK=1), after #1169's read census:
    • Once a second, every 4 KiB page of those ranges gets PAGE_GUARD. This is done holding the write guards' lock exclusively, and never on a block the guards keep read-only or one the kernel is writing for the title (kernel_writing takes the census's guards off).
    • A first handler counts each guard hit:
      • our own tagged paths (copy and texture refreshes, our copies);
      • the title's reads and writes, by instruction (named by module on the line);
      • touches in a guarded page outside the ranges.
  • All of it is counted on the VICTORY_WC_STATS line.

Results (diagnostics build, 7900 XTX, plus the PORT_* switches and VICTORY_WINDOWS_BAR_MB=1024)

Matched A/B: same save loaded, standing still, a 62-second window each, with the unwatched and host-memory copies copied back as above.

on off
frame (median) 67.7 ms (14.9 fps) 78.6 ms (12.8 fps)
copy-back 17.2 ms, 1.5 MB 34.8 ms, 23.5 MB
copies up 14.7 ms, 45 MB 20.2 ms, 75 MB
draws 8,942 7,211

The remaining copy-back time is mostly copies in host memory, which are still copied back.

Census: about 13 minutes of play with VICTORY_WC_CENSUS=1.

  • About 690 MB of ranges left on the card; about 900 MB of guards set over the run.
  • 0 title page reads.
  • Title writes: about 0.5 MB/s, about 92% from one store-only loop. It builds 64-byte records and writes them with two vmovups; the rest are similar packing loops. None of them load from their destination.
  • No guards came off for kernel file reads.
  • Gaps: about 20% of the ranges couldn't be guarded (read-only guard blocks, memory not committed), and a read after a write to the same page within the same second isn't seen.

Visual check: no difference seen. A foliage flicker that turned up shows with the switch off too, at the same spot.

Tests

cargo test -p victory-gpu --lib -- census:: wc:: shadow::: 40 passed. They cover the range set (join, cut, cover) and a census test on real guarded pages: a read, a write and a tagged touch are each counted once and go on. Built with --profile diag --features diagnostics.

🤖 Generated with Claude Code

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:issue:5521636448 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/477). Originally posted by [icecreammule277-dot](https://github.com/icecreammule277-dot) on 2026-11-27T05:19:54Z. --- *AI-assisted (Claude Code). Numbers and log lines only.* **Builds on #476:** its first two commits are that PR. Adds `VICTORY_WC_NO_BACK=1` (off by default). Shaders' writes into title memory the title asked for as write-combined stay on the card. They aren't declared as written, so there's no snapshot, no compare and no copy-back. A census switch checks that the title doesn't read them. ## Why #476 showed that all of the copy-back in a heavy scene goes into write-combined memory. On the console the CPU writes such memory but doesn't read it back. This follows the console's own model: what the GPU wrote stays where the GPU wrote it. It's the same idea as fxceless/victory-fork issue #1169 and PR #1178 (lazy copy-back), but much narrower: no fault handler, and it's chosen by the protection the title asked for. ## What it does - **Which ranges stay on the card:** a declared write (from lists or picked views) of 64 KiB or more (`VICTORY_WC_NO_BACK_MIN_KB`) that lies wholly in write-combined title memory. Its copy must also be in the card's memory and known to be write-watched. - Anything else is copied back as before: unwatched memory (a refresh couldn't tell what the CPU wrote) and copies in host memory (which hold the shaders' bytes themselves). - **Refreshes:** - The range is noted as the card's on its copy (`Shadow::card_owns`). - Where the memory is watched, pages the CPU writes still go up. - Where a refresh can't tell (memory not watched), the card's ranges are left out and counted. In the A/B below that count was 0. - **`VICTORY_WC_KEEP_STORES=1`** (off): copies holding such ranges send up only the dwords the title changed, through the existing `keep_stores` path. A part the CPU writes only in part otherwise goes up whole, with older title bytes next to the CPU's. The trade-off is that exact sending misses a value written over the same value. It's separate because neither side has evidence yet. - **`VICTORY_WC_CENSUS=1`** (diagnostics, needs `VICTORY_WC_NO_BACK=1`), after #1169's read census: - Once a second, every 4 KiB page of those ranges gets `PAGE_GUARD`. This is done holding the write guards' lock exclusively, and never on a block the guards keep read-only or one the kernel is writing for the title (`kernel_writing` takes the census's guards off). - A first handler counts each guard hit: - our own tagged paths (copy and texture refreshes, our copies); - the title's reads and writes, by instruction (named by module on the line); - touches in a guarded page outside the ranges. - All of it is counted on the `VICTORY_WC_STATS` line. ## Results (diagnostics build, 7900 XTX, plus the `PORT_*` switches and `VICTORY_WINDOWS_BAR_MB=1024`) **Matched A/B:** same save loaded, standing still, a 62-second window each, with the unwatched and host-memory copies copied back as above. | | on | off | |---|---|---| | frame (median) | **67.7 ms (14.9 fps)** | 78.6 ms (12.8 fps) | | copy-back | **17.2 ms, 1.5 MB** | 34.8 ms, 23.5 MB | | copies up | **14.7 ms, 45 MB** | 20.2 ms, 75 MB | | draws | 8,942 | 7,211 | The remaining copy-back time is mostly copies in host memory, which are still copied back. **Census:** about 13 minutes of play with `VICTORY_WC_CENSUS=1`. - About 690 MB of ranges left on the card; about 900 MB of guards set over the run. - **0 title page reads.** - Title writes: about 0.5 MB/s, about 92% from one store-only loop. It builds 64-byte records and writes them with two `vmovups`; the rest are similar packing loops. None of them load from their destination. - No guards came off for kernel file reads. - Gaps: about 20% of the ranges couldn't be guarded (read-only guard blocks, memory not committed), and a read after a write to the same page within the same second isn't seen. **Visual check:** no difference seen. A foliage flicker that turned up shows with the switch off too, at the same spot. ## Tests `cargo test -p victory-gpu --lib -- census:: wc:: shadow::`: 40 passed. They cover the range set (join, cut, cover) and a census test on real guarded pages: a read, a write and a tagged touch are each counted once and go on. Built with `--profile diag --features diagnostics`. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
MamaLeVrai commented 2026-11-27 07:01:46 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by MamaLeVrai on 2026-11-27T07:01:46Z.


Tested on an RX 6950 XT (RDNA 2), driver 32.0.21045.29003, Windows 11 build 26300, Rust 1.98.1, release. At 0834177: victory-gpu 401 passed, 0 failed, 34 ignored; victory-hle 162 passed, 0 failed, 2 ignored.

AI-assisted (Claude Code); no game data.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:comment:7212072356 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/477#issuecomment-7212072356). Originally posted by [MamaLeVrai](https://github.com/MamaLeVrai) on 2026-11-27T07:01:46Z. --- Tested on an RX 6950 XT (RDNA 2), driver 32.0.21045.29003, Windows 11 build 26300, Rust 1.98.1, release. At `0834177`: `victory-gpu` 401 passed, 0 failed, 34 ignored; `victory-hle` 162 passed, 0 failed, 2 ignored. AI-assisted (Claude Code); no game data.
gw1337x commented 2026-11-27 09:39:14 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gw1337x on 2026-11-27T09:39:14Z.


Tested in the title on RDNA 3: RX 7800 XT 16 GB, driver 32.0.32015.7029, Ryzen 7 9800X3D, 32 GB RAM, Windows 11 26200 (Memory Integrity off). Diagnostics builds (--profile diag --features diagnostics) of 0834177 and its base 4eb6cfd, same boot.

Settings: scripts/play.ps1 settings plus VICTORY_PORT_CONSTANTS/DESCRIPTORS/CBV/GUARD/JOURNAL=1, Series X profile, ray tracing off; the PR's runs add VICTORY_WC_NO_BACK=1. Method: 270 s hands-off from a Chapter I boat save; fps is the layer's 1 s figure from the window title, sampled every second, 45-265 s with 1000+ draws ("steady" from 205 s); per-frame figures from VICTORY_TIMELINE windows of 30 frames at 200 s and 240 s; screenshots every 5 s.

Run (order) Build steady fps (title / layer's log) frame card running / idle per frame
1 0834177 NO_BACK 30.0 / 30.0 32.8 ms 30.6-30.8 / 2.1-2.2 ms
2 4eb6cfd 29.0 / 28.6 34.1-34.2 ms 31.1-31.7 / 2.5-3.1 ms
3 0834177 NO_BACK 30.0 / 30.0 32.7-32.8 ms 31.0-31.1 / 1.5-1.9 ms
4 4eb6cfd 29.0 / 28.6 33.8-34.4 ms 31.8-32.2 / 2.0-2.2 ms
5, 6 0834177 NO_BACK - / 30.0, 30.0 - -
7 0834177 NO_BACK + VICTORY_WC_CENSUS=1 - / 30.0 - -

What showed:

  • With VICTORY_WC_NO_BACK=1 the steady figure is 30.0 in all five runs against 28.6 in the two base runs here; frames are about 1-1.5 ms shorter.
  • Active: the wc line reports 800-1,300 declarations a frame left on the card in the boat scene; 5-12 MB a frame of small ones still copied back.
  • Census (run 7): 545-589 MB of ranges guarded through the boat scene; the title touched 0.000 MB a second of them, read or written, in all 51 lines. Guard pass 0.7 ms. So in this scene the title's processor does not read what is left on the card.
  • Peak commit 33.7-34.4 GB in the five NO_BACK runs against 32.5-33.5 GB for the two base runs here (private peak 34.5-34.9 GB against 33.3-34.2 GB).
  • Picture: the 241 s shots match the base in runs 1, 5, 6 and 7. In run 3 the man's shirt on the boat is dark grey from 185 s to the end (same shirt and logo, the boat and his neck lit as in the others); in 19 other boat runs today (base and other PRs, checked at 241 s) it never was. One in five runs of the PR; I have not established whether it comes from the change or is the title's own variation.

Five runs of the PR with the switch, one scene, ray tracing off.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:comment:7214934563 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/477#issuecomment-7214934563). Originally posted by [gw1337x](https://github.com/gw1337x) on 2026-11-27T09:39:14Z. --- Tested in the title on RDNA 3: RX 7800 XT 16 GB, driver 32.0.32015.7029, Ryzen 7 9800X3D, 32 GB RAM, Windows 11 26200 (Memory Integrity off). Diagnostics builds (`--profile diag --features diagnostics`) of `0834177` and its base `4eb6cfd`, same boot. Settings: `scripts/play.ps1` settings plus `VICTORY_PORT_CONSTANTS/DESCRIPTORS/CBV/GUARD/JOURNAL=1`, Series X profile, ray tracing off; the PR's runs add `VICTORY_WC_NO_BACK=1`. Method: 270 s hands-off from a Chapter I boat save; fps is the layer's 1 s figure from the window title, sampled every second, 45-265 s with 1000+ draws ("steady" from 205 s); per-frame figures from `VICTORY_TIMELINE` windows of 30 frames at 200 s and 240 s; screenshots every 5 s. | Run (order) | Build | steady fps (title / layer's log) | frame | card running / idle per frame | |---|---|---|---|---| | 1 | `0834177` NO_BACK | 30.0 / 30.0 | 32.8 ms | 30.6-30.8 / 2.1-2.2 ms | | 2 | `4eb6cfd` | 29.0 / 28.6 | 34.1-34.2 ms | 31.1-31.7 / 2.5-3.1 ms | | 3 | `0834177` NO_BACK | 30.0 / 30.0 | 32.7-32.8 ms | 31.0-31.1 / 1.5-1.9 ms | | 4 | `4eb6cfd` | 29.0 / 28.6 | 33.8-34.4 ms | 31.8-32.2 / 2.0-2.2 ms | | 5, 6 | `0834177` NO_BACK | - / 30.0, 30.0 | - | - | | 7 | `0834177` NO_BACK + `VICTORY_WC_CENSUS=1` | - / 30.0 | - | - | What showed: - With `VICTORY_WC_NO_BACK=1` the steady figure is 30.0 in all five runs against 28.6 in the two base runs here; frames are about 1-1.5 ms shorter. - Active: the `wc` line reports 800-1,300 declarations a frame left on the card in the boat scene; 5-12 MB a frame of small ones still copied back. - Census (run 7): 545-589 MB of ranges guarded through the boat scene; the title touched 0.000 MB a second of them, read or written, in all 51 lines. Guard pass 0.7 ms. So in this scene the title's processor does not read what is left on the card. - Peak commit 33.7-34.4 GB in the five NO_BACK runs against 32.5-33.5 GB for the two base runs here (private peak 34.5-34.9 GB against 33.3-34.2 GB). - Picture: the 241 s shots match the base in runs 1, 5, 6 and 7. In run 3 the man's shirt on the boat is dark grey from 185 s to the end (same shirt and logo, the boat and his neck lit as in the others); in 19 other boat runs today (base and other PRs, checked at 241 s) it never was. One in five runs of the PR; I have not established whether it comes from the change or is the title's own variation. Five runs of the PR with the switch, one scene, ray tracing off.
gw1337x commented 2026-11-27 12:07:52 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gw1337x on 2026-11-27T12:07:52Z.


#477 and #470 stack, measured together. Memory Integrity was off.

PC: Ryzen 7 9800X3D, RX 7800 XT, 32 GB. Test: 270 s hands-off boat scene, RT off, Belobug launcher settings plus the 5 port switches. I made a local build of #477 (0834177) with #470's two commits cherry-picked on top (no conflicts) and ran it with VICTORY_WC_NO_BACK=1. Compared against 4eb6cfd, 3 runs each, interleaved.

#477 + #470 base 4eb6cfd
steady fps (last minute, layer log) 30.0 / 30.0 / 30.0 28.4 / 28.3 / 28.6
world on screen (first 1,000+ draws a frame), s after start 39.9 / 36.2 / 36.5 42.9 / 44.0 / 44.3
seconds under 15 fps (window title, 45-265 s, seconds with 1,000+ draws) 7 / 6 / 8 13 / 15 / 14
peak commit, GB 33.5 / 33.8 / 33.7 33.8 / 34.2 / 33.9
device loss lines 0 0
  • Both halves were active in every combo run: 8 file-cache opens per run, and NO_BACK lines in the log.
  • Pictures at 241 s look normal in all three.

Each PR keeps its own gain when they're combined: #477's steady fps and #470's faster load.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:comment:7217874958 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/477#issuecomment-7217874958). Originally posted by [gw1337x](https://github.com/gw1337x) on 2026-11-27T12:07:52Z. --- #477 and #470 stack, measured together. Memory Integrity was off. PC: Ryzen 7 9800X3D, RX 7800 XT, 32 GB. Test: 270 s hands-off boat scene, RT off, Belobug launcher settings plus the 5 port switches. I made a local build of #477 (`0834177`) with #470's two commits cherry-picked on top (no conflicts) and ran it with `VICTORY_WC_NO_BACK=1`. Compared against `4eb6cfd`, 3 runs each, interleaved. | | #477 + #470 | base `4eb6cfd` | |---|---|---| | steady fps (last minute, layer log) | 30.0 / 30.0 / 30.0 | 28.4 / 28.3 / 28.6 | | world on screen (first 1,000+ draws a frame), s after start | 39.9 / 36.2 / 36.5 | 42.9 / 44.0 / 44.3 | | seconds under 15 fps (window title, 45-265 s, seconds with 1,000+ draws) | 7 / 6 / 8 | 13 / 15 / 14 | | peak commit, GB | 33.5 / 33.8 / 33.7 | 33.8 / 34.2 / 33.9 | | device loss lines | 0 | 0 | - Both halves were active in every combo run: 8 file-cache opens per run, and NO_BACK lines in the log. - Pictures at 241 s look normal in all three. Each PR keeps its own gain when they're combined: #477's steady fps and #470's faster load.
gw1337x commented 2026-11-27 13:35:11 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gw1337x on 2026-11-27T13:35:11Z.


Follow-up: #477 with VICTORY_WC_NO_BACK=1 while driving, not just sitting in the boat. Memory Integrity was off.

PC: Ryzen 7 9800X3D, RX 7800 XT, 32 GB. RT off, Belobug launcher settings plus the 5 port switches, warm caches. #477 (0834177) on 4eb6cfd vs 4eb6cfd, interleaved (PR, base, PR, base, PR, base). Same boat scene; scripted full throttle from 190 s with no steering, run ends at 220 s.

Routes split after about 205 s even on base (same input, different heading), so the main window is 190-205 s, and the frame-time numbers come from the timelines taken at 190 s and 200 s (30 frames each, 60 per run).

#477 run 1 #477 run 2 #477 run 3 base run 1 base run 2 base run 3
Fps, 190-205 s (window title, median) 30.0 29.0 30.0 27.0 28.0 27.5
Lowest fps, 190-205 s 25 28 26 22 26 22
Frames over 40 ms (of 60) 1 3 1 12 9 9
Frame time p50 33.2 ms 33.6 ms 33.3 ms 35.5 ms 34.6 ms 35.0 ms
Frame time p95 38.3 ms 45.0 ms 38.0 ms 51.8 ms 51.8 ms 52.5 ms
  • 190-205 s: no overlap between the two sides on any row.
  • 205-220 s: the two sides overlap (25.0/28.0/28.0 vs 26.0/26.0/22.0 fps).
  • Routes: PR run 1 turned off course by 220 s. Base run 1 met a traffic yacht at about 201 s and stopped next to it by 210 s. Leaving base run 1 out, base is 28.0/27.5 fps for 190-205 s, still below #477.
  • Other checks: no device loss, and peak commit 33.7-34.0 GB vs 33.5-33.8 GB.

The #477 + #470 stack gave the same result in this test (190-205 s: 29.0-30.0 fps, 0-2 frames over 40 ms of 60), so the gain while driving comes from #477, as it does sitting still.

AI-assisted (Claude Code); numbers from the run logs and timelines.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:comment:7219680928 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/477#issuecomment-7219680928). Originally posted by [gw1337x](https://github.com/gw1337x) on 2026-11-27T13:35:11Z. --- Follow-up: #477 with `VICTORY_WC_NO_BACK=1` while driving, not just sitting in the boat. Memory Integrity was off. PC: Ryzen 7 9800X3D, RX 7800 XT, 32 GB. RT off, Belobug launcher settings plus the 5 port switches, warm caches. #477 (`0834177`) on `4eb6cfd` vs `4eb6cfd`, interleaved (PR, base, PR, base, PR, base). Same boat scene; scripted full throttle from 190 s with no steering, run ends at 220 s. Routes split after about 205 s even on base (same input, different heading), so the main window is 190-205 s, and the frame-time numbers come from the timelines taken at 190 s and 200 s (30 frames each, 60 per run). | | #477 run 1 | #477 run 2 | #477 run 3 | base run 1 | base run 2 | base run 3 | |---|---|---|---|---|---|---| | Fps, 190-205 s (window title, median) | 30.0 | 29.0 | 30.0 | 27.0 | 28.0 | 27.5 | | Lowest fps, 190-205 s | 25 | 28 | 26 | 22 | 26 | 22 | | Frames over 40 ms (of 60) | 1 | 3 | 1 | 12 | 9 | 9 | | Frame time p50 | 33.2 ms | 33.6 ms | 33.3 ms | 35.5 ms | 34.6 ms | 35.0 ms | | Frame time p95 | 38.3 ms | 45.0 ms | 38.0 ms | 51.8 ms | 51.8 ms | 52.5 ms | - **190-205 s:** no overlap between the two sides on any row. - **205-220 s:** the two sides overlap (25.0/28.0/28.0 vs 26.0/26.0/22.0 fps). - **Routes:** PR run 1 turned off course by 220 s. Base run 1 met a traffic yacht at about 201 s and stopped next to it by 210 s. Leaving base run 1 out, base is 28.0/27.5 fps for 190-205 s, still below #477. - **Other checks:** no device loss, and peak commit 33.7-34.0 GB vs 33.5-33.8 GB. The #477 + #470 stack gave the same result in this test (190-205 s: 29.0-30.0 fps, 0-2 frames over 40 ms of 60), so the gain while driving comes from #477, as it does sitting still. AI-assisted (Claude Code); numbers from the run logs and timelines.
luisaugustz commented 2026-11-27 14:59:14 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by luisaugustz on 2026-11-27T14:59:14Z.


Confirming on RX 9070 XT + Ryzen 7 5800X (a-publier 4eb6cfd + this PR, Series X, RT off, same save and spot):

fps ms/frame copy back
off 11.8 84.7 32.5 ms, ~21 MB
VICTORY_WC_NO_BACK=1 13.8 ~73 ~18-20 ms, 2.6 MB

Copy back fell from about 21 MB to 2.6 MB a frame. We have played with it on for several sessions since and have not noticed anything it breaks, though we did not do a careful visual A/B.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:comment:7221480597 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/477#issuecomment-7221480597). Originally posted by [luisaugustz](https://github.com/luisaugustz) on 2026-11-27T14:59:14Z. --- Confirming on RX 9070 XT + Ryzen 7 5800X (a-publier `4eb6cfd` + this PR, Series X, RT off, same save and spot): | | fps | ms/frame | copy back | |---|---|---|---| | off | 11.8 | 84.7 | 32.5 ms, ~21 MB | | `VICTORY_WC_NO_BACK=1` | 13.8 | ~73 | ~18-20 ms, 2.6 MB | Copy back fell from about 21 MB to 2.6 MB a frame. We have played with it on for several sessions since and have not noticed anything it breaks, though we did not do a careful visual A/B.
gut0to commented 2026-11-27 15:10:40 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-27T15:10:40Z.

Review: COMMENTED


AI-assisted static review; I traced the page-arm failure path and the vectored exception handler. I did not run the test suite.

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review:6090158298 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/477#pullrequestreview-6090158298). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-27T15:10:40Z. **Review:** COMMENTED --- AI-assisted static review; I traced the page-arm failure path and the vectored exception handler. I did not run the test suite.
gut0to commented 2026-11-27 15:10:40 +00:00 (Migrated from github.com)

Imported from Belobug/VIctory-Belobug-AMD. Originally posted by gut0to on 2026-11-27T15:10:40Z.

Code review location: crates/victory-gpu/src/census.rs; line 268

@@ -0,0 +1,424 @@
+//! Census of what the title touches of the memory shaders' writes were
+//! left in on the card (`VICTORY_WC_CENSUS=1`, with `VICTORY_WC_NO_BACK=1`).
+//!
+//! [`crate::wc::skip_back`] leaves shaders' writes into write-combined title
+//! memory on the card: title memory there keeps older bytes. That is only
+//! right if the title's processor does not read them. This counts what it
+//! does touch, after fxceless/victory-fork issue #1169's read census: once
+//! a second the 4 KiB pages of those ranges ([`note`]) get `PAGE_GUARD`,
+//! and a guard hit there is counted, once per guard, by who touched the
+//! page, then let go on (the system took the guard off with the fault).
+//!
+//! - Reads and writes of the layer's own paths that name themselves
+//!   ([`tag`]: copy refreshes, texture refreshes, our copies) count as the
+//!   layer's.
+//! - Any other touch is counted by the instruction that made it, read or
+//!   write; the line names the most frequent ones by module (none: the
+//!   title's code; `victory.exe`: our code on a thread no tag names, such as
+//!   a call of the title's into the HLE).
+//! - A read is a byte the title would have needed copied back (an upper
+//!   bound: a whole page counts, and part of a page may lie outside the
+//!   ranges, counted apart). A write is the title's own new bytes (the
+//!   write watch still sends them up).
+//!
+//! Guards are set holding the write guards' lock alone, and never on a
+//! block those guards keep read-only or one the kernel is writing for the
+//! title ([`crate::watch::census_arm`]); the kernel's writes for the title
+//! take them off first ([`disarm`]), since the kernel fails on a guard
+//! instead of faulting. The handler is put first, after the write guards':
+//! a copy of ours that hits a guard goes on, counted as ours.
+//!
+//! shortcut: a protection change of the title's own (or of the in-place
+//! views) between the query and the guard is undone by the guard. Our
+//! copies through the kernel (`VICTORY_SAFE_COPY=0`) would fail on a guard:
+//! the census then stays off. Measurement only: never on by default.
+
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed};
+use std::sync::{OnceLock, RwLock};
+
+const PAGE: usize = 4096;
+/// Pages of the 40-bit title address space.
+const PAGES: usize = 1 << 28;
+
+/// Whether the census runs.
+pub(crate) fn on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        let asked = std::env::var_os("VICTORY_WC_CENSUS").is_some_and(|v| v == "1");
+        if asked && !crate::wc::no_back() {
+            tracing::warn!("VICTORY_WC_CENSUS needs VICTORY_WC_NO_BACK=1: off");
+            return false;
+        }
+        if asked && !crate::safecopy::on() {
+            tracing::warn!("VICTORY_WC_CENSUS needs our own copies (not VICTORY_SAFE_COPY=0): off");
+            return false;
+        }
+        if asked {
+            tracing::warn!(
+                "VICTORY_WC_CENSUS: pages of what shaders' writes were left in on the card are guarded to count what the title touches (slower)"
+            );
+        }
+        asked
+    })
+}
+
+/// Title memory whose shaders' writes are on the card, of all copies.
+fn owned() -> &'static RwLock<crate::wc::Ranges> {
+    static OWNED: OnceLock<RwLock<crate::wc::Ranges>> = OnceLock::new();
+    OWNED.get_or_init(Default::default)
+}
+
+/// `[from, to)` of title memory holds older bytes than the card's.
+pub(crate) fn note(from: usize, to: usize) {
+    if !on() || from >= to {
+        return;
+    }
+    if owned().read().unwrap_or_else(|e| e.into_inner()).covers(from, to) {
+        return;
+    }
+    owned().write().unwrap_or_else(|e| e.into_inner()).add(from, to);
+}
+
+/// A copy that held `[from, to)` is gone: not counted there any more, and
+/// its guards come off.
+pub(crate) fn forget(from: usize, to: usize) {
+    if !on() || from >= to {
+        return;
+    }
+    owned().write().unwrap_or_else(|e| e.into_inner()).remove(from, to);
+    for page in from / PAGE..to.div_ceil(PAGE) {
+        if is_ours(page) {
+            set_guard(page * PAGE, PAGE, false);
+        }
+    }
+}
+
+/// One bit per page the census ever guarded: a guard hit there is the
+/// census's (never cleared, so that a hit just after a guard came off is
+/// still known as ours and let go on).
+fn ours() -> &'static [AtomicU64] {
+    static OURS: OnceLock<Box<[AtomicU64]>> = OnceLock::new();
+    OURS.get_or_init(|| (0..PAGES / 64).map(|_| AtomicU64::new(0)).collect())
+}
+
+fn is_ours(page: usize) -> bool {
+    page < PAGES && ours()[page / 64].load(Relaxed) & (1u64 << (page % 64)) != 0
+}
+
+// Whether this thread's touches of title memory are the layer's ([`tag`]).
+thread_local! {
+    static TAGGED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
+}
+
+/// This thread's touches of title memory are the layer's until the result
+/// is dropped.
+pub(crate) fn tag() -> Tag {
+    Tag(TAGGED.with(|t| t.replace(true)))
+}
+
+pub(crate) struct Tag(bool);
+impl Drop for Tag {
+    fn drop(&mut self) {
+        TAGGED.with(|t| t.set(self.0));
+    }
+}
+
+/// Per-second counts, in pages: guards set; touched by a tagged path of
+/// ours; untagged reads and writes inside the ranges; untagged touches of a
+/// guarded page outside them (its other part); guards the kernel's writes
+/// for the title took off.
+static COUNT: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6];
+const ARMED: usize = 0;
+const LAYER: usize = 1;
+const READ: usize = 2;
+const WRITE: usize = 3;
+const EDGE: usize = 4;
+const KERNEL: usize = 5;
+/// Since the start: guard passes and the time they took (µs).
+static PASSES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
+
+/// The instructions of untagged touches inside the ranges, with their reads
+/// and writes since the start (an open table: a slot is taken once).
+const SLOTS: usize = 256;
+static RIPS: [AtomicUsize; SLOTS] = [const { AtomicUsize::new(0) }; SLOTS];
+static RIP_COUNT: [[AtomicU64; 2]; SLOTS] = [const { [const { AtomicU64::new(0) }; 2] }; SLOTS];
+/// Touches whose instruction found no slot.
+static RIPS_FULL: AtomicU64 = AtomicU64::new(0);
+
+fn count_rip(rip: usize, write: bool) {
+    let mut i = rip.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 56;
+    for _ in 0..SLOTS {
+        let slot = i % SLOTS;
+        let at = RIPS[slot].load(Relaxed);
+        if at == rip || (at == 0 && RIPS[slot].compare_exchange(0, rip, Relaxed, Relaxed).map_or_else(|now| now == rip, |_| true)) {
+            RIP_COUNT[slot][write as usize].fetch_add(1, Relaxed);
+            return;
+        }
+        i += 1;
+    }
+    RIPS_FULL.fetch_add(1, Relaxed);
+}
+
+unsafe extern "system" fn on_guard(p: *mut windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_POINTERS) -> i32 {
+    const GUARD: i32 = 0x8000_0001_u32 as i32;
+    const CONTINUE_EXECUTION: i32 = -1;
+    const CONTINUE_SEARCH: i32 = 0;
+    // SAFETY: the system passes a valid record.
+    let r = unsafe { &*(*p).ExceptionRecord };
+    if r.ExceptionCode != GUARD || r.NumberParameters < 2 {
+        return CONTINUE_SEARCH;
+    }
+    let address = r.ExceptionInformation[1];
+    if !is_ours(address / PAGE) {
+        return CONTINUE_SEARCH;
+    }
+    // The guard went with the fault: the access goes on when retried.
+    if TAGGED.with(std::cell::Cell::get) {
+        COUNT[LAYER].fetch_add(1, Relaxed);
+        return CONTINUE_EXECUTION;
+    }
+    // (Not waited for: a writer holds the lock only to add or take out.)
+    let inside = owned().try_read().map_or(true, |o| o.contains(address));
+    if !inside {
+        COUNT[EDGE].fetch_add(1, Relaxed);
+        return CONTINUE_EXECUTION;
+    }
+    let write = r.ExceptionInformation[0] == 1;
+    COUNT[if write { WRITE } else { READ }].fetch_add(1, Relaxed);
+    count_rip(r.ExceptionAddress as usize, write);
+    CONTINUE_EXECUTION
+}
+
+/// Before the kernel writes `[at, at + len)` for the title (a file read;
+/// called holding the write guards' lock): the census's guards there come
+/// off, and none is set again until it is done ([`crate::watch::census_arm`]
+/// looks at the kernel's writes).
+pub(crate) fn disarm(at: usize, len: usize) {
+    if !on() || len == 0 {
+        return;
+    }
+    for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
+        if is_ours(page) && set_guard(page * PAGE, PAGE, false) {
+            COUNT[KERNEL].fetch_add(1, Relaxed);
+        }
+    }
+}
+
+/// Once a second: guards every page of the ranges that has none now.
+pub(crate) fn arm() {
+    if !on() {
+        return;
+    }
+    static HANDLER: std::sync::Once = std::sync::Once::new();
+    // SAFETY: a handler that lives forever, put first (after the write
+    // guards' own, put at startup).
+    HANDLER.call_once(|| unsafe {
+        windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(on_guard));
+    });
+    let began = std::time::Instant::now();
+    let ranges: Vec<(usize, usize)> = owned().read().unwrap_or_else(|e| e.into_inner()).iter().collect();
+    let mut armed = 0u64;
+    crate::watch::census_arm(|busy| {
+        for (from, to) in ranges {
+            if crate::wc::kind(from) != crate::wc::Kind::WriteCombined {
+                continue;
+            }
+            let (first, end) = (from / PAGE, to.div_ceil(PAGE).min(PAGES));
+            let mut page = first;
+            while page < end {
+                // A run of pages free to guard, cut where the guards are busy.
+                while page < end && busy(page * PAGE) {
+                    page += 1;
+                }
+                let start = page;
+                while page < end && !busy(page * PAGE) {
+                    page += 1;
+                }
+                if start < page {
+                    armed += guard_run(start, page);
+                }
+            }
+        }
+    });
+    COUNT[ARMED].fetch_add(armed, Relaxed);
+    PASSES[0].fetch_add(1, Relaxed);
+    PASSES[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed);
+}
+
+/// Guards pages `[first, end)` region by region of one protection, where
+/// committed, readable and not guarded already. Returns the pages guarded.
+fn guard_run(first: usize, end: usize) -> u64 {
+    use windows_sys::Win32::System::Memory::{
+        MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualProtect, VirtualQuery,
+    };
+    let mut armed = 0;
+    let mut at = first * PAGE;
+    let end = end * PAGE;
+    while at < end {
+        let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+        // SAFETY: a query of any address; the out struct is ours.
+        if unsafe { VirtualQuery(at as _, &mut m, std::mem::size_of_val(&m)) } == 0 {
+            return armed;
+        }
+        let region_end = (m.BaseAddress as usize + m.RegionSize).min(end).max(at + PAGE);
+        if m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.Protect != 0 {
+            let pages = (region_end - at) / PAGE;
+            // The bits before the guard: a hit at once is then the census's.
+            for page in at / PAGE..region_end / PAGE {
+                ours()[page / 64].fetch_or(1u64 << (page % 64), Relaxed);

AI-assisted review: these ours bits are set before VirtualProtect so an immediate census fault is recognized, but they are not rolled back when VirtualProtect fails. If the address is later reused and another owner installs PAGE_GUARD, on_guard will treat that unrelated exception as ours and return CONTINUE_EXECUTION, consuming the other guard. Could the arm state be rolled back safely on failure while preserving the immediate-fault case, with a test for a failed arm followed by a foreign guard?

<!-- greyfinch-sync:Belobug/VIctory-Belobug-AMD:review-comment:4720996463 --> Imported from [Belobug/VIctory-Belobug-AMD](https://github.com/Belobug/VIctory-Belobug-AMD/pull/477#discussion_r4720996463). Originally posted by [gut0to](https://github.com/gut0to) on 2026-11-27T15:10:40Z. **Code review location:** `crates/victory-gpu/src/census.rs`; line 268 ~~~~diff @@ -0,0 +1,424 @@ +//! Census of what the title touches of the memory shaders' writes were +//! left in on the card (`VICTORY_WC_CENSUS=1`, with `VICTORY_WC_NO_BACK=1`). +//! +//! [`crate::wc::skip_back`] leaves shaders' writes into write-combined title +//! memory on the card: title memory there keeps older bytes. That is only +//! right if the title's processor does not read them. This counts what it +//! does touch, after fxceless/victory-fork issue #1169's read census: once +//! a second the 4 KiB pages of those ranges ([`note`]) get `PAGE_GUARD`, +//! and a guard hit there is counted, once per guard, by who touched the +//! page, then let go on (the system took the guard off with the fault). +//! +//! - Reads and writes of the layer's own paths that name themselves +//! ([`tag`]: copy refreshes, texture refreshes, our copies) count as the +//! layer's. +//! - Any other touch is counted by the instruction that made it, read or +//! write; the line names the most frequent ones by module (none: the +//! title's code; `victory.exe`: our code on a thread no tag names, such as +//! a call of the title's into the HLE). +//! - A read is a byte the title would have needed copied back (an upper +//! bound: a whole page counts, and part of a page may lie outside the +//! ranges, counted apart). A write is the title's own new bytes (the +//! write watch still sends them up). +//! +//! Guards are set holding the write guards' lock alone, and never on a +//! block those guards keep read-only or one the kernel is writing for the +//! title ([`crate::watch::census_arm`]); the kernel's writes for the title +//! take them off first ([`disarm`]), since the kernel fails on a guard +//! instead of faulting. The handler is put first, after the write guards': +//! a copy of ours that hits a guard goes on, counted as ours. +//! +//! shortcut: a protection change of the title's own (or of the in-place +//! views) between the query and the guard is undone by the guard. Our +//! copies through the kernel (`VICTORY_SAFE_COPY=0`) would fail on a guard: +//! the census then stays off. Measurement only: never on by default. + +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed}; +use std::sync::{OnceLock, RwLock}; + +const PAGE: usize = 4096; +/// Pages of the 40-bit title address space. +const PAGES: usize = 1 << 28; + +/// Whether the census runs. +pub(crate) fn on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let asked = std::env::var_os("VICTORY_WC_CENSUS").is_some_and(|v| v == "1"); + if asked && !crate::wc::no_back() { + tracing::warn!("VICTORY_WC_CENSUS needs VICTORY_WC_NO_BACK=1: off"); + return false; + } + if asked && !crate::safecopy::on() { + tracing::warn!("VICTORY_WC_CENSUS needs our own copies (not VICTORY_SAFE_COPY=0): off"); + return false; + } + if asked { + tracing::warn!( + "VICTORY_WC_CENSUS: pages of what shaders' writes were left in on the card are guarded to count what the title touches (slower)" + ); + } + asked + }) +} + +/// Title memory whose shaders' writes are on the card, of all copies. +fn owned() -> &'static RwLock<crate::wc::Ranges> { + static OWNED: OnceLock<RwLock<crate::wc::Ranges>> = OnceLock::new(); + OWNED.get_or_init(Default::default) +} + +/// `[from, to)` of title memory holds older bytes than the card's. +pub(crate) fn note(from: usize, to: usize) { + if !on() || from >= to { + return; + } + if owned().read().unwrap_or_else(|e| e.into_inner()).covers(from, to) { + return; + } + owned().write().unwrap_or_else(|e| e.into_inner()).add(from, to); +} + +/// A copy that held `[from, to)` is gone: not counted there any more, and +/// its guards come off. +pub(crate) fn forget(from: usize, to: usize) { + if !on() || from >= to { + return; + } + owned().write().unwrap_or_else(|e| e.into_inner()).remove(from, to); + for page in from / PAGE..to.div_ceil(PAGE) { + if is_ours(page) { + set_guard(page * PAGE, PAGE, false); + } + } +} + +/// One bit per page the census ever guarded: a guard hit there is the +/// census's (never cleared, so that a hit just after a guard came off is +/// still known as ours and let go on). +fn ours() -> &'static [AtomicU64] { + static OURS: OnceLock<Box<[AtomicU64]>> = OnceLock::new(); + OURS.get_or_init(|| (0..PAGES / 64).map(|_| AtomicU64::new(0)).collect()) +} + +fn is_ours(page: usize) -> bool { + page < PAGES && ours()[page / 64].load(Relaxed) & (1u64 << (page % 64)) != 0 +} + +// Whether this thread's touches of title memory are the layer's ([`tag`]). +thread_local! { + static TAGGED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// This thread's touches of title memory are the layer's until the result +/// is dropped. +pub(crate) fn tag() -> Tag { + Tag(TAGGED.with(|t| t.replace(true))) +} + +pub(crate) struct Tag(bool); +impl Drop for Tag { + fn drop(&mut self) { + TAGGED.with(|t| t.set(self.0)); + } +} + +/// Per-second counts, in pages: guards set; touched by a tagged path of +/// ours; untagged reads and writes inside the ranges; untagged touches of a +/// guarded page outside them (its other part); guards the kernel's writes +/// for the title took off. +static COUNT: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6]; +const ARMED: usize = 0; +const LAYER: usize = 1; +const READ: usize = 2; +const WRITE: usize = 3; +const EDGE: usize = 4; +const KERNEL: usize = 5; +/// Since the start: guard passes and the time they took (µs). +static PASSES: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; + +/// The instructions of untagged touches inside the ranges, with their reads +/// and writes since the start (an open table: a slot is taken once). +const SLOTS: usize = 256; +static RIPS: [AtomicUsize; SLOTS] = [const { AtomicUsize::new(0) }; SLOTS]; +static RIP_COUNT: [[AtomicU64; 2]; SLOTS] = [const { [const { AtomicU64::new(0) }; 2] }; SLOTS]; +/// Touches whose instruction found no slot. +static RIPS_FULL: AtomicU64 = AtomicU64::new(0); + +fn count_rip(rip: usize, write: bool) { + let mut i = rip.wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 56; + for _ in 0..SLOTS { + let slot = i % SLOTS; + let at = RIPS[slot].load(Relaxed); + if at == rip || (at == 0 && RIPS[slot].compare_exchange(0, rip, Relaxed, Relaxed).map_or_else(|now| now == rip, |_| true)) { + RIP_COUNT[slot][write as usize].fetch_add(1, Relaxed); + return; + } + i += 1; + } + RIPS_FULL.fetch_add(1, Relaxed); +} + +unsafe extern "system" fn on_guard(p: *mut windows_sys::Win32::System::Diagnostics::Debug::EXCEPTION_POINTERS) -> i32 { + const GUARD: i32 = 0x8000_0001_u32 as i32; + const CONTINUE_EXECUTION: i32 = -1; + const CONTINUE_SEARCH: i32 = 0; + // SAFETY: the system passes a valid record. + let r = unsafe { &*(*p).ExceptionRecord }; + if r.ExceptionCode != GUARD || r.NumberParameters < 2 { + return CONTINUE_SEARCH; + } + let address = r.ExceptionInformation[1]; + if !is_ours(address / PAGE) { + return CONTINUE_SEARCH; + } + // The guard went with the fault: the access goes on when retried. + if TAGGED.with(std::cell::Cell::get) { + COUNT[LAYER].fetch_add(1, Relaxed); + return CONTINUE_EXECUTION; + } + // (Not waited for: a writer holds the lock only to add or take out.) + let inside = owned().try_read().map_or(true, |o| o.contains(address)); + if !inside { + COUNT[EDGE].fetch_add(1, Relaxed); + return CONTINUE_EXECUTION; + } + let write = r.ExceptionInformation[0] == 1; + COUNT[if write { WRITE } else { READ }].fetch_add(1, Relaxed); + count_rip(r.ExceptionAddress as usize, write); + CONTINUE_EXECUTION +} + +/// Before the kernel writes `[at, at + len)` for the title (a file read; +/// called holding the write guards' lock): the census's guards there come +/// off, and none is set again until it is done ([`crate::watch::census_arm`] +/// looks at the kernel's writes). +pub(crate) fn disarm(at: usize, len: usize) { + if !on() || len == 0 { + return; + } + for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) { + if is_ours(page) && set_guard(page * PAGE, PAGE, false) { + COUNT[KERNEL].fetch_add(1, Relaxed); + } + } +} + +/// Once a second: guards every page of the ranges that has none now. +pub(crate) fn arm() { + if !on() { + return; + } + static HANDLER: std::sync::Once = std::sync::Once::new(); + // SAFETY: a handler that lives forever, put first (after the write + // guards' own, put at startup). + HANDLER.call_once(|| unsafe { + windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(on_guard)); + }); + let began = std::time::Instant::now(); + let ranges: Vec<(usize, usize)> = owned().read().unwrap_or_else(|e| e.into_inner()).iter().collect(); + let mut armed = 0u64; + crate::watch::census_arm(|busy| { + for (from, to) in ranges { + if crate::wc::kind(from) != crate::wc::Kind::WriteCombined { + continue; + } + let (first, end) = (from / PAGE, to.div_ceil(PAGE).min(PAGES)); + let mut page = first; + while page < end { + // A run of pages free to guard, cut where the guards are busy. + while page < end && busy(page * PAGE) { + page += 1; + } + let start = page; + while page < end && !busy(page * PAGE) { + page += 1; + } + if start < page { + armed += guard_run(start, page); + } + } + } + }); + COUNT[ARMED].fetch_add(armed, Relaxed); + PASSES[0].fetch_add(1, Relaxed); + PASSES[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed); +} + +/// Guards pages `[first, end)` region by region of one protection, where +/// committed, readable and not guarded already. Returns the pages guarded. +fn guard_run(first: usize, end: usize) -> u64 { + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualProtect, VirtualQuery, + }; + let mut armed = 0; + let mut at = first * PAGE; + let end = end * PAGE; + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a query of any address; the out struct is ours. + if unsafe { VirtualQuery(at as _, &mut m, std::mem::size_of_val(&m)) } == 0 { + return armed; + } + let region_end = (m.BaseAddress as usize + m.RegionSize).min(end).max(at + PAGE); + if m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.Protect != 0 { + let pages = (region_end - at) / PAGE; + // The bits before the guard: a hit at once is then the census's. + for page in at / PAGE..region_end / PAGE { + ours()[page / 64].fetch_or(1u64 << (page % 64), Relaxed); ~~~~ --- AI-assisted review: these `ours` bits are set before `VirtualProtect` so an immediate census fault is recognized, but they are not rolled back when `VirtualProtect` fails. If the address is later reused and another owner installs `PAGE_GUARD`, `on_guard` will treat that unrelated exception as ours and return `CONTINUE_EXECUTION`, consuming the other guard. Could the arm state be rolled back safely on failure while preserving the immediate-fault case, with a test for a failed arm followed by a foreign guard?
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/477:upstream-pr/477'
git switch 'upstream-pr/477'

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 'a-publier'
git merge --no-ff 'upstream-pr/477'
git switch 'upstream-pr/477'
git rebase 'a-publier'
git switch 'a-publier'
git merge --ff-only 'upstream-pr/477'
git switch 'upstream-pr/477'
git rebase 'a-publier'
git switch 'a-publier'
git merge --no-ff 'upstream-pr/477'
git switch 'a-publier'
git merge --squash 'upstream-pr/477'
git switch 'a-publier'
git merge --ff-only 'upstream-pr/477'
git switch 'a-publier'
git merge 'upstream-pr/477'
git push origin 'a-publier'
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!477
No description provided.