D3D12.X: add opt-in watch_cold core module for read-only cold blocks #3639

Open
iggyvilla wants to merge 2 commits from upstream-pr/3639 into amd-dev
iggyvilla commented 2026-12-02 02:47:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by iggyvilla on 2026-12-02T02:47:00Z.


Stacked on #3597; only the top commit belongs here.

TL;DR — Before vs After

Aspect Before (#3639 v1) After (#3639 Part 1 core)
Scope & size 2,890 lines across 8 files (core + wiring + negative-cache & diagnostic counters) 704 lines across 2 files (watch_cold.rs + mod.rs), core module only; call-site wiring split into a small stacked follow-up PR
Default behavior Opt-in (XCL_WATCH_COLD=1, off by default) Opt-in (XCL_WATCH_COLD=1, off by default; #[allow(dead_code)] until wiring PR lands)
Coherent UMA VirtualProtect error 87 skipped upfront Same O(1) !uma.shadowed() && uma.in_committed_window upfront skip (removed obsolete prot_cache / CHANGES ring)
Concurrency FREEZE_END checked before COLD lock in changed_now FREEZE_END checked under COLD lock in changed_now, closing pin-vs-freeze race; thaw_range cleanup on failed freeze
60 s smoke (RX 6650 XT) 1654 frames (60 61 60, 15902 MB) on amd-dev 1641 frames (60 60 60, 16237 MB, 0 removals, 0 crashes)

What is in it
Adds the opt-in hle::d3d12x::watch_cold core module (XCL_WATCH_COLD=1, default off, requires XCL_GUEST_WRITE_GUARD=1 from #3597) so cold watched title memory can be protected PAGE_READONLY and excluded from per-submit GetWriteWatch scans.

In response to review feedback on PR size and complexity:

  • Stripped the obsolete prot_cache, CHANGES ring buffer, and diagnostic STATS counters made redundant by the O(1) upfront imported-coherent-UMA skip (!uma.shadowed() && uma.in_committed_window), shrinking watch_cold.rs from 2,739 lines to 702 lines (619 runtime + 83 tests).
  • Split all title_textures / kernelx / lazy / sparse call-site wiring (and the tracks_hot_blocks() fix for mark_hot / all_hot / sibling warming) into a separate small stacked follow-up PR.
  • Preserved all safety invariants: lock-free 1024-entry OPENED VEH ring, unlocked VirtualProtect serialized with guest_write::while_unpinned and meets_guarded_view, post-protect GetWriteWatch scan (take_after), guard / guard_free / changed pinning + FREEZE_END / HANDLING drain, multi-span 4 MiB fault windows, range-local gap coalescing (XCL_WATCH_COLD_GAP_MB), and per-block hot/cold streak holding.

Tested

  • Hardware: AMD Radeon RX 6650 XT (Windows 11, release build).
  • Targeted unit tests (cargo test -p xcl --lib -- hle::d3d12x::watch_cold::tests --test-threads=1): 4 passed, 0 failed (freeze_fault_window_and_guard_round_trip covering freeze / 4 MiB multi-span fault / thaw / pin, coalesce_calls_merges_within_gap_and_stays_inside_range, hot_streak_holds_block_after_consecutive_frame_faults, look_with_freezes_clean_pieces_and_skips_hot_blocks).
  • Whole-workspace GPU suite (cargo test --workspace --no-fail-fast -- --test-threads=4): 2,966 passed, 16 pre-existing failed, 49 ignored (same pre-existing failures as clean origin/amd-dev 41aa60ce: 3 RDNA2 f32/NaN tests, 6 parallel sparse/title_textures contention tests, 5 e2e debug-layer/title tests, 2 two_pass_driver_cache tests).
  • Release build (cargo build --release -p xcl): succeeded cleanly.

Regression run
Baseline (origin/main d8bd9a38):

xcl-smoke v1
commit: d8bd9a38204667f3ca7dd9eeffcc2f1c937b07b0
gpu: AMD Radeon RX 6650 XT
title: 1778c2d9
seconds: 60
exit: 0x0
frames shown: 1618 (PresentX 1618)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 15479 MB

Baseline (origin/amd-dev 41aa60ce):

xcl-smoke v1
commit: 41aa60ce842060a597b7e8724896f7bf6a031af5
gpu: AMD Radeon RX 6650 XT
title: 1778c2d9
seconds: 60
exit: 0x0
frames shown: 1654 (PresentX 1654)
presents per 2 s (last 3): 60 61 60
device removals: 0
crashes: 0
peak commit: 15902 MB

PR head (a2a329de, default flags):

xcl-smoke v1
commit: a2a329de2b42845e921f5bdf3b595445910d5e93
gpu: AMD Radeon RX 6650 XT
title: 1778c2d9
seconds: 60
exit: 0x0
frames shown: 1641 (PresentX 1641)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 16237 MB

Not tested

  • Live title runtime with XCL_WATCH_COLD=1 active (call-site wiring into title_textures / kernelx / sparse is split into the stacked follow-up PR).
  • NVIDIA and Intel GPUs, and Wine.

AI use

  • Antigravity (Gemini) refactored watch_cold.rs to remove obsolete paths and split out call-site wiring, tightened changed_now synchronization, ran unit/workspace tests and 60 s smoke on local AMD hardware, and wrote this description.
<!-- greyfinch-sync:ivall/xcl:issue:5598797977 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639). Originally posted by [iggyvilla](https://github.com/iggyvilla) on 2026-12-02T02:47:00Z. --- Stacked on #3597; only the top commit belongs here. ### TL;DR — Before vs After | Aspect | Before (`#3639` v1) | After (`#3639` Part 1 core) | | --- | --- | --- | | Scope & size | 2,890 lines across 8 files (core + wiring + negative-cache & diagnostic counters) | **704 lines across 2 files** (`watch_cold.rs` + `mod.rs`), core module only; call-site wiring split into a small stacked follow-up PR | | Default behavior | Opt-in (`XCL_WATCH_COLD=1`, off by default) | Opt-in (`XCL_WATCH_COLD=1`, off by default; `#[allow(dead_code)]` until wiring PR lands) | | Coherent UMA | `VirtualProtect` error 87 skipped upfront | Same O(1) `!uma.shadowed() && uma.in_committed_window` upfront skip (removed obsolete `prot_cache` / `CHANGES` ring) | | Concurrency | `FREEZE_END` checked before `COLD` lock in `changed_now` | `FREEZE_END` checked under `COLD` lock in `changed_now`, closing pin-vs-freeze race; `thaw_range` cleanup on failed freeze | | 60 s smoke (`RX 6650 XT`) | `1654` frames (`60 61 60`, `15902 MB`) on `amd-dev` | `1641` frames (`60 60 60`, `16237 MB`, 0 removals, 0 crashes) | **What is in it** Adds the opt-in `hle::d3d12x::watch_cold` core module (`XCL_WATCH_COLD=1`, default off, requires `XCL_GUEST_WRITE_GUARD=1` from #3597) so cold watched title memory can be protected `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans. In response to review feedback on PR size and complexity: - Stripped the obsolete `prot_cache`, `CHANGES` ring buffer, and diagnostic `STATS` counters made redundant by the O(1) upfront imported-coherent-UMA skip (`!uma.shadowed() && uma.in_committed_window`), shrinking `watch_cold.rs` from 2,739 lines to 702 lines (619 runtime + 83 tests). - Split all `title_textures` / `kernelx` / `lazy` / `sparse` call-site wiring (and the `tracks_hot_blocks()` fix for `mark_hot` / `all_hot` / sibling warming) into a separate small stacked follow-up PR. - Preserved all safety invariants: lock-free 1024-entry `OPENED` VEH ring, unlocked `VirtualProtect` serialized with `guest_write::while_unpinned` and `meets_guarded_view`, post-protect `GetWriteWatch` scan (`take_after`), `guard` / `guard_free` / `changed` pinning + `FREEZE_END` / `HANDLING` drain, multi-span 4 MiB fault windows, range-local gap coalescing (`XCL_WATCH_COLD_GAP_MB`), and per-block hot/cold streak holding. **Tested** - Hardware: AMD Radeon RX 6650 XT (Windows 11, release build). - Targeted unit tests (`cargo test -p xcl --lib -- hle::d3d12x::watch_cold::tests --test-threads=1`): **4 passed, 0 failed** (`freeze_fault_window_and_guard_round_trip` covering freeze / 4 MiB multi-span fault / thaw / pin, `coalesce_calls_merges_within_gap_and_stays_inside_range`, `hot_streak_holds_block_after_consecutive_frame_faults`, `look_with_freezes_clean_pieces_and_skips_hot_blocks`). - Whole-workspace GPU suite (`cargo test --workspace --no-fail-fast -- --test-threads=4`): **2,966 passed, 16 pre-existing failed, 49 ignored** (same pre-existing failures as clean `origin/amd-dev` `41aa60ce`: 3 RDNA2 f32/NaN tests, 6 parallel `sparse`/`title_textures` contention tests, 5 `e2e` debug-layer/title tests, 2 `two_pass_driver_cache` tests). - Release build (`cargo build --release -p xcl`): succeeded cleanly. **Regression run** Baseline (`origin/main` `d8bd9a38`): ``` xcl-smoke v1 commit: d8bd9a38204667f3ca7dd9eeffcc2f1c937b07b0 gpu: AMD Radeon RX 6650 XT title: 1778c2d9 seconds: 60 exit: 0x0 frames shown: 1618 (PresentX 1618) presents per 2 s (last 3): 61 60 60 device removals: 0 crashes: 0 peak commit: 15479 MB ``` Baseline (`origin/amd-dev` `41aa60ce`): ``` xcl-smoke v1 commit: 41aa60ce842060a597b7e8724896f7bf6a031af5 gpu: AMD Radeon RX 6650 XT title: 1778c2d9 seconds: 60 exit: 0x0 frames shown: 1654 (PresentX 1654) presents per 2 s (last 3): 60 61 60 device removals: 0 crashes: 0 peak commit: 15902 MB ``` PR head (`a2a329de`, default flags): ``` xcl-smoke v1 commit: a2a329de2b42845e921f5bdf3b595445910d5e93 gpu: AMD Radeon RX 6650 XT title: 1778c2d9 seconds: 60 exit: 0x0 frames shown: 1641 (PresentX 1641) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 16237 MB ``` **Not tested** - Live title runtime with `XCL_WATCH_COLD=1` active (call-site wiring into `title_textures` / `kernelx` / `sparse` is split into the stacked follow-up PR). - NVIDIA and Intel GPUs, and Wine. **AI use** - Antigravity (Gemini) refactored `watch_cold.rs` to remove obsolete paths and split out call-site wiring, tightened `changed_now` synchronization, ran unit/workspace tests and 60 s smoke on local AMD hardware, and wrote this description.
Foniass commented 2026-12-02 02:57:16 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T02:57:16Z.


Review (head 3a164a8c, diff read, not a merge-check):

  • Too large to review as one PR. The PR's own commit 3a164a8c changes 2,890 lines (watch_cold.rs alone 2,739), none generated or test data; without the unit tests about 1,700 lines are runtime code, and the description does not say why it cannot be split. Please split it along CONTRIBUTING.md, each part under ~400 lines and stacked on #3597 (with a Stacked on #3597 line at the top): (1) preparation with no behaviour change: the guest_write additions (FREEZE_LOCK, while_unpinned, meets_guarded_view, the wait in open_with) with their test, and the refresh_hot / hot_set split in title_textures.rs; (2) the watch_cold core (claim / freeze / fault / thaw, look_with) with its tests, not yet called; (3) turning it on: the guard / guard_free / changed hooks in kernelx.rs, kernelx/lazy.rs and sparse.rs and the look_with dispatch in refresh_parts; (4) the window and gap tunables; (5) the STATS counters, line() and the submit_cost.rs hook.
  • XCL_WATCH_COLD=1 turns off mark_hot and all_hot. hot_looks() (title_textures.rs ~2081) now returns false when watch_cold::on(), so mark_hot (~2520) returns early and blocks a texture creation (~891) or a sparse commit (sparse.rs ~3773, ~6400) marks hot are no longer taken by the next look, while all_hot (~3518) returns true, so upload_all (~3570) skips the written_pages pass and a texture spanning taken and untaken blocks goes up partly old and partly new. The PR's own sibling-block warming (watch_cold.rs ~1494) is a no-op for the same reason; the 4 MiB test only checks the same look.

Not reviewed line by line because of the size. Fine: opt-in and checked once; with XCL_WATCH_COLD unset every hook returns before taking a lock; the freeze is serialized against guest writes through while_unpinned with a write-watch take after the protection.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7333371417 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#issuecomment-7333371417). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T02:57:16Z. --- Review (head 3a164a8c, diff read, not a merge-check): - **Too large to review as one PR.** The PR's own commit `3a164a8c` changes 2,890 lines (`watch_cold.rs` alone 2,739), none generated or test data; without the unit tests about 1,700 lines are runtime code, and the description does not say why it cannot be split. Please split it along CONTRIBUTING.md, each part under ~400 lines and stacked on #3597 (with a `Stacked on #3597` line at the top): (1) preparation with no behaviour change: the `guest_write` additions (`FREEZE_LOCK`, `while_unpinned`, `meets_guarded_view`, the wait in `open_with`) with their test, and the `refresh_hot` / `hot_set` split in `title_textures.rs`; (2) the `watch_cold` core (claim / freeze / fault / thaw, `look_with`) with its tests, not yet called; (3) turning it on: the `guard` / `guard_free` / `changed` hooks in `kernelx.rs`, `kernelx/lazy.rs` and `sparse.rs` and the `look_with` dispatch in `refresh_parts`; (4) the window and gap tunables; (5) the `STATS` counters, `line()` and the `submit_cost.rs` hook. - **`XCL_WATCH_COLD=1` turns off `mark_hot` and `all_hot`.** `hot_looks()` (`title_textures.rs` ~2081) now returns false when `watch_cold::on()`, so `mark_hot` (~2520) returns early and blocks a texture creation (~891) or a sparse commit (`sparse.rs` ~3773, ~6400) marks hot are no longer taken by the next look, while `all_hot` (~3518) returns true, so `upload_all` (~3570) skips the `written_pages` pass and a texture spanning taken and untaken blocks goes up partly old and partly new. The PR's own sibling-block warming (`watch_cold.rs` ~1494) is a no-op for the same reason; the 4 MiB test only checks the same look. Not reviewed line by line because of the size. Fine: opt-in and checked once; with `XCL_WATCH_COLD` unset every hook returns before taking a lock; the freeze is serialized against guest writes through `while_unpinned` with a write-watch take after the protection. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
iggyvilla commented 2026-12-02 07:09:44 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by iggyvilla on 2026-12-02T07:09:44Z.


Thanks for the thorough review! Updated #3639 to address PR size and structure:

  • Stripped the obsolete prot_cache, CHANGES ring, and diagnostic STATS counters (made redundant by the upfront O(1) !uma.shadowed() && uma.in_committed_window skip), shrinking watch_cold.rs from 2,739 lines to 702 lines (704 lines total across 2 files, down from 2,890 lines across 8 files).
  • Closed a pin-vs-freeze race in changed_now (now checks FREEZE_END under COLD lock before thawing) and switched failed-freeze cleanup to thaw_range.
  • Moved FREEZE_LOCK / while_unpinned / meets_guarded_view into #3597 and split the title_textures / kernelx / lazy / sparse call-site wiring — including the tracks_hot_blocks() fix for mark_hot / all_hot / sibling-block warming you flagged — into a small stacked follow-up PR (opening next).
<!-- greyfinch-sync:ivall/xcl:comment:7337849282 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#issuecomment-7337849282). Originally posted by [iggyvilla](https://github.com/iggyvilla) on 2026-12-02T07:09:44Z. --- Thanks for the thorough review! Updated #3639 to address PR size and structure: - Stripped the obsolete `prot_cache`, `CHANGES` ring, and diagnostic `STATS` counters (made redundant by the upfront O(1) `!uma.shadowed() && uma.in_committed_window` skip), shrinking `watch_cold.rs` from 2,739 lines to **702 lines** (704 lines total across 2 files, down from 2,890 lines across 8 files). - Closed a pin-vs-freeze race in `changed_now` (now checks `FREEZE_END` under `COLD` lock before thawing) and switched failed-freeze cleanup to `thaw_range`. - Moved `FREEZE_LOCK` / `while_unpinned` / `meets_guarded_view` into #3597 and split the `title_textures` / `kernelx` / `lazy` / `sparse` call-site wiring — including the `tracks_hot_blocks()` fix for `mark_hot` / `all_hot` / sibling-block warming you flagged — into a small stacked follow-up PR (opening next).
Foniass commented 2026-12-02 07:17:46 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T07:17:46Z.


Follow-up review (head a2a329de, since 3a164a8c, diff read, not a merge-check):

  • Too large to review as one PR: partly fixed. The PR's own commit a2a329de is 704 lines in 2 files (watch_cold.rs, 619 runtime) with a Stacked on #3597 line, still above ~400, and the window, gap and hot-hold tunables (part 4 of the suggested split) are in it.
  • XCL_WATCH_COLD=1 turns off mark_hot and all_hot: not in this part (title_textures.rs is not touched); the description puts the fix in the wiring PR that follows.

New:

  • A fault window can drop a span frozen after it, leaving read-only pages with no handler. fault() records (lo, hi) in OPENED (~331) and apply_faults() later calls carve on it (~250), which removes every COLD span in that range without thawing it (~185-199); freeze checks overlap only against COLD (~487), not windows still pending in OPENED. With the default 2 MiB window multi makes (lo, hi) the whole block (~288-289), so a fault taken during a look, after apply_faults (~566) and before freeze (~615) freezes a sibling piece of the same block, gets that sibling dropped at the next apply_faults; the same happens to later parts of a multi-part freeze when a fault lands between two VirtualProtect calls (~497-503). Those pages stay PAGE_READONLY with no COLD entry, so the next write makes fault() return false (~276-282): an unhandled access violation, and freeze never picks them up again (~473).
  • Pieces that always fail use up the per-look freeze budget. look_with picks the first FREEZE_PER_LOOK pieces with clean >= FREEZE_AFTER before trying them (~608) and resets clean only on success (~616), so a piece freeze always refuses (imported coherent UMA ~457, a guarded view, a part not read-write ~473) is picked again every look; 64 of them early in ranges mean nothing after them is ever frozen.
  • Re-registering the ranges leaves a gap. When ranges changes, look_with unregisters every old range and then registers the new ones one by one (~571-578); an open_with / writable check in between finds a frozen page outside any registered range, does not pin or touch it, and a ReadFile into it fails with ERROR_NOACCESS while kernel_write skips its retry.
  • freeze is the first caller of while_unpinned. That makes #3597's open_with lost wakeup (guest_write.rs ~330-336, see the follow-up there) reachable once this is wired.
  • The tests do not exercise the fault path. No test writes to a frozen page (fault() is called directly, ~647, so handler ~344-352 never runs); guard / guard_free / changed return early because on() is false; the over-8-parts window, the full ring and every concurrent case are untested.

Fine: nothing calls the module yet, so the default path is unchanged; changed_now checks FREEZE_END under COLD; a failed protection is rolled back with thaw_range; the handler's common path does not allocate and its lock order does not cycle with freeze, look_with or open_with; take_after runs after the protection.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7338009919 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#issuecomment-7338009919). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T07:17:46Z. --- Follow-up review (head a2a329de, since 3a164a8c, diff read, not a merge-check): - **Too large to review as one PR:** partly fixed. The PR's own commit `a2a329de` is 704 lines in 2 files (`watch_cold.rs`, 619 runtime) with a `Stacked on #3597` line, still above ~400, and the window, gap and hot-hold tunables (part 4 of the suggested split) are in it. - **`XCL_WATCH_COLD=1` turns off `mark_hot` and `all_hot`:** not in this part (`title_textures.rs` is not touched); the description puts the fix in the wiring PR that follows. New: - **A fault window can drop a span frozen after it, leaving read-only pages with no handler.** `fault()` records `(lo, hi)` in `OPENED` (~331) and `apply_faults()` later calls `carve` on it (~250), which removes every `COLD` span in that range without thawing it (~185-199); `freeze` checks overlap only against `COLD` (~487), not windows still pending in `OPENED`. With the default 2 MiB window `multi` makes `(lo, hi)` the whole block (~288-289), so a fault taken during a look, after `apply_faults` (~566) and before `freeze` (~615) freezes a sibling piece of the same block, gets that sibling dropped at the next `apply_faults`; the same happens to later parts of a multi-part freeze when a fault lands between two `VirtualProtect` calls (~497-503). Those pages stay `PAGE_READONLY` with no `COLD` entry, so the next write makes `fault()` return false (~276-282): an unhandled access violation, and `freeze` never picks them up again (~473). - **Pieces that always fail use up the per-look freeze budget.** `look_with` picks the first `FREEZE_PER_LOOK` pieces with `clean >= FREEZE_AFTER` before trying them (~608) and resets `clean` only on success (~616), so a piece `freeze` always refuses (imported coherent UMA ~457, a guarded view, a part not read-write ~473) is picked again every look; 64 of them early in `ranges` mean nothing after them is ever frozen. - **Re-registering the ranges leaves a gap.** When `ranges` changes, `look_with` unregisters every old range and then registers the new ones one by one (~571-578); an `open_with` / `writable` check in between finds a frozen page outside any registered range, does not pin or touch it, and a `ReadFile` into it fails with `ERROR_NOACCESS` while `kernel_write` skips its retry. - **`freeze` is the first caller of `while_unpinned`.** That makes #3597's `open_with` lost wakeup (`guest_write.rs` ~330-336, see the follow-up there) reachable once this is wired. - **The tests do not exercise the fault path.** No test writes to a frozen page (`fault()` is called directly, ~647, so `handler` ~344-352 never runs); `guard` / `guard_free` / `changed` return early because `on()` is false; the over-8-parts window, the full ring and every concurrent case are untested. Fine: nothing calls the module yet, so the default path is unchanged; `changed_now` checks `FREEZE_END` under `COLD`; a failed protection is rolled back with `thaw_range`; the handler's common path does not allocate and its lock order does not cycle with `freeze`, `look_with` or `open_with`; `take_after` runs after the protection. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Foniass commented 2026-12-02 13:23:18 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T13:23:18Z.


merge-check
base: 41aa60ce84
head: a2a329de2b
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2972 passed, 9 failed, 49 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on amd-dev); failing: gpu::recomp::lower_dxil::tests::f32_programs_on_the_gpu, gpu::recomp::tests::gpu_fract_f32_edges, hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping, hle::d3d12x::title_textures::tests::placed_title_textures_share_vram_and_preserve_pixels, hle::d3d12x::title_textures::tests::remapped_pages_are_compared_with_what_they_held, hle::d3d12x::title_textures::tests::stream_recheck_keeps_the_whole_upload_baseline_over_partial_uploads, hle::d3d12x::title_textures::tests::stream_recheck_partial_upload_without_an_entry_queues_a_whole_upload, hle::d3d12x::title_textures::tests::stream_recheck_schedule_catches_late_writes_and_resets_milestones (the same tests fail on amd-dev 41aa60ce alone on this card, so none is from this PR)
review: read by one reviewer at this same head; the review is at https://github.com/xcl-dev/xcl/pull/3639#issuecomment-7338009919 and its findings stand. Most serious: apply_faults runs carve over a fault's whole 2 MiB window (~250) without thawing it, so a sibling piece frozen after that fault is dropped while still read-only and the next write to it is an unhandled access violation.
performance: 60 s smoke of a retail title, amd-dev 41aa60ce vs this merge (a2a329de): 1671 -> 1680 frames shown (100 %; last presents per 2 s: 60 60 60), peak commit 16722 -> 16659 MB, 0 device removals, 0 crashes.
verdict: not yet: apply_faults runs carve over a fault's whole 2 MiB window (~250) without thawing it, so a sibling piece frozen after that fault is dropped while still read-only and the next write to it is an unhandled access violation (see the review)
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7346795845 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#issuecomment-7346795845). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T13:23:18Z. --- merge-check base: 41aa60ce842060a597b7e8724896f7bf6a031af5 head: a2a329de2b42845e921f5bdf3b595445910d5e93 merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2972 passed, 9 failed, 49 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on amd-dev); failing: gpu::recomp::lower_dxil::tests::f32_programs_on_the_gpu, gpu::recomp::tests::gpu_fract_f32_edges, hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping, hle::d3d12x::title_textures::tests::placed_title_textures_share_vram_and_preserve_pixels, hle::d3d12x::title_textures::tests::remapped_pages_are_compared_with_what_they_held, hle::d3d12x::title_textures::tests::stream_recheck_keeps_the_whole_upload_baseline_over_partial_uploads, hle::d3d12x::title_textures::tests::stream_recheck_partial_upload_without_an_entry_queues_a_whole_upload, hle::d3d12x::title_textures::tests::stream_recheck_schedule_catches_late_writes_and_resets_milestones (the same tests fail on amd-dev 41aa60ce alone on this card, so none is from this PR) review: read by one reviewer at this same head; the review is at https://github.com/xcl-dev/xcl/pull/3639#issuecomment-7338009919 and its findings stand. Most serious: `apply_faults` runs `carve` over a fault's whole 2 MiB window (~250) without thawing it, so a sibling piece frozen after that fault is dropped while still read-only and the next write to it is an unhandled access violation. performance: 60 s smoke of a retail title, amd-dev 41aa60ce vs this merge (a2a329de): 1671 -> 1680 frames shown (100 %; last presents per 2 s: 60 60 60), peak commit 16722 -> 16659 MB, 0 device removals, 0 crashes. verdict: not yet: `apply_faults` runs `carve` over a fault's whole 2 MiB window (~250) without thawing it, so a sibling piece frozen after that fault is dropped while still read-only and the next write to it is an unhandled access violation (see the review) hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5 AI-written and posted by Foniass without a human check of each point.
bmjask commented 2026-12-02 17:36:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:36:28Z.

Code review location: crates/xcl/src/hle/d3d12x/watch_cold.rs; line 250

@@ -0,0 +1,702 @@
+//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory
+//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans.
+//!
+//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default
+//!   2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path.
+//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB`
+//!   (default 4 MiB) are coalesced into one `GetWriteWatch` call.
+//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped
+//!   upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87.
+//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and
+//!   against title commits/decommits/protects via `guard` / `guard_free` / `changed`.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, Once, OnceLock};
+
+use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
+use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS};
+use windows_sys::Win32::System::Memory::{
+    VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ,
+    PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE,
+};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+const BLOCK: usize = 2 << 20;
+const FREEZE_AFTER: u8 = 4;
+const FREEZE_PER_LOOK: usize = 64;
+const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE;
+const WINDOW_PARTS: usize = 8;
+
+struct Cfg {
+    on: bool,
+    window: usize,
+    gap: usize,
+    hot_streak: u8,
+    hot_hold: u64,
+}
+
+fn env_num(name: &str, default: u64) -> u64 {
+    std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default)
+}
+
+fn cfg() -> &'static Cfg {
+    static CFG: OnceLock<Cfg> = OnceLock::new();
+    CFG.get_or_init(|| {
+        let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1");
+        let on = asked && guest_write::enabled();
+        if asked && !on {
+            crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+        }
+        let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096);
+        let window = (kb * 1024).next_power_of_two().min(4 << 20);
+        let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20;
+        let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1);
+        let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600);
+        if on {
+            crate::xlog_info!(
+                "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)",
+                window >> 10,
+                gap >> 20
+            );
+        }
+        Cfg { on, window, gap, hot_streak, hot_hold }
+    })
+}
+
+pub fn on() -> bool {
+    cfg().on
+}
+
+fn in_imported_uma(a: usize, n: usize) -> bool {
+    crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n))
+}
+
+struct Cold {
+    end: usize,
+    parts: Vec<(usize, usize, u32)>,
+}
+
+struct Opened {
+    e: [(usize, usize, usize, u64); 1024],
+    n: usize,
+}
+impl Opened {
+    const fn new() -> Self {
+        Self { e: [(0, 0, 0, 0); 1024], n: 0 }
+    }
+}
+
+#[derive(Default)]
+struct Heat {
+    last_frame: u64,
+    streak: u8,
+    hot_until: u64,
+}
+impl Heat {
+    fn fault(&mut self, f: u64, streak_at: u8, hold: u64) {
+        if f == self.last_frame {
+            return;
+        }
+        self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) {
+            self.streak.saturating_add(1)
+        } else {
+            1
+        };
+        self.last_frame = f;
+        if self.streak >= streak_at && hold > 0 {
+            self.hot_until = self.hot_until.max(f.saturating_add(hold));
+            self.streak = 0;
+        }
+    }
+    fn hot(&self, f: u64) -> bool {
+        f < self.hot_until
+    }
+}
+
+#[derive(Default)]
+struct Looks {
+    clean: HashMap<(usize, usize), u8>,
+    registered: Vec<(usize, usize)>,
+    ranges: Option<Arc<Vec<(usize, usize)>>>,
+    cold_gen: u64,
+    pieces: Vec<(usize, usize)>,
+}
+
+static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new());
+static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new());
+static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new());
+static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+static OPENED: Mutex<Opened> = Mutex::new(Opened::new());
+static HANDLING: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_AT: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_END: AtomicUsize = AtomicUsize::new(0);
+static COLD_GEN: AtomicU64 = AtomicU64::new(0);
+static LOOKS: Mutex<Option<Looks>> = Mutex::new(None);
+static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
+static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new());
+static HANDLER: Once = Once::new();
+static ACTIVE: AtomicBool = AtomicBool::new(false);
+
+fn frame() -> u64 {
+    super::present::activity().0.max(1)
+}
+
+fn read_only(p: u32) -> u32 {
+    let m = p & MODIFIERS;
+    match p & !MODIFIERS {
+        PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m,
+        _ => PAGE_READONLY | m,
+    }
+}
+
+fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> {
+    parts.iter().filter_map(|&(a, n, p)| {
+        let (s, e) = (a.max(lo), (a + n).min(hi));
+        (s < e).then_some((s, e - s, p))
+    }).collect()
+}
+
+unsafe fn thaw(parts: &[(usize, usize, u32)]) {
+    for &(a, n, p) in parts {
+        let mut at = a;
+        let end = a + n;
+        while at < end {
+            let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 {
+                break;
+            }
+            let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end);
+            if next <= at {
+                break;
+            }
+            if m.State == MEM_COMMIT && m.Protect == read_only(p) {
+                let mut old = 0;
+                let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old);
+            }
+            at = next;
+        }
+    }
+}
+
+fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) {
+    let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        let c = cold.remove(&s).unwrap();
+        if s < lo {
+            cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) });
+        }
+        if hi < c.end {
+            cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) });
+        }
+    }
+}
+
+unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) {
+    let end = a.saturating_add(n);
+    let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        if let Some(c) = cold.remove(&s) {
+            thaw(&c.parts);
+        }
+    }
+}
+
+unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> {
+    let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?;
+    if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) {
+        return None;
+    }
+    let end = cold[&s].end;
+    let w = at & !(window - 1);
+    let w_end = w.saturating_add(window);
+    let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+    let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa);
+    let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) };
+    let open: Vec<(usize, usize, u32)> = if multi {
+        let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k);
+        cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect()
+    } else {
+        clip(&cold[&s].parts, lo, hi)
+    };
+    thaw(&open);
+    carve(cold, lo, hi);
+    Some((lo, hi))
+}
+
+fn apply_faults() {
+    let opened: Vec<(usize, usize, usize, u64)> = {
+        let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner());
+        let n = std::mem::take(&mut r.n);
+        r.e[..n].to_vec()
+    };
+    if opened.is_empty() {
+        return;
+    }
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        for &(lo, hi, _, _) in &opened {
+            carve(&mut cold, lo, hi);

Critical: apply_faults carves queued fault windows out of COLD without thawing them, so any span freeze added inside that window after the fault was queued is dropped while its pages are still PAGE_READONLY. The default window is 2 MiB = BLOCK, so multi is true and the window is the whole block, not clipped to the span. If a title thread faults on cold span S during look_with's take calls, fault thaws S and only queues window W in the OPENED ring. Then the same look_with calls freeze(P) for a piece P in W (e.g. another watched range in the block): P doesn't overlap S, so it's protected read-only and inserted into COLD. The next apply_faults carves W and removes P's entry without thawing, so on the next title write to P fault finds nothing in COLD, VirtualQuery shows PAGE_READONLY, and the handler returns EXCEPTION_CONTINUE_SEARCH: an unhandled access violation. Thawing any COLD span inside the window before carving (or refusing to freeze inside a queued window) would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773491478 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#discussion_r4773491478). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:36:28Z. **Code review location:** `crates/xcl/src/hle/d3d12x/watch_cold.rs`; line 250 ~~~~diff @@ -0,0 +1,702 @@ +//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory +//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans. +//! +//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default +//! 2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path. +//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB` +//! (default 4 MiB) are coalesced into one `GetWriteWatch` call. +//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped +//! upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87. +//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and +//! against title commits/decommits/protects via `guard` / `guard_free` / `changed`. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, Once, OnceLock}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{ + VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE, +}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; +const BLOCK: usize = 2 << 20; +const FREEZE_AFTER: u8 = 4; +const FREEZE_PER_LOOK: usize = 64; +const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE; +const WINDOW_PARTS: usize = 8; + +struct Cfg { + on: bool, + window: usize, + gap: usize, + hot_streak: u8, + hot_hold: u64, +} + +fn env_num(name: &str, default: u64) -> u64 { + std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default) +} + +fn cfg() -> &'static Cfg { + static CFG: OnceLock<Cfg> = OnceLock::new(); + CFG.get_or_init(|| { + let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1"); + let on = asked && guest_write::enabled(); + if asked && !on { + crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + } + let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096); + let window = (kb * 1024).next_power_of_two().min(4 << 20); + let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20; + let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1); + let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600); + if on { + crate::xlog_info!( + "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)", + window >> 10, + gap >> 20 + ); + } + Cfg { on, window, gap, hot_streak, hot_hold } + }) +} + +pub fn on() -> bool { + cfg().on +} + +fn in_imported_uma(a: usize, n: usize) -> bool { + crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n)) +} + +struct Cold { + end: usize, + parts: Vec<(usize, usize, u32)>, +} + +struct Opened { + e: [(usize, usize, usize, u64); 1024], + n: usize, +} +impl Opened { + const fn new() -> Self { + Self { e: [(0, 0, 0, 0); 1024], n: 0 } + } +} + +#[derive(Default)] +struct Heat { + last_frame: u64, + streak: u8, + hot_until: u64, +} +impl Heat { + fn fault(&mut self, f: u64, streak_at: u8, hold: u64) { + if f == self.last_frame { + return; + } + self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) { + self.streak.saturating_add(1) + } else { + 1 + }; + self.last_frame = f; + if self.streak >= streak_at && hold > 0 { + self.hot_until = self.hot_until.max(f.saturating_add(hold)); + self.streak = 0; + } + } + fn hot(&self, f: u64) -> bool { + f < self.hot_until + } +} + +#[derive(Default)] +struct Looks { + clean: HashMap<(usize, usize), u8>, + registered: Vec<(usize, usize)>, + ranges: Option<Arc<Vec<(usize, usize)>>>, + cold_gen: u64, + pieces: Vec<(usize, usize)>, +} + +static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new()); +static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); +static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new()); +static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); +static OPENED: Mutex<Opened> = Mutex::new(Opened::new()); +static HANDLING: AtomicUsize = AtomicUsize::new(0); +static FREEZE_AT: AtomicUsize = AtomicUsize::new(0); +static FREEZE_END: AtomicUsize = AtomicUsize::new(0); +static COLD_GEN: AtomicU64 = AtomicU64::new(0); +static LOOKS: Mutex<Option<Looks>> = Mutex::new(None); +static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None); +static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new()); +static HANDLER: Once = Once::new(); +static ACTIVE: AtomicBool = AtomicBool::new(false); + +fn frame() -> u64 { + super::present::activity().0.max(1) +} + +fn read_only(p: u32) -> u32 { + let m = p & MODIFIERS; + match p & !MODIFIERS { + PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m, + _ => PAGE_READONLY | m, + } +} + +fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> { + parts.iter().filter_map(|&(a, n, p)| { + let (s, e) = (a.max(lo), (a + n).min(hi)); + (s < e).then_some((s, e - s, p)) + }).collect() +} + +unsafe fn thaw(parts: &[(usize, usize, u32)]) { + for &(a, n, p) in parts { + let mut at = a; + let end = a + n; + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 { + break; + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end); + if next <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == read_only(p) { + let mut old = 0; + let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old); + } + at = next; + } + } +} + +fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + let c = cold.remove(&s).unwrap(); + if s < lo { + cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) }); + } + if hi < c.end { + cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) }); + } + } +} + +unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) { + let end = a.saturating_add(n); + let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + if let Some(c) = cold.remove(&s) { + thaw(&c.parts); + } + } +} + +unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> { + let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?; + if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) { + return None; + } + let end = cold[&s].end; + let w = at & !(window - 1); + let w_end = w.saturating_add(window); + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa); + let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) }; + let open: Vec<(usize, usize, u32)> = if multi { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k); + cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect() + } else { + clip(&cold[&s].parts, lo, hi) + }; + thaw(&open); + carve(cold, lo, hi); + Some((lo, hi)) +} + +fn apply_faults() { + let opened: Vec<(usize, usize, usize, u64)> = { + let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + let n = std::mem::take(&mut r.n); + r.e[..n].to_vec() + }; + if opened.is_empty() { + return; + } + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + for &(lo, hi, _, _) in &opened { + carve(&mut cold, lo, hi); ~~~~ --- **Critical**: `apply_faults` carves queued fault windows out of COLD without thawing them, so any span `freeze` added inside that window after the fault was queued is dropped while its pages are still PAGE_READONLY. The default window is 2 MiB = BLOCK, so `multi` is true and the window is the whole block, not clipped to the span. If a title thread faults on cold span S during `look_with`'s `take` calls, `fault` thaws S and only queues window W in the OPENED ring. Then the same `look_with` calls `freeze(P)` for a piece P in W (e.g. another watched range in the block): P doesn't overlap S, so it's protected read-only and inserted into COLD. The next `apply_faults` carves W and removes P's entry without thawing, so on the next title write to P `fault` finds nothing in COLD, VirtualQuery shows PAGE_READONLY, and the handler returns EXCEPTION_CONTINUE_SEARCH: an unhandled access violation. Thawing any COLD span inside the window before carving (or refusing to freeze inside a queued window) would fix it.
bmjask commented 2026-12-02 17:36:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:36:28Z.

Code review location: crates/xcl/src/hle/d3d12x/watch_cold.rs; line 326

@@ -0,0 +1,702 @@
+//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory
+//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans.
+//!
+//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default
+//!   2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path.
+//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB`
+//!   (default 4 MiB) are coalesced into one `GetWriteWatch` call.
+//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped
+//!   upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87.
+//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and
+//!   against title commits/decommits/protects via `guard` / `guard_free` / `changed`.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, Once, OnceLock};
+
+use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
+use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS};
+use windows_sys::Win32::System::Memory::{
+    VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ,
+    PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE,
+};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+const BLOCK: usize = 2 << 20;
+const FREEZE_AFTER: u8 = 4;
+const FREEZE_PER_LOOK: usize = 64;
+const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE;
+const WINDOW_PARTS: usize = 8;
+
+struct Cfg {
+    on: bool,
+    window: usize,
+    gap: usize,
+    hot_streak: u8,
+    hot_hold: u64,
+}
+
+fn env_num(name: &str, default: u64) -> u64 {
+    std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default)
+}
+
+fn cfg() -> &'static Cfg {
+    static CFG: OnceLock<Cfg> = OnceLock::new();
+    CFG.get_or_init(|| {
+        let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1");
+        let on = asked && guest_write::enabled();
+        if asked && !on {
+            crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+        }
+        let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096);
+        let window = (kb * 1024).next_power_of_two().min(4 << 20);
+        let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20;
+        let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1);
+        let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600);
+        if on {
+            crate::xlog_info!(
+                "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)",
+                window >> 10,
+                gap >> 20
+            );
+        }
+        Cfg { on, window, gap, hot_streak, hot_hold }
+    })
+}
+
+pub fn on() -> bool {
+    cfg().on
+}
+
+fn in_imported_uma(a: usize, n: usize) -> bool {
+    crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n))
+}
+
+struct Cold {
+    end: usize,
+    parts: Vec<(usize, usize, u32)>,
+}
+
+struct Opened {
+    e: [(usize, usize, usize, u64); 1024],
+    n: usize,
+}
+impl Opened {
+    const fn new() -> Self {
+        Self { e: [(0, 0, 0, 0); 1024], n: 0 }
+    }
+}
+
+#[derive(Default)]
+struct Heat {
+    last_frame: u64,
+    streak: u8,
+    hot_until: u64,
+}
+impl Heat {
+    fn fault(&mut self, f: u64, streak_at: u8, hold: u64) {
+        if f == self.last_frame {
+            return;
+        }
+        self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) {
+            self.streak.saturating_add(1)
+        } else {
+            1
+        };
+        self.last_frame = f;
+        if self.streak >= streak_at && hold > 0 {
+            self.hot_until = self.hot_until.max(f.saturating_add(hold));
+            self.streak = 0;
+        }
+    }
+    fn hot(&self, f: u64) -> bool {
+        f < self.hot_until
+    }
+}
+
+#[derive(Default)]
+struct Looks {
+    clean: HashMap<(usize, usize), u8>,
+    registered: Vec<(usize, usize)>,
+    ranges: Option<Arc<Vec<(usize, usize)>>>,
+    cold_gen: u64,
+    pieces: Vec<(usize, usize)>,
+}
+
+static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new());
+static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new());
+static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new());
+static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+static OPENED: Mutex<Opened> = Mutex::new(Opened::new());
+static HANDLING: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_AT: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_END: AtomicUsize = AtomicUsize::new(0);
+static COLD_GEN: AtomicU64 = AtomicU64::new(0);
+static LOOKS: Mutex<Option<Looks>> = Mutex::new(None);
+static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
+static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new());
+static HANDLER: Once = Once::new();
+static ACTIVE: AtomicBool = AtomicBool::new(false);
+
+fn frame() -> u64 {
+    super::present::activity().0.max(1)
+}
+
+fn read_only(p: u32) -> u32 {
+    let m = p & MODIFIERS;
+    match p & !MODIFIERS {
+        PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m,
+        _ => PAGE_READONLY | m,
+    }
+}
+
+fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> {
+    parts.iter().filter_map(|&(a, n, p)| {
+        let (s, e) = (a.max(lo), (a + n).min(hi));
+        (s < e).then_some((s, e - s, p))
+    }).collect()
+}
+
+unsafe fn thaw(parts: &[(usize, usize, u32)]) {
+    for &(a, n, p) in parts {
+        let mut at = a;
+        let end = a + n;
+        while at < end {
+            let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 {
+                break;
+            }
+            let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end);
+            if next <= at {
+                break;
+            }
+            if m.State == MEM_COMMIT && m.Protect == read_only(p) {
+                let mut old = 0;
+                let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old);
+            }
+            at = next;
+        }
+    }
+}
+
+fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) {
+    let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        let c = cold.remove(&s).unwrap();
+        if s < lo {
+            cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) });
+        }
+        if hi < c.end {
+            cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) });
+        }
+    }
+}
+
+unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) {
+    let end = a.saturating_add(n);
+    let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        if let Some(c) = cold.remove(&s) {
+            thaw(&c.parts);
+        }
+    }
+}
+
+unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> {
+    let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?;
+    if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) {
+        return None;
+    }
+    let end = cold[&s].end;
+    let w = at & !(window - 1);
+    let w_end = w.saturating_add(window);
+    let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+    let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa);
+    let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) };
+    let open: Vec<(usize, usize, u32)> = if multi {
+        let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k);
+        cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect()
+    } else {
+        clip(&cold[&s].parts, lo, hi)
+    };
+    thaw(&open);
+    carve(cold, lo, hi);
+    Some((lo, hi))
+}
+
+fn apply_faults() {
+    let opened: Vec<(usize, usize, usize, u64)> = {
+        let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner());
+        let n = std::mem::take(&mut r.n);
+        r.e[..n].to_vec()
+    };
+    if opened.is_empty() {
+        return;
+    }
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        for &(lo, hi, _, _) in &opened {
+            carve(&mut cold, lo, hi);
+        }
+    }
+    {
+        let c = cfg();
+        let mut heat = HEAT.lock().unwrap_or_else(|e| e.into_inner());
+        for &(_, _, at, f) in &opened {
+            heat.entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+        }
+    }
+    FAULTED.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(_, _, at, _)| at & !(PAGE - 1)));
+    OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(lo, hi, _, _)| (lo, hi)));
+}
+
+fn was_ours(at: usize) -> bool {
+    EVER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|e| e.contains(&(at & !(BLOCK - 1))))
+}
+
+unsafe fn fault(at: usize, window: usize) -> bool {
+    let f = frame();
+    let mut open = [(0usize, 0usize, 0u32); WINDOW_PARTS];
+    let mut k = 0;
+    let (lo, hi);
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        let found = cold.range(..=at).next_back().filter(|(_, c)| at < c.end && c.parts.iter().any(|&(a, n, _)| a <= at && at < a + n));
+        let Some((&s, c)) = found else {
+            drop(cold);
+            let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0
+                && m.State == MEM_COMMIT
+                && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE);
+            return now && was_ours(at);
+        };
+        let c_end = c.end;
+        let w = at & !(window - 1);
+        let w_end = w.saturating_add(window);
+        let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+        let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa);
+        (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(c_end)) };
+        let mut over = false;
+        let mut push_parts = |parts: &[(usize, usize, u32)]| -> bool {
+            for &(a, n, p) in parts {
+                let (ps, pe) = (a.max(lo), (a + n).min(hi));
+                if ps < pe {
+                    if k == WINDOW_PARTS {
+                        return true;
+                    }
+                    open[k] = (ps, pe - ps, p);
+                    k += 1;
+                }
+            }
+            false
+        };
+        if multi {
+            let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&b, _)| b);
+            for (_, span) in cold.range(from..hi) {
+                if push_parts(&span.parts) {
+                    over = true;
+                    break;
+                }
+            }
+        } else {
+            over = push_parts(&c.parts);
+        }
+        if over {
+            let Some((lo, hi)) = open_window(&mut cold, at, window) else { return false };
+            drop(cold);
+            let c = cfg();
+            HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+            FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1));
+            OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi));
+            return true;
+        }
+        HANDLING.fetch_add(1, Ordering::AcqRel);
+    }
+    thaw(&open[..k]);

Critical: A fault during freeze's VirtualProtect loop over a multi-part span thaws only the parts already protected; the loop then protects the rest, and the queued window later removes the whole span from COLD. freeze inserts span [a, end) with parts p0..p2 (e.g. mixed write-combine and plain read-write regions) and protects p0. If another thread writes to p0 and faults, FREEZE_END overlaps, so multi is false and the window is clipped to the span. thaw restores p0 and skips p1/p2, which are still read-write. The freeze thread then protects p1/p2 and returns true, and the next apply_faults carves the span out of COLD, leaving p1/p2 read-only and untracked, so the next write there is an unhandled access violation. Rechecking for a fault on the span after the loop, and thawing everything if one happened, would close it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773491486 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#discussion_r4773491486). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:36:28Z. **Code review location:** `crates/xcl/src/hle/d3d12x/watch_cold.rs`; line 326 ~~~~diff @@ -0,0 +1,702 @@ +//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory +//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans. +//! +//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default +//! 2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path. +//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB` +//! (default 4 MiB) are coalesced into one `GetWriteWatch` call. +//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped +//! upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87. +//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and +//! against title commits/decommits/protects via `guard` / `guard_free` / `changed`. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, Once, OnceLock}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{ + VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE, +}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; +const BLOCK: usize = 2 << 20; +const FREEZE_AFTER: u8 = 4; +const FREEZE_PER_LOOK: usize = 64; +const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE; +const WINDOW_PARTS: usize = 8; + +struct Cfg { + on: bool, + window: usize, + gap: usize, + hot_streak: u8, + hot_hold: u64, +} + +fn env_num(name: &str, default: u64) -> u64 { + std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default) +} + +fn cfg() -> &'static Cfg { + static CFG: OnceLock<Cfg> = OnceLock::new(); + CFG.get_or_init(|| { + let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1"); + let on = asked && guest_write::enabled(); + if asked && !on { + crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + } + let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096); + let window = (kb * 1024).next_power_of_two().min(4 << 20); + let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20; + let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1); + let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600); + if on { + crate::xlog_info!( + "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)", + window >> 10, + gap >> 20 + ); + } + Cfg { on, window, gap, hot_streak, hot_hold } + }) +} + +pub fn on() -> bool { + cfg().on +} + +fn in_imported_uma(a: usize, n: usize) -> bool { + crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n)) +} + +struct Cold { + end: usize, + parts: Vec<(usize, usize, u32)>, +} + +struct Opened { + e: [(usize, usize, usize, u64); 1024], + n: usize, +} +impl Opened { + const fn new() -> Self { + Self { e: [(0, 0, 0, 0); 1024], n: 0 } + } +} + +#[derive(Default)] +struct Heat { + last_frame: u64, + streak: u8, + hot_until: u64, +} +impl Heat { + fn fault(&mut self, f: u64, streak_at: u8, hold: u64) { + if f == self.last_frame { + return; + } + self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) { + self.streak.saturating_add(1) + } else { + 1 + }; + self.last_frame = f; + if self.streak >= streak_at && hold > 0 { + self.hot_until = self.hot_until.max(f.saturating_add(hold)); + self.streak = 0; + } + } + fn hot(&self, f: u64) -> bool { + f < self.hot_until + } +} + +#[derive(Default)] +struct Looks { + clean: HashMap<(usize, usize), u8>, + registered: Vec<(usize, usize)>, + ranges: Option<Arc<Vec<(usize, usize)>>>, + cold_gen: u64, + pieces: Vec<(usize, usize)>, +} + +static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new()); +static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); +static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new()); +static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); +static OPENED: Mutex<Opened> = Mutex::new(Opened::new()); +static HANDLING: AtomicUsize = AtomicUsize::new(0); +static FREEZE_AT: AtomicUsize = AtomicUsize::new(0); +static FREEZE_END: AtomicUsize = AtomicUsize::new(0); +static COLD_GEN: AtomicU64 = AtomicU64::new(0); +static LOOKS: Mutex<Option<Looks>> = Mutex::new(None); +static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None); +static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new()); +static HANDLER: Once = Once::new(); +static ACTIVE: AtomicBool = AtomicBool::new(false); + +fn frame() -> u64 { + super::present::activity().0.max(1) +} + +fn read_only(p: u32) -> u32 { + let m = p & MODIFIERS; + match p & !MODIFIERS { + PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m, + _ => PAGE_READONLY | m, + } +} + +fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> { + parts.iter().filter_map(|&(a, n, p)| { + let (s, e) = (a.max(lo), (a + n).min(hi)); + (s < e).then_some((s, e - s, p)) + }).collect() +} + +unsafe fn thaw(parts: &[(usize, usize, u32)]) { + for &(a, n, p) in parts { + let mut at = a; + let end = a + n; + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 { + break; + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end); + if next <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == read_only(p) { + let mut old = 0; + let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old); + } + at = next; + } + } +} + +fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + let c = cold.remove(&s).unwrap(); + if s < lo { + cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) }); + } + if hi < c.end { + cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) }); + } + } +} + +unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) { + let end = a.saturating_add(n); + let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + if let Some(c) = cold.remove(&s) { + thaw(&c.parts); + } + } +} + +unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> { + let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?; + if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) { + return None; + } + let end = cold[&s].end; + let w = at & !(window - 1); + let w_end = w.saturating_add(window); + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa); + let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) }; + let open: Vec<(usize, usize, u32)> = if multi { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k); + cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect() + } else { + clip(&cold[&s].parts, lo, hi) + }; + thaw(&open); + carve(cold, lo, hi); + Some((lo, hi)) +} + +fn apply_faults() { + let opened: Vec<(usize, usize, usize, u64)> = { + let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + let n = std::mem::take(&mut r.n); + r.e[..n].to_vec() + }; + if opened.is_empty() { + return; + } + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + for &(lo, hi, _, _) in &opened { + carve(&mut cold, lo, hi); + } + } + { + let c = cfg(); + let mut heat = HEAT.lock().unwrap_or_else(|e| e.into_inner()); + for &(_, _, at, f) in &opened { + heat.entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + } + } + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(_, _, at, _)| at & !(PAGE - 1))); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(lo, hi, _, _)| (lo, hi))); +} + +fn was_ours(at: usize) -> bool { + EVER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|e| e.contains(&(at & !(BLOCK - 1)))) +} + +unsafe fn fault(at: usize, window: usize) -> bool { + let f = frame(); + let mut open = [(0usize, 0usize, 0u32); WINDOW_PARTS]; + let mut k = 0; + let (lo, hi); + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let found = cold.range(..=at).next_back().filter(|(_, c)| at < c.end && c.parts.iter().any(|&(a, n, _)| a <= at && at < a + n)); + let Some((&s, c)) = found else { + drop(cold); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 + && m.State == MEM_COMMIT + && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE); + return now && was_ours(at); + }; + let c_end = c.end; + let w = at & !(window - 1); + let w_end = w.saturating_add(window); + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa); + (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(c_end)) }; + let mut over = false; + let mut push_parts = |parts: &[(usize, usize, u32)]| -> bool { + for &(a, n, p) in parts { + let (ps, pe) = (a.max(lo), (a + n).min(hi)); + if ps < pe { + if k == WINDOW_PARTS { + return true; + } + open[k] = (ps, pe - ps, p); + k += 1; + } + } + false + }; + if multi { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&b, _)| b); + for (_, span) in cold.range(from..hi) { + if push_parts(&span.parts) { + over = true; + break; + } + } + } else { + over = push_parts(&c.parts); + } + if over { + let Some((lo, hi)) = open_window(&mut cold, at, window) else { return false }; + drop(cold); + let c = cfg(); + HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1)); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi)); + return true; + } + HANDLING.fetch_add(1, Ordering::AcqRel); + } + thaw(&open[..k]); ~~~~ --- **Critical**: A fault during `freeze`'s VirtualProtect loop over a multi-part span thaws only the parts already protected; the loop then protects the rest, and the queued window later removes the whole span from COLD. `freeze` inserts span [a, end) with parts p0..p2 (e.g. mixed write-combine and plain read-write regions) and protects p0. If another thread writes to p0 and faults, FREEZE_END overlaps, so `multi` is false and the window is clipped to the span. `thaw` restores p0 and skips p1/p2, which are still read-write. The freeze thread then protects p1/p2 and returns true, and the next `apply_faults` carves the span out of COLD, leaving p1/p2 read-only and untracked, so the next write there is an unhandled access violation. Rechecking for a fault on the span after the loop, and thawing everything if one happened, would close it.
bmjask commented 2026-12-02 17:36:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:36:28Z.

Code review location: crates/xcl/src/hle/d3d12x/watch_cold.rs; line 572

@@ -0,0 +1,702 @@
+//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory
+//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans.
+//!
+//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default
+//!   2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path.
+//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB`
+//!   (default 4 MiB) are coalesced into one `GetWriteWatch` call.
+//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped
+//!   upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87.
+//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and
+//!   against title commits/decommits/protects via `guard` / `guard_free` / `changed`.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, Once, OnceLock};
+
+use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
+use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS};
+use windows_sys::Win32::System::Memory::{
+    VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ,
+    PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE,
+};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+const BLOCK: usize = 2 << 20;
+const FREEZE_AFTER: u8 = 4;
+const FREEZE_PER_LOOK: usize = 64;
+const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE;
+const WINDOW_PARTS: usize = 8;
+
+struct Cfg {
+    on: bool,
+    window: usize,
+    gap: usize,
+    hot_streak: u8,
+    hot_hold: u64,
+}
+
+fn env_num(name: &str, default: u64) -> u64 {
+    std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default)
+}
+
+fn cfg() -> &'static Cfg {
+    static CFG: OnceLock<Cfg> = OnceLock::new();
+    CFG.get_or_init(|| {
+        let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1");
+        let on = asked && guest_write::enabled();
+        if asked && !on {
+            crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+        }
+        let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096);
+        let window = (kb * 1024).next_power_of_two().min(4 << 20);
+        let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20;
+        let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1);
+        let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600);
+        if on {
+            crate::xlog_info!(
+                "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)",
+                window >> 10,
+                gap >> 20
+            );
+        }
+        Cfg { on, window, gap, hot_streak, hot_hold }
+    })
+}
+
+pub fn on() -> bool {
+    cfg().on
+}
+
+fn in_imported_uma(a: usize, n: usize) -> bool {
+    crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n))
+}
+
+struct Cold {
+    end: usize,
+    parts: Vec<(usize, usize, u32)>,
+}
+
+struct Opened {
+    e: [(usize, usize, usize, u64); 1024],
+    n: usize,
+}
+impl Opened {
+    const fn new() -> Self {
+        Self { e: [(0, 0, 0, 0); 1024], n: 0 }
+    }
+}
+
+#[derive(Default)]
+struct Heat {
+    last_frame: u64,
+    streak: u8,
+    hot_until: u64,
+}
+impl Heat {
+    fn fault(&mut self, f: u64, streak_at: u8, hold: u64) {
+        if f == self.last_frame {
+            return;
+        }
+        self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) {
+            self.streak.saturating_add(1)
+        } else {
+            1
+        };
+        self.last_frame = f;
+        if self.streak >= streak_at && hold > 0 {
+            self.hot_until = self.hot_until.max(f.saturating_add(hold));
+            self.streak = 0;
+        }
+    }
+    fn hot(&self, f: u64) -> bool {
+        f < self.hot_until
+    }
+}
+
+#[derive(Default)]
+struct Looks {
+    clean: HashMap<(usize, usize), u8>,
+    registered: Vec<(usize, usize)>,
+    ranges: Option<Arc<Vec<(usize, usize)>>>,
+    cold_gen: u64,
+    pieces: Vec<(usize, usize)>,
+}
+
+static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new());
+static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new());
+static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new());
+static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+static OPENED: Mutex<Opened> = Mutex::new(Opened::new());
+static HANDLING: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_AT: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_END: AtomicUsize = AtomicUsize::new(0);
+static COLD_GEN: AtomicU64 = AtomicU64::new(0);
+static LOOKS: Mutex<Option<Looks>> = Mutex::new(None);
+static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
+static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new());
+static HANDLER: Once = Once::new();
+static ACTIVE: AtomicBool = AtomicBool::new(false);
+
+fn frame() -> u64 {
+    super::present::activity().0.max(1)
+}
+
+fn read_only(p: u32) -> u32 {
+    let m = p & MODIFIERS;
+    match p & !MODIFIERS {
+        PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m,
+        _ => PAGE_READONLY | m,
+    }
+}
+
+fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> {
+    parts.iter().filter_map(|&(a, n, p)| {
+        let (s, e) = (a.max(lo), (a + n).min(hi));
+        (s < e).then_some((s, e - s, p))
+    }).collect()
+}
+
+unsafe fn thaw(parts: &[(usize, usize, u32)]) {
+    for &(a, n, p) in parts {
+        let mut at = a;
+        let end = a + n;
+        while at < end {
+            let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 {
+                break;
+            }
+            let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end);
+            if next <= at {
+                break;
+            }
+            if m.State == MEM_COMMIT && m.Protect == read_only(p) {
+                let mut old = 0;
+                let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old);
+            }
+            at = next;
+        }
+    }
+}
+
+fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) {
+    let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        let c = cold.remove(&s).unwrap();
+        if s < lo {
+            cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) });
+        }
+        if hi < c.end {
+            cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) });
+        }
+    }
+}
+
+unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) {
+    let end = a.saturating_add(n);
+    let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        if let Some(c) = cold.remove(&s) {
+            thaw(&c.parts);
+        }
+    }
+}
+
+unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> {
+    let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?;
+    if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) {
+        return None;
+    }
+    let end = cold[&s].end;
+    let w = at & !(window - 1);
+    let w_end = w.saturating_add(window);
+    let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+    let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa);
+    let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) };
+    let open: Vec<(usize, usize, u32)> = if multi {
+        let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k);
+        cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect()
+    } else {
+        clip(&cold[&s].parts, lo, hi)
+    };
+    thaw(&open);
+    carve(cold, lo, hi);
+    Some((lo, hi))
+}
+
+fn apply_faults() {
+    let opened: Vec<(usize, usize, usize, u64)> = {
+        let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner());
+        let n = std::mem::take(&mut r.n);
+        r.e[..n].to_vec()
+    };
+    if opened.is_empty() {
+        return;
+    }
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        for &(lo, hi, _, _) in &opened {
+            carve(&mut cold, lo, hi);
+        }
+    }
+    {
+        let c = cfg();
+        let mut heat = HEAT.lock().unwrap_or_else(|e| e.into_inner());
+        for &(_, _, at, f) in &opened {
+            heat.entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+        }
+    }
+    FAULTED.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(_, _, at, _)| at & !(PAGE - 1)));
+    OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(lo, hi, _, _)| (lo, hi)));
+}
+
+fn was_ours(at: usize) -> bool {
+    EVER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|e| e.contains(&(at & !(BLOCK - 1))))
+}
+
+unsafe fn fault(at: usize, window: usize) -> bool {
+    let f = frame();
+    let mut open = [(0usize, 0usize, 0u32); WINDOW_PARTS];
+    let mut k = 0;
+    let (lo, hi);
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        let found = cold.range(..=at).next_back().filter(|(_, c)| at < c.end && c.parts.iter().any(|&(a, n, _)| a <= at && at < a + n));
+        let Some((&s, c)) = found else {
+            drop(cold);
+            let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0
+                && m.State == MEM_COMMIT
+                && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE);
+            return now && was_ours(at);
+        };
+        let c_end = c.end;
+        let w = at & !(window - 1);
+        let w_end = w.saturating_add(window);
+        let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+        let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa);
+        (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(c_end)) };
+        let mut over = false;
+        let mut push_parts = |parts: &[(usize, usize, u32)]| -> bool {
+            for &(a, n, p) in parts {
+                let (ps, pe) = (a.max(lo), (a + n).min(hi));
+                if ps < pe {
+                    if k == WINDOW_PARTS {
+                        return true;
+                    }
+                    open[k] = (ps, pe - ps, p);
+                    k += 1;
+                }
+            }
+            false
+        };
+        if multi {
+            let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&b, _)| b);
+            for (_, span) in cold.range(from..hi) {
+                if push_parts(&span.parts) {
+                    over = true;
+                    break;
+                }
+            }
+        } else {
+            over = push_parts(&c.parts);
+        }
+        if over {
+            let Some((lo, hi)) = open_window(&mut cold, at, window) else { return false };
+            drop(cold);
+            let c = cfg();
+            HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+            FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1));
+            OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi));
+            return true;
+        }
+        HANDLING.fetch_add(1, Ordering::AcqRel);
+    }
+    thaw(&open[..k]);
+    HANDLING.fetch_sub(1, Ordering::AcqRel);
+    let mut ring = OPENED.lock().unwrap_or_else(|e| e.into_inner());
+    if ring.n < ring.e.len() {
+        let i = ring.n;
+        ring.e[i] = (lo, hi, at, f);
+        ring.n += 1;
+        return true;
+    }
+    drop(ring);
+    carve(&mut COLD.lock().unwrap_or_else(|e| e.into_inner()), lo, hi);
+    let c = cfg();
+    HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+    FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1));
+    OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi));
+    true
+}
+
+unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
+    let r = &*(*info).ExceptionRecord;
+    if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1 {
+        if fault(r.ExceptionInformation[1], cfg().window) {
+            return -1;
+        }
+    }
+    0
+}
+
+fn install() {
+    HANDLER.call_once(|| unsafe {
+        AddVectoredExceptionHandler(1, Some(handler));
+    });
+}
+
+fn pin(a: usize, n: usize, d: isize) {
+    let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+    let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n));
+    while b < end {
+        if d > 0 {
+            *g.entry(b).or_default() += 1;
+        } else if let Some(c) = g.get_mut(&b) {
+            *c -= 1;
+            if *c == 0 {
+                g.remove(&b);
+            }
+        }
+        let Some(next) = b.checked_add(BLOCK) else { break };
+        b = next;
+    }
+}
+
+fn pinned(a: usize, n: usize) -> bool {
+    let g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+    let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n));
+    while b < end {
+        if g.contains_key(&b) {
+            return true;
+        }
+        let Some(next) = b.checked_add(BLOCK) else { break };
+        b = next;
+    }
+    false
+}
+
+unsafe fn changed_now(a: usize, n: usize) {
+    if n == 0 || !ACTIVE.load(Ordering::Acquire) {
+        return;
+    }
+    apply_faults();
+    let end = a.saturating_add(n);
+    loop {
+        {
+            let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+            let fe = FREEZE_END.load(Ordering::Acquire);
+            if fe == 0 || FREEZE_AT.load(Ordering::Acquire) >= end || a >= fe {
+                thaw_range(&mut cold, a, n);
+                break;
+            }
+        }
+        std::thread::yield_now();
+    }
+    while HANDLING.load(Ordering::Acquire) != 0 {
+        std::thread::yield_now();
+    }
+}
+
+pub struct Guard(usize, usize);
+impl Drop for Guard {
+    fn drop(&mut self) {
+        if self.1 != 0 {
+            pin(self.0, self.1, -1);
+        }
+    }
+}
+
+pub unsafe fn guard(a: usize, n: usize) -> Guard {
+    if n == 0 || !on() {
+        return Guard(0, 0);
+    }
+    pin(a, n, 1);
+    changed_now(a, n);
+    Guard(a, n)
+}
+
+pub unsafe fn guard_free(a: usize, n: usize) -> Guard {
+    if a == 0 || !on() {
+        return Guard(0, 0);
+    }
+    let len = if n != 0 {
+        n
+    } else {
+        let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+        if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 {
+            m.RegionSize
+        } else {
+            0
+        }
+    };
+    guard(a, len)
+}
+
+pub unsafe fn changed(a: usize, n: usize) {
+    if on() {
+        changed_now(a, n);
+    }
+}
+
+/// Freeze `[a, a + n)` read-only if all committed parts are read-write, unpinned, and outside
+/// guarded views / imported coherent UMA. Calls `take_after` after protecting so writes racing
+/// with `VirtualProtect` are never lost.
+unsafe fn freeze(a: usize, n: usize, mut take_after: impl FnMut(usize, usize)) -> bool {
+    if n == 0 || in_imported_uma(a, n) || guest_write::meets_guarded_view(a, n) {
+        return false;
+    }
+    let mut parts = Vec::new();
+    let mut at = a;
+    let end = a.saturating_add(n);
+    while at < end {
+        let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+        if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 {
+            return false;
+        }
+        let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end);
+        if next <= at {
+            return false;
+        }
+        if m.State == MEM_COMMIT {
+            if !matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE) {
+                return false;
+            }
+            parts.push((at, next - at, m.Protect));
+        }
+        at = next;
+    }
+    if parts.is_empty() {
+        return false;
+    }
+    install();
+    ACTIVE.store(true, Ordering::Release);
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        if pinned(a, n) || cold.range(..end).next_back().is_some_and(|(_, c)| c.end > a) {
+            return false;
+        }
+        FREEZE_AT.store(a, Ordering::Release);
+        FREEZE_END.store(end, Ordering::Release);
+        cold.insert(a, Cold { end, parts: parts.clone() });
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+        EVER.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashSet::new).insert(a & !(BLOCK - 1));
+    }
+    let ok = guest_write::while_unpinned(a, n, || {
+        for (i, &(pa, pn, p)) in parts.iter().enumerate() {
+            let mut old = 0;
+            if VirtualProtect(pa as *const c_void, pn, read_only(p), &mut old) == 0 {
+                thaw(&parts[..i]);
+                return false;
+            }
+        }
+        true
+    });
+    FREEZE_END.store(0, Ordering::Release);
+    if !ok {
+        thaw_range(&mut COLD.lock().unwrap_or_else(|e| e.into_inner()), a, n);
+        return false;
+    }
+    take_after(a, n);
+    true
+}
+
+fn hot_pieces(ranges: &[(usize, usize)], cold: &BTreeMap<usize, Cold>) -> Vec<(usize, usize)> {
+    let mut out = Vec::new();
+    for &(base, size) in ranges {
+        let mut at = base;
+        let end = base.saturating_add(size);
+        while at < end {
+            let next = ((at & !(BLOCK - 1)).saturating_add(BLOCK)).min(end);
+            let mut cur = at;
+            let from = cold.range(..=cur).next_back().filter(|(_, c)| c.end > cur).map_or(cur, |(&s, _)| s);
+            for (&s, c) in cold.range(from..next) {
+                if s > cur {
+                    out.push((cur, s - cur));
+                }
+                cur = cur.max(c.end);
+                if cur >= next {
+                    break;
+                }
+            }
+            if cur < next {
+                out.push((cur, next - cur));
+            }
+            at = next;
+        }
+    }
+    out
+}
+
+fn coalesce_calls(pieces: &[(usize, usize)], ranges: &[(usize, usize)], gap: usize) -> Vec<(usize, usize)> {
+    let mut calls: Vec<(usize, usize)> = Vec::with_capacity(pieces.len());
+    for &(a, n) in pieces {
+        let ri = ranges.partition_point(|&(b, s)| b + s <= a);
+        let r_end = ranges.get(ri).map_or(a + n, |&(b, s)| b + s);
+        match calls.last_mut() {
+            Some((ca, cn)) if a >= *ca + *cn && a - (*ca + *cn) <= gap && a + n <= r_end && *ca >= ranges.get(ri).map_or(0, |&(b, _)| b) => {
+                *cn = a + n - *ca;
+            }
+            _ => calls.push((a, n)),
+        }
+    }
+    calls
+}
+
+/// One look over `ranges`: drains faulted pages, scans non-cold pieces coalesced within
+/// `XCL_WATCH_COLD_GAP_MB`, and freezes clean cold pieces. Returns `(opened_ranges)` so the
+/// caller can warm blocks opened by a multi-block fault window.
+pub unsafe fn look_with(
+    ranges: &Arc<Vec<(usize, usize)>>,
+    hot: &[usize],
+    dirty: &mut Vec<usize>,
+    mut take: impl FnMut(usize, usize, &mut Vec<usize>),
+) -> Vec<(usize, usize)> {
+    apply_faults();
+    dirty.append(&mut FAULTED.lock().unwrap_or_else(|e| e.into_inner()));
+    let opened_ranges = std::mem::take(&mut *OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()));
+    let mut lg = LOOKS.lock().unwrap_or_else(|e| e.into_inner());
+    let ls = lg.get_or_insert_with(Looks::default);
+    if ls.registered != **ranges {
+        for &(a, n) in &ls.registered {

High: When the watched ranges change, look_with unregisters the old ranges from guest_write but doesn't thaw cold spans inside ranges that were dropped. If a range R with frozen spans is dropped while its memory stays alive, guest_write::unregister(R) runs but COLD still holds R's spans as PAGE_READONLY, and hot_pieces no longer looks at R, so they stay frozen for good. A later ReadFile/NtReadFile into R is no longer pinned or touched by guest_write::open, so the kernel fails it with ERROR_NOACCESS / STATUS_ACCESS_VIOLATION and the data silently isn't loaded. There's also a short window between unregistering the old ranges and registering the new ones where kernel writes into still-cold ranges fail. Thawing dropped ranges' spans before unregistering would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773491493 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#discussion_r4773491493). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:36:28Z. **Code review location:** `crates/xcl/src/hle/d3d12x/watch_cold.rs`; line 572 ~~~~diff @@ -0,0 +1,702 @@ +//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory +//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans. +//! +//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default +//! 2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path. +//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB` +//! (default 4 MiB) are coalesced into one `GetWriteWatch` call. +//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped +//! upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87. +//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and +//! against title commits/decommits/protects via `guard` / `guard_free` / `changed`. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, Once, OnceLock}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{ + VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE, +}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; +const BLOCK: usize = 2 << 20; +const FREEZE_AFTER: u8 = 4; +const FREEZE_PER_LOOK: usize = 64; +const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE; +const WINDOW_PARTS: usize = 8; + +struct Cfg { + on: bool, + window: usize, + gap: usize, + hot_streak: u8, + hot_hold: u64, +} + +fn env_num(name: &str, default: u64) -> u64 { + std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default) +} + +fn cfg() -> &'static Cfg { + static CFG: OnceLock<Cfg> = OnceLock::new(); + CFG.get_or_init(|| { + let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1"); + let on = asked && guest_write::enabled(); + if asked && !on { + crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + } + let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096); + let window = (kb * 1024).next_power_of_two().min(4 << 20); + let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20; + let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1); + let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600); + if on { + crate::xlog_info!( + "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)", + window >> 10, + gap >> 20 + ); + } + Cfg { on, window, gap, hot_streak, hot_hold } + }) +} + +pub fn on() -> bool { + cfg().on +} + +fn in_imported_uma(a: usize, n: usize) -> bool { + crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n)) +} + +struct Cold { + end: usize, + parts: Vec<(usize, usize, u32)>, +} + +struct Opened { + e: [(usize, usize, usize, u64); 1024], + n: usize, +} +impl Opened { + const fn new() -> Self { + Self { e: [(0, 0, 0, 0); 1024], n: 0 } + } +} + +#[derive(Default)] +struct Heat { + last_frame: u64, + streak: u8, + hot_until: u64, +} +impl Heat { + fn fault(&mut self, f: u64, streak_at: u8, hold: u64) { + if f == self.last_frame { + return; + } + self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) { + self.streak.saturating_add(1) + } else { + 1 + }; + self.last_frame = f; + if self.streak >= streak_at && hold > 0 { + self.hot_until = self.hot_until.max(f.saturating_add(hold)); + self.streak = 0; + } + } + fn hot(&self, f: u64) -> bool { + f < self.hot_until + } +} + +#[derive(Default)] +struct Looks { + clean: HashMap<(usize, usize), u8>, + registered: Vec<(usize, usize)>, + ranges: Option<Arc<Vec<(usize, usize)>>>, + cold_gen: u64, + pieces: Vec<(usize, usize)>, +} + +static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new()); +static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); +static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new()); +static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); +static OPENED: Mutex<Opened> = Mutex::new(Opened::new()); +static HANDLING: AtomicUsize = AtomicUsize::new(0); +static FREEZE_AT: AtomicUsize = AtomicUsize::new(0); +static FREEZE_END: AtomicUsize = AtomicUsize::new(0); +static COLD_GEN: AtomicU64 = AtomicU64::new(0); +static LOOKS: Mutex<Option<Looks>> = Mutex::new(None); +static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None); +static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new()); +static HANDLER: Once = Once::new(); +static ACTIVE: AtomicBool = AtomicBool::new(false); + +fn frame() -> u64 { + super::present::activity().0.max(1) +} + +fn read_only(p: u32) -> u32 { + let m = p & MODIFIERS; + match p & !MODIFIERS { + PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m, + _ => PAGE_READONLY | m, + } +} + +fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> { + parts.iter().filter_map(|&(a, n, p)| { + let (s, e) = (a.max(lo), (a + n).min(hi)); + (s < e).then_some((s, e - s, p)) + }).collect() +} + +unsafe fn thaw(parts: &[(usize, usize, u32)]) { + for &(a, n, p) in parts { + let mut at = a; + let end = a + n; + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 { + break; + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end); + if next <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == read_only(p) { + let mut old = 0; + let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old); + } + at = next; + } + } +} + +fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + let c = cold.remove(&s).unwrap(); + if s < lo { + cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) }); + } + if hi < c.end { + cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) }); + } + } +} + +unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) { + let end = a.saturating_add(n); + let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + if let Some(c) = cold.remove(&s) { + thaw(&c.parts); + } + } +} + +unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> { + let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?; + if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) { + return None; + } + let end = cold[&s].end; + let w = at & !(window - 1); + let w_end = w.saturating_add(window); + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa); + let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) }; + let open: Vec<(usize, usize, u32)> = if multi { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k); + cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect() + } else { + clip(&cold[&s].parts, lo, hi) + }; + thaw(&open); + carve(cold, lo, hi); + Some((lo, hi)) +} + +fn apply_faults() { + let opened: Vec<(usize, usize, usize, u64)> = { + let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + let n = std::mem::take(&mut r.n); + r.e[..n].to_vec() + }; + if opened.is_empty() { + return; + } + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + for &(lo, hi, _, _) in &opened { + carve(&mut cold, lo, hi); + } + } + { + let c = cfg(); + let mut heat = HEAT.lock().unwrap_or_else(|e| e.into_inner()); + for &(_, _, at, f) in &opened { + heat.entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + } + } + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(_, _, at, _)| at & !(PAGE - 1))); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(lo, hi, _, _)| (lo, hi))); +} + +fn was_ours(at: usize) -> bool { + EVER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|e| e.contains(&(at & !(BLOCK - 1)))) +} + +unsafe fn fault(at: usize, window: usize) -> bool { + let f = frame(); + let mut open = [(0usize, 0usize, 0u32); WINDOW_PARTS]; + let mut k = 0; + let (lo, hi); + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let found = cold.range(..=at).next_back().filter(|(_, c)| at < c.end && c.parts.iter().any(|&(a, n, _)| a <= at && at < a + n)); + let Some((&s, c)) = found else { + drop(cold); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 + && m.State == MEM_COMMIT + && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE); + return now && was_ours(at); + }; + let c_end = c.end; + let w = at & !(window - 1); + let w_end = w.saturating_add(window); + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa); + (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(c_end)) }; + let mut over = false; + let mut push_parts = |parts: &[(usize, usize, u32)]| -> bool { + for &(a, n, p) in parts { + let (ps, pe) = (a.max(lo), (a + n).min(hi)); + if ps < pe { + if k == WINDOW_PARTS { + return true; + } + open[k] = (ps, pe - ps, p); + k += 1; + } + } + false + }; + if multi { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&b, _)| b); + for (_, span) in cold.range(from..hi) { + if push_parts(&span.parts) { + over = true; + break; + } + } + } else { + over = push_parts(&c.parts); + } + if over { + let Some((lo, hi)) = open_window(&mut cold, at, window) else { return false }; + drop(cold); + let c = cfg(); + HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1)); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi)); + return true; + } + HANDLING.fetch_add(1, Ordering::AcqRel); + } + thaw(&open[..k]); + HANDLING.fetch_sub(1, Ordering::AcqRel); + let mut ring = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + if ring.n < ring.e.len() { + let i = ring.n; + ring.e[i] = (lo, hi, at, f); + ring.n += 1; + return true; + } + drop(ring); + carve(&mut COLD.lock().unwrap_or_else(|e| e.into_inner()), lo, hi); + let c = cfg(); + HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1)); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi)); + true +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1 { + if fault(r.ExceptionInformation[1], cfg().window) { + return -1; + } + } + 0 +} + +fn install() { + HANDLER.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +fn pin(a: usize, n: usize, d: isize) { + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n)); + while b < end { + if d > 0 { + *g.entry(b).or_default() += 1; + } else if let Some(c) = g.get_mut(&b) { + *c -= 1; + if *c == 0 { + g.remove(&b); + } + } + let Some(next) = b.checked_add(BLOCK) else { break }; + b = next; + } +} + +fn pinned(a: usize, n: usize) -> bool { + let g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n)); + while b < end { + if g.contains_key(&b) { + return true; + } + let Some(next) = b.checked_add(BLOCK) else { break }; + b = next; + } + false +} + +unsafe fn changed_now(a: usize, n: usize) { + if n == 0 || !ACTIVE.load(Ordering::Acquire) { + return; + } + apply_faults(); + let end = a.saturating_add(n); + loop { + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let fe = FREEZE_END.load(Ordering::Acquire); + if fe == 0 || FREEZE_AT.load(Ordering::Acquire) >= end || a >= fe { + thaw_range(&mut cold, a, n); + break; + } + } + std::thread::yield_now(); + } + while HANDLING.load(Ordering::Acquire) != 0 { + std::thread::yield_now(); + } +} + +pub struct Guard(usize, usize); +impl Drop for Guard { + fn drop(&mut self) { + if self.1 != 0 { + pin(self.0, self.1, -1); + } + } +} + +pub unsafe fn guard(a: usize, n: usize) -> Guard { + if n == 0 || !on() { + return Guard(0, 0); + } + pin(a, n, 1); + changed_now(a, n); + Guard(a, n) +} + +pub unsafe fn guard_free(a: usize, n: usize) -> Guard { + if a == 0 || !on() { + return Guard(0, 0); + } + let len = if n != 0 { + n + } else { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 { + m.RegionSize + } else { + 0 + } + }; + guard(a, len) +} + +pub unsafe fn changed(a: usize, n: usize) { + if on() { + changed_now(a, n); + } +} + +/// Freeze `[a, a + n)` read-only if all committed parts are read-write, unpinned, and outside +/// guarded views / imported coherent UMA. Calls `take_after` after protecting so writes racing +/// with `VirtualProtect` are never lost. +unsafe fn freeze(a: usize, n: usize, mut take_after: impl FnMut(usize, usize)) -> bool { + if n == 0 || in_imported_uma(a, n) || guest_write::meets_guarded_view(a, n) { + return false; + } + let mut parts = Vec::new(); + let mut at = a; + let end = a.saturating_add(n); + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 { + return false; + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end); + if next <= at { + return false; + } + if m.State == MEM_COMMIT { + if !matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE) { + return false; + } + parts.push((at, next - at, m.Protect)); + } + at = next; + } + if parts.is_empty() { + return false; + } + install(); + ACTIVE.store(true, Ordering::Release); + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + if pinned(a, n) || cold.range(..end).next_back().is_some_and(|(_, c)| c.end > a) { + return false; + } + FREEZE_AT.store(a, Ordering::Release); + FREEZE_END.store(end, Ordering::Release); + cold.insert(a, Cold { end, parts: parts.clone() }); + COLD_GEN.fetch_add(1, Ordering::AcqRel); + EVER.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_with(HashSet::new).insert(a & !(BLOCK - 1)); + } + let ok = guest_write::while_unpinned(a, n, || { + for (i, &(pa, pn, p)) in parts.iter().enumerate() { + let mut old = 0; + if VirtualProtect(pa as *const c_void, pn, read_only(p), &mut old) == 0 { + thaw(&parts[..i]); + return false; + } + } + true + }); + FREEZE_END.store(0, Ordering::Release); + if !ok { + thaw_range(&mut COLD.lock().unwrap_or_else(|e| e.into_inner()), a, n); + return false; + } + take_after(a, n); + true +} + +fn hot_pieces(ranges: &[(usize, usize)], cold: &BTreeMap<usize, Cold>) -> Vec<(usize, usize)> { + let mut out = Vec::new(); + for &(base, size) in ranges { + let mut at = base; + let end = base.saturating_add(size); + while at < end { + let next = ((at & !(BLOCK - 1)).saturating_add(BLOCK)).min(end); + let mut cur = at; + let from = cold.range(..=cur).next_back().filter(|(_, c)| c.end > cur).map_or(cur, |(&s, _)| s); + for (&s, c) in cold.range(from..next) { + if s > cur { + out.push((cur, s - cur)); + } + cur = cur.max(c.end); + if cur >= next { + break; + } + } + if cur < next { + out.push((cur, next - cur)); + } + at = next; + } + } + out +} + +fn coalesce_calls(pieces: &[(usize, usize)], ranges: &[(usize, usize)], gap: usize) -> Vec<(usize, usize)> { + let mut calls: Vec<(usize, usize)> = Vec::with_capacity(pieces.len()); + for &(a, n) in pieces { + let ri = ranges.partition_point(|&(b, s)| b + s <= a); + let r_end = ranges.get(ri).map_or(a + n, |&(b, s)| b + s); + match calls.last_mut() { + Some((ca, cn)) if a >= *ca + *cn && a - (*ca + *cn) <= gap && a + n <= r_end && *ca >= ranges.get(ri).map_or(0, |&(b, _)| b) => { + *cn = a + n - *ca; + } + _ => calls.push((a, n)), + } + } + calls +} + +/// One look over `ranges`: drains faulted pages, scans non-cold pieces coalesced within +/// `XCL_WATCH_COLD_GAP_MB`, and freezes clean cold pieces. Returns `(opened_ranges)` so the +/// caller can warm blocks opened by a multi-block fault window. +pub unsafe fn look_with( + ranges: &Arc<Vec<(usize, usize)>>, + hot: &[usize], + dirty: &mut Vec<usize>, + mut take: impl FnMut(usize, usize, &mut Vec<usize>), +) -> Vec<(usize, usize)> { + apply_faults(); + dirty.append(&mut FAULTED.lock().unwrap_or_else(|e| e.into_inner())); + let opened_ranges = std::mem::take(&mut *OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner())); + let mut lg = LOOKS.lock().unwrap_or_else(|e| e.into_inner()); + let ls = lg.get_or_insert_with(Looks::default); + if ls.registered != **ranges { + for &(a, n) in &ls.registered { ~~~~ --- **High**: When the watched ranges change, `look_with` unregisters the old ranges from guest_write but doesn't thaw cold spans inside ranges that were dropped. If a range R with frozen spans is dropped while its memory stays alive, `guest_write::unregister(R)` runs but COLD still holds R's spans as PAGE_READONLY, and `hot_pieces` no longer looks at R, so they stay frozen for good. A later ReadFile/NtReadFile into R is no longer pinned or touched by `guest_write::open`, so the kernel fails it with ERROR_NOACCESS / STATUS_ACCESS_VIOLATION and the data silently isn't loaded. There's also a short window between unregistering the old ranges and registering the new ones where kernel writes into still-cold ranges fail. Thawing dropped ranges' spans before unregistering would fix it.
bmjask commented 2026-12-02 17:36:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:36:28Z.

Code review location: crates/xcl/src/hle/d3d12x/watch_cold.rs; line 438

@@ -0,0 +1,702 @@
+//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory
+//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans.
+//!
+//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default
+//!   2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path.
+//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB`
+//!   (default 4 MiB) are coalesced into one `GetWriteWatch` call.
+//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped
+//!   upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87.
+//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and
+//!   against title commits/decommits/protects via `guard` / `guard_free` / `changed`.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, Once, OnceLock};
+
+use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
+use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS};
+use windows_sys::Win32::System::Memory::{
+    VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ,
+    PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE,
+};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+const BLOCK: usize = 2 << 20;
+const FREEZE_AFTER: u8 = 4;
+const FREEZE_PER_LOOK: usize = 64;
+const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE;
+const WINDOW_PARTS: usize = 8;
+
+struct Cfg {
+    on: bool,
+    window: usize,
+    gap: usize,
+    hot_streak: u8,
+    hot_hold: u64,
+}
+
+fn env_num(name: &str, default: u64) -> u64 {
+    std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default)
+}
+
+fn cfg() -> &'static Cfg {
+    static CFG: OnceLock<Cfg> = OnceLock::new();
+    CFG.get_or_init(|| {
+        let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1");
+        let on = asked && guest_write::enabled();
+        if asked && !on {
+            crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+        }
+        let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096);
+        let window = (kb * 1024).next_power_of_two().min(4 << 20);
+        let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20;
+        let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1);
+        let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600);
+        if on {
+            crate::xlog_info!(
+                "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)",
+                window >> 10,
+                gap >> 20
+            );
+        }
+        Cfg { on, window, gap, hot_streak, hot_hold }
+    })
+}
+
+pub fn on() -> bool {
+    cfg().on
+}
+
+fn in_imported_uma(a: usize, n: usize) -> bool {
+    crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n))
+}
+
+struct Cold {
+    end: usize,
+    parts: Vec<(usize, usize, u32)>,
+}
+
+struct Opened {
+    e: [(usize, usize, usize, u64); 1024],
+    n: usize,
+}
+impl Opened {
+    const fn new() -> Self {
+        Self { e: [(0, 0, 0, 0); 1024], n: 0 }
+    }
+}
+
+#[derive(Default)]
+struct Heat {
+    last_frame: u64,
+    streak: u8,
+    hot_until: u64,
+}
+impl Heat {
+    fn fault(&mut self, f: u64, streak_at: u8, hold: u64) {
+        if f == self.last_frame {
+            return;
+        }
+        self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) {
+            self.streak.saturating_add(1)
+        } else {
+            1
+        };
+        self.last_frame = f;
+        if self.streak >= streak_at && hold > 0 {
+            self.hot_until = self.hot_until.max(f.saturating_add(hold));
+            self.streak = 0;
+        }
+    }
+    fn hot(&self, f: u64) -> bool {
+        f < self.hot_until
+    }
+}
+
+#[derive(Default)]
+struct Looks {
+    clean: HashMap<(usize, usize), u8>,
+    registered: Vec<(usize, usize)>,
+    ranges: Option<Arc<Vec<(usize, usize)>>>,
+    cold_gen: u64,
+    pieces: Vec<(usize, usize)>,
+}
+
+static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new());
+static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new());
+static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new());
+static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+static OPENED: Mutex<Opened> = Mutex::new(Opened::new());
+static HANDLING: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_AT: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_END: AtomicUsize = AtomicUsize::new(0);
+static COLD_GEN: AtomicU64 = AtomicU64::new(0);
+static LOOKS: Mutex<Option<Looks>> = Mutex::new(None);
+static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
+static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new());
+static HANDLER: Once = Once::new();
+static ACTIVE: AtomicBool = AtomicBool::new(false);
+
+fn frame() -> u64 {
+    super::present::activity().0.max(1)
+}
+
+fn read_only(p: u32) -> u32 {
+    let m = p & MODIFIERS;
+    match p & !MODIFIERS {
+        PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m,
+        _ => PAGE_READONLY | m,
+    }
+}
+
+fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> {
+    parts.iter().filter_map(|&(a, n, p)| {
+        let (s, e) = (a.max(lo), (a + n).min(hi));
+        (s < e).then_some((s, e - s, p))
+    }).collect()
+}
+
+unsafe fn thaw(parts: &[(usize, usize, u32)]) {
+    for &(a, n, p) in parts {
+        let mut at = a;
+        let end = a + n;
+        while at < end {
+            let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 {
+                break;
+            }
+            let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end);
+            if next <= at {
+                break;
+            }
+            if m.State == MEM_COMMIT && m.Protect == read_only(p) {
+                let mut old = 0;
+                let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old);
+            }
+            at = next;
+        }
+    }
+}
+
+fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) {
+    let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        let c = cold.remove(&s).unwrap();
+        if s < lo {
+            cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) });
+        }
+        if hi < c.end {
+            cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) });
+        }
+    }
+}
+
+unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) {
+    let end = a.saturating_add(n);
+    let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        if let Some(c) = cold.remove(&s) {
+            thaw(&c.parts);
+        }
+    }
+}
+
+unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> {
+    let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?;
+    if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) {
+        return None;
+    }
+    let end = cold[&s].end;
+    let w = at & !(window - 1);
+    let w_end = w.saturating_add(window);
+    let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+    let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa);
+    let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) };
+    let open: Vec<(usize, usize, u32)> = if multi {
+        let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k);
+        cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect()
+    } else {
+        clip(&cold[&s].parts, lo, hi)
+    };
+    thaw(&open);
+    carve(cold, lo, hi);
+    Some((lo, hi))
+}
+
+fn apply_faults() {
+    let opened: Vec<(usize, usize, usize, u64)> = {
+        let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner());
+        let n = std::mem::take(&mut r.n);
+        r.e[..n].to_vec()
+    };
+    if opened.is_empty() {
+        return;
+    }
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        for &(lo, hi, _, _) in &opened {
+            carve(&mut cold, lo, hi);
+        }
+    }
+    {
+        let c = cfg();
+        let mut heat = HEAT.lock().unwrap_or_else(|e| e.into_inner());
+        for &(_, _, at, f) in &opened {
+            heat.entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+        }
+    }
+    FAULTED.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(_, _, at, _)| at & !(PAGE - 1)));
+    OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(lo, hi, _, _)| (lo, hi)));
+}
+
+fn was_ours(at: usize) -> bool {
+    EVER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|e| e.contains(&(at & !(BLOCK - 1))))
+}
+
+unsafe fn fault(at: usize, window: usize) -> bool {
+    let f = frame();
+    let mut open = [(0usize, 0usize, 0u32); WINDOW_PARTS];
+    let mut k = 0;
+    let (lo, hi);
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        let found = cold.range(..=at).next_back().filter(|(_, c)| at < c.end && c.parts.iter().any(|&(a, n, _)| a <= at && at < a + n));
+        let Some((&s, c)) = found else {
+            drop(cold);
+            let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0
+                && m.State == MEM_COMMIT
+                && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE);
+            return now && was_ours(at);
+        };
+        let c_end = c.end;
+        let w = at & !(window - 1);
+        let w_end = w.saturating_add(window);
+        let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+        let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa);
+        (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(c_end)) };
+        let mut over = false;
+        let mut push_parts = |parts: &[(usize, usize, u32)]| -> bool {
+            for &(a, n, p) in parts {
+                let (ps, pe) = (a.max(lo), (a + n).min(hi));
+                if ps < pe {
+                    if k == WINDOW_PARTS {
+                        return true;
+                    }
+                    open[k] = (ps, pe - ps, p);
+                    k += 1;
+                }
+            }
+            false
+        };
+        if multi {
+            let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&b, _)| b);
+            for (_, span) in cold.range(from..hi) {
+                if push_parts(&span.parts) {
+                    over = true;
+                    break;
+                }
+            }
+        } else {
+            over = push_parts(&c.parts);
+        }
+        if over {
+            let Some((lo, hi)) = open_window(&mut cold, at, window) else { return false };
+            drop(cold);
+            let c = cfg();
+            HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+            FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1));
+            OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi));
+            return true;
+        }
+        HANDLING.fetch_add(1, Ordering::AcqRel);
+    }
+    thaw(&open[..k]);
+    HANDLING.fetch_sub(1, Ordering::AcqRel);
+    let mut ring = OPENED.lock().unwrap_or_else(|e| e.into_inner());
+    if ring.n < ring.e.len() {
+        let i = ring.n;
+        ring.e[i] = (lo, hi, at, f);
+        ring.n += 1;
+        return true;
+    }
+    drop(ring);
+    carve(&mut COLD.lock().unwrap_or_else(|e| e.into_inner()), lo, hi);
+    let c = cfg();
+    HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+    FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1));
+    OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi));
+    true
+}
+
+unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
+    let r = &*(*info).ExceptionRecord;
+    if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1 {
+        if fault(r.ExceptionInformation[1], cfg().window) {
+            return -1;
+        }
+    }
+    0
+}
+
+fn install() {
+    HANDLER.call_once(|| unsafe {
+        AddVectoredExceptionHandler(1, Some(handler));
+    });
+}
+
+fn pin(a: usize, n: usize, d: isize) {
+    let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+    let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n));
+    while b < end {
+        if d > 0 {
+            *g.entry(b).or_default() += 1;
+        } else if let Some(c) = g.get_mut(&b) {
+            *c -= 1;
+            if *c == 0 {
+                g.remove(&b);
+            }
+        }
+        let Some(next) = b.checked_add(BLOCK) else { break };
+        b = next;
+    }
+}
+
+fn pinned(a: usize, n: usize) -> bool {
+    let g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+    let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n));
+    while b < end {
+        if g.contains_key(&b) {
+            return true;
+        }
+        let Some(next) = b.checked_add(BLOCK) else { break };
+        b = next;
+    }
+    false
+}
+
+unsafe fn changed_now(a: usize, n: usize) {
+    if n == 0 || !ACTIVE.load(Ordering::Acquire) {
+        return;
+    }
+    apply_faults();
+    let end = a.saturating_add(n);
+    loop {
+        {
+            let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+            let fe = FREEZE_END.load(Ordering::Acquire);
+            if fe == 0 || FREEZE_AT.load(Ordering::Acquire) >= end || a >= fe {
+                thaw_range(&mut cold, a, n);
+                break;
+            }
+        }
+        std::thread::yield_now();
+    }
+    while HANDLING.load(Ordering::Acquire) != 0 {
+        std::thread::yield_now();
+    }
+}
+
+pub struct Guard(usize, usize);
+impl Drop for Guard {
+    fn drop(&mut self) {
+        if self.1 != 0 {
+            pin(self.0, self.1, -1);
+        }
+    }
+}
+
+pub unsafe fn guard(a: usize, n: usize) -> Guard {
+    if n == 0 || !on() {
+        return Guard(0, 0);
+    }
+    pin(a, n, 1);
+    changed_now(a, n);
+    Guard(a, n)
+}
+
+pub unsafe fn guard_free(a: usize, n: usize) -> Guard {
+    if a == 0 || !on() {
+        return Guard(0, 0);
+    }
+    let len = if n != 0 {
+        n
+    } else {
+        let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+        if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 {

High: For guard_free(a, 0) the length comes from VirtualQuery's RegionSize at a, which covers only the first region with uniform attributes, and freezing itself splits allocations into read-only and read-write regions. If the title calls VirtualFree(base, 0, MEM_RELEASE) on a 64 MiB allocation whose second block is frozen, RegionSize at base stops at the first protection change (e.g. 2 MiB), so changed_now and thaw_range clear only that part, and the cold spans after it stay in COLD after release. If the address is reused for a new watched allocation, hot_pieces keeps leaving those stale spans out of the GetWriteWatch scan, so CPU writes there never reach the GPU, and fault can make a page the title marked PAGE_READONLY on purpose writable. Walking regions with the same AllocationBase to get the whole allocation would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773491497 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#discussion_r4773491497). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:36:28Z. **Code review location:** `crates/xcl/src/hle/d3d12x/watch_cold.rs`; line 438 ~~~~diff @@ -0,0 +1,702 @@ +//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory +//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans. +//! +//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default +//! 2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path. +//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB` +//! (default 4 MiB) are coalesced into one `GetWriteWatch` call. +//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped +//! upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87. +//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and +//! against title commits/decommits/protects via `guard` / `guard_free` / `changed`. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, Once, OnceLock}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{ + VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE, +}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; +const BLOCK: usize = 2 << 20; +const FREEZE_AFTER: u8 = 4; +const FREEZE_PER_LOOK: usize = 64; +const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE; +const WINDOW_PARTS: usize = 8; + +struct Cfg { + on: bool, + window: usize, + gap: usize, + hot_streak: u8, + hot_hold: u64, +} + +fn env_num(name: &str, default: u64) -> u64 { + std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default) +} + +fn cfg() -> &'static Cfg { + static CFG: OnceLock<Cfg> = OnceLock::new(); + CFG.get_or_init(|| { + let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1"); + let on = asked && guest_write::enabled(); + if asked && !on { + crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + } + let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096); + let window = (kb * 1024).next_power_of_two().min(4 << 20); + let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20; + let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1); + let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600); + if on { + crate::xlog_info!( + "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)", + window >> 10, + gap >> 20 + ); + } + Cfg { on, window, gap, hot_streak, hot_hold } + }) +} + +pub fn on() -> bool { + cfg().on +} + +fn in_imported_uma(a: usize, n: usize) -> bool { + crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n)) +} + +struct Cold { + end: usize, + parts: Vec<(usize, usize, u32)>, +} + +struct Opened { + e: [(usize, usize, usize, u64); 1024], + n: usize, +} +impl Opened { + const fn new() -> Self { + Self { e: [(0, 0, 0, 0); 1024], n: 0 } + } +} + +#[derive(Default)] +struct Heat { + last_frame: u64, + streak: u8, + hot_until: u64, +} +impl Heat { + fn fault(&mut self, f: u64, streak_at: u8, hold: u64) { + if f == self.last_frame { + return; + } + self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) { + self.streak.saturating_add(1) + } else { + 1 + }; + self.last_frame = f; + if self.streak >= streak_at && hold > 0 { + self.hot_until = self.hot_until.max(f.saturating_add(hold)); + self.streak = 0; + } + } + fn hot(&self, f: u64) -> bool { + f < self.hot_until + } +} + +#[derive(Default)] +struct Looks { + clean: HashMap<(usize, usize), u8>, + registered: Vec<(usize, usize)>, + ranges: Option<Arc<Vec<(usize, usize)>>>, + cold_gen: u64, + pieces: Vec<(usize, usize)>, +} + +static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new()); +static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); +static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new()); +static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); +static OPENED: Mutex<Opened> = Mutex::new(Opened::new()); +static HANDLING: AtomicUsize = AtomicUsize::new(0); +static FREEZE_AT: AtomicUsize = AtomicUsize::new(0); +static FREEZE_END: AtomicUsize = AtomicUsize::new(0); +static COLD_GEN: AtomicU64 = AtomicU64::new(0); +static LOOKS: Mutex<Option<Looks>> = Mutex::new(None); +static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None); +static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new()); +static HANDLER: Once = Once::new(); +static ACTIVE: AtomicBool = AtomicBool::new(false); + +fn frame() -> u64 { + super::present::activity().0.max(1) +} + +fn read_only(p: u32) -> u32 { + let m = p & MODIFIERS; + match p & !MODIFIERS { + PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m, + _ => PAGE_READONLY | m, + } +} + +fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> { + parts.iter().filter_map(|&(a, n, p)| { + let (s, e) = (a.max(lo), (a + n).min(hi)); + (s < e).then_some((s, e - s, p)) + }).collect() +} + +unsafe fn thaw(parts: &[(usize, usize, u32)]) { + for &(a, n, p) in parts { + let mut at = a; + let end = a + n; + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 { + break; + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end); + if next <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == read_only(p) { + let mut old = 0; + let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old); + } + at = next; + } + } +} + +fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + let c = cold.remove(&s).unwrap(); + if s < lo { + cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) }); + } + if hi < c.end { + cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) }); + } + } +} + +unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) { + let end = a.saturating_add(n); + let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + if let Some(c) = cold.remove(&s) { + thaw(&c.parts); + } + } +} + +unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> { + let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?; + if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) { + return None; + } + let end = cold[&s].end; + let w = at & !(window - 1); + let w_end = w.saturating_add(window); + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa); + let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) }; + let open: Vec<(usize, usize, u32)> = if multi { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k); + cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect() + } else { + clip(&cold[&s].parts, lo, hi) + }; + thaw(&open); + carve(cold, lo, hi); + Some((lo, hi)) +} + +fn apply_faults() { + let opened: Vec<(usize, usize, usize, u64)> = { + let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + let n = std::mem::take(&mut r.n); + r.e[..n].to_vec() + }; + if opened.is_empty() { + return; + } + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + for &(lo, hi, _, _) in &opened { + carve(&mut cold, lo, hi); + } + } + { + let c = cfg(); + let mut heat = HEAT.lock().unwrap_or_else(|e| e.into_inner()); + for &(_, _, at, f) in &opened { + heat.entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + } + } + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(_, _, at, _)| at & !(PAGE - 1))); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(lo, hi, _, _)| (lo, hi))); +} + +fn was_ours(at: usize) -> bool { + EVER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|e| e.contains(&(at & !(BLOCK - 1)))) +} + +unsafe fn fault(at: usize, window: usize) -> bool { + let f = frame(); + let mut open = [(0usize, 0usize, 0u32); WINDOW_PARTS]; + let mut k = 0; + let (lo, hi); + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let found = cold.range(..=at).next_back().filter(|(_, c)| at < c.end && c.parts.iter().any(|&(a, n, _)| a <= at && at < a + n)); + let Some((&s, c)) = found else { + drop(cold); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 + && m.State == MEM_COMMIT + && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE); + return now && was_ours(at); + }; + let c_end = c.end; + let w = at & !(window - 1); + let w_end = w.saturating_add(window); + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa); + (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(c_end)) }; + let mut over = false; + let mut push_parts = |parts: &[(usize, usize, u32)]| -> bool { + for &(a, n, p) in parts { + let (ps, pe) = (a.max(lo), (a + n).min(hi)); + if ps < pe { + if k == WINDOW_PARTS { + return true; + } + open[k] = (ps, pe - ps, p); + k += 1; + } + } + false + }; + if multi { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&b, _)| b); + for (_, span) in cold.range(from..hi) { + if push_parts(&span.parts) { + over = true; + break; + } + } + } else { + over = push_parts(&c.parts); + } + if over { + let Some((lo, hi)) = open_window(&mut cold, at, window) else { return false }; + drop(cold); + let c = cfg(); + HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1)); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi)); + return true; + } + HANDLING.fetch_add(1, Ordering::AcqRel); + } + thaw(&open[..k]); + HANDLING.fetch_sub(1, Ordering::AcqRel); + let mut ring = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + if ring.n < ring.e.len() { + let i = ring.n; + ring.e[i] = (lo, hi, at, f); + ring.n += 1; + return true; + } + drop(ring); + carve(&mut COLD.lock().unwrap_or_else(|e| e.into_inner()), lo, hi); + let c = cfg(); + HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1)); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi)); + true +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1 { + if fault(r.ExceptionInformation[1], cfg().window) { + return -1; + } + } + 0 +} + +fn install() { + HANDLER.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +fn pin(a: usize, n: usize, d: isize) { + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n)); + while b < end { + if d > 0 { + *g.entry(b).or_default() += 1; + } else if let Some(c) = g.get_mut(&b) { + *c -= 1; + if *c == 0 { + g.remove(&b); + } + } + let Some(next) = b.checked_add(BLOCK) else { break }; + b = next; + } +} + +fn pinned(a: usize, n: usize) -> bool { + let g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n)); + while b < end { + if g.contains_key(&b) { + return true; + } + let Some(next) = b.checked_add(BLOCK) else { break }; + b = next; + } + false +} + +unsafe fn changed_now(a: usize, n: usize) { + if n == 0 || !ACTIVE.load(Ordering::Acquire) { + return; + } + apply_faults(); + let end = a.saturating_add(n); + loop { + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let fe = FREEZE_END.load(Ordering::Acquire); + if fe == 0 || FREEZE_AT.load(Ordering::Acquire) >= end || a >= fe { + thaw_range(&mut cold, a, n); + break; + } + } + std::thread::yield_now(); + } + while HANDLING.load(Ordering::Acquire) != 0 { + std::thread::yield_now(); + } +} + +pub struct Guard(usize, usize); +impl Drop for Guard { + fn drop(&mut self) { + if self.1 != 0 { + pin(self.0, self.1, -1); + } + } +} + +pub unsafe fn guard(a: usize, n: usize) -> Guard { + if n == 0 || !on() { + return Guard(0, 0); + } + pin(a, n, 1); + changed_now(a, n); + Guard(a, n) +} + +pub unsafe fn guard_free(a: usize, n: usize) -> Guard { + if a == 0 || !on() { + return Guard(0, 0); + } + let len = if n != 0 { + n + } else { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 { ~~~~ --- **High**: For `guard_free(a, 0)` the length comes from VirtualQuery's RegionSize at `a`, which covers only the first region with uniform attributes, and freezing itself splits allocations into read-only and read-write regions. If the title calls VirtualFree(base, 0, MEM_RELEASE) on a 64 MiB allocation whose second block is frozen, RegionSize at base stops at the first protection change (e.g. 2 MiB), so `changed_now` and `thaw_range` clear only that part, and the cold spans after it stay in COLD after release. If the address is reused for a new watched allocation, `hot_pieces` keeps leaving those stale spans out of the GetWriteWatch scan, so CPU writes there never reach the GPU, and `fault` can make a page the title marked PAGE_READONLY on purpose writable. Walking regions with the same AllocationBase to get the whole allocation would fix it.
bmjask commented 2026-12-02 17:36:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:36:28Z.

Code review location: crates/xcl/src/hle/d3d12x/watch_cold.rs; line 456

@@ -0,0 +1,702 @@
+//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory
+//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans.
+//!
+//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default
+//!   2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path.
+//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB`
+//!   (default 4 MiB) are coalesced into one `GetWriteWatch` call.
+//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped
+//!   upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87.
+//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and
+//!   against title commits/decommits/protects via `guard` / `guard_free` / `changed`.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex, Once, OnceLock};
+
+use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
+use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS};
+use windows_sys::Win32::System::Memory::{
+    VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ,
+    PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE,
+};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+const BLOCK: usize = 2 << 20;
+const FREEZE_AFTER: u8 = 4;
+const FREEZE_PER_LOOK: usize = 64;
+const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE;
+const WINDOW_PARTS: usize = 8;
+
+struct Cfg {
+    on: bool,
+    window: usize,
+    gap: usize,
+    hot_streak: u8,
+    hot_hold: u64,
+}
+
+fn env_num(name: &str, default: u64) -> u64 {
+    std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default)
+}
+
+fn cfg() -> &'static Cfg {
+    static CFG: OnceLock<Cfg> = OnceLock::new();
+    CFG.get_or_init(|| {
+        let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1");
+        let on = asked && guest_write::enabled();
+        if asked && !on {
+            crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+        }
+        let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096);
+        let window = (kb * 1024).next_power_of_two().min(4 << 20);
+        let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20;
+        let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1);
+        let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600);
+        if on {
+            crate::xlog_info!(
+                "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)",
+                window >> 10,
+                gap >> 20
+            );
+        }
+        Cfg { on, window, gap, hot_streak, hot_hold }
+    })
+}
+
+pub fn on() -> bool {
+    cfg().on
+}
+
+fn in_imported_uma(a: usize, n: usize) -> bool {
+    crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n))
+}
+
+struct Cold {
+    end: usize,
+    parts: Vec<(usize, usize, u32)>,
+}
+
+struct Opened {
+    e: [(usize, usize, usize, u64); 1024],
+    n: usize,
+}
+impl Opened {
+    const fn new() -> Self {
+        Self { e: [(0, 0, 0, 0); 1024], n: 0 }
+    }
+}
+
+#[derive(Default)]
+struct Heat {
+    last_frame: u64,
+    streak: u8,
+    hot_until: u64,
+}
+impl Heat {
+    fn fault(&mut self, f: u64, streak_at: u8, hold: u64) {
+        if f == self.last_frame {
+            return;
+        }
+        self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) {
+            self.streak.saturating_add(1)
+        } else {
+            1
+        };
+        self.last_frame = f;
+        if self.streak >= streak_at && hold > 0 {
+            self.hot_until = self.hot_until.max(f.saturating_add(hold));
+            self.streak = 0;
+        }
+    }
+    fn hot(&self, f: u64) -> bool {
+        f < self.hot_until
+    }
+}
+
+#[derive(Default)]
+struct Looks {
+    clean: HashMap<(usize, usize), u8>,
+    registered: Vec<(usize, usize)>,
+    ranges: Option<Arc<Vec<(usize, usize)>>>,
+    cold_gen: u64,
+    pieces: Vec<(usize, usize)>,
+}
+
+static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new());
+static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new());
+static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new());
+static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
+static OPENED: Mutex<Opened> = Mutex::new(Opened::new());
+static HANDLING: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_AT: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_END: AtomicUsize = AtomicUsize::new(0);
+static COLD_GEN: AtomicU64 = AtomicU64::new(0);
+static LOOKS: Mutex<Option<Looks>> = Mutex::new(None);
+static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
+static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new());
+static HANDLER: Once = Once::new();
+static ACTIVE: AtomicBool = AtomicBool::new(false);
+
+fn frame() -> u64 {
+    super::present::activity().0.max(1)
+}
+
+fn read_only(p: u32) -> u32 {
+    let m = p & MODIFIERS;
+    match p & !MODIFIERS {
+        PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m,
+        _ => PAGE_READONLY | m,
+    }
+}
+
+fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> {
+    parts.iter().filter_map(|&(a, n, p)| {
+        let (s, e) = (a.max(lo), (a + n).min(hi));
+        (s < e).then_some((s, e - s, p))
+    }).collect()
+}
+
+unsafe fn thaw(parts: &[(usize, usize, u32)]) {
+    for &(a, n, p) in parts {
+        let mut at = a;
+        let end = a + n;
+        while at < end {
+            let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 {
+                break;
+            }
+            let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end);
+            if next <= at {
+                break;
+            }
+            if m.State == MEM_COMMIT && m.Protect == read_only(p) {
+                let mut old = 0;
+                let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old);
+            }
+            at = next;
+        }
+    }
+}
+
+fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) {
+    let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        let c = cold.remove(&s).unwrap();
+        if s < lo {
+            cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) });
+        }
+        if hi < c.end {
+            cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) });
+        }
+    }
+}
+
+unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) {
+    let end = a.saturating_add(n);
+    let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s);
+    let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect();
+    if !hit.is_empty() {
+        COLD_GEN.fetch_add(1, Ordering::AcqRel);
+    }
+    for s in hit {
+        if let Some(c) = cold.remove(&s) {
+            thaw(&c.parts);
+        }
+    }
+}
+
+unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> {
+    let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?;
+    if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) {
+        return None;
+    }
+    let end = cold[&s].end;
+    let w = at & !(window - 1);
+    let w_end = w.saturating_add(window);
+    let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+    let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa);
+    let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) };
+    let open: Vec<(usize, usize, u32)> = if multi {
+        let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k);
+        cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect()
+    } else {
+        clip(&cold[&s].parts, lo, hi)
+    };
+    thaw(&open);
+    carve(cold, lo, hi);
+    Some((lo, hi))
+}
+
+fn apply_faults() {
+    let opened: Vec<(usize, usize, usize, u64)> = {
+        let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner());
+        let n = std::mem::take(&mut r.n);
+        r.e[..n].to_vec()
+    };
+    if opened.is_empty() {
+        return;
+    }
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        for &(lo, hi, _, _) in &opened {
+            carve(&mut cold, lo, hi);
+        }
+    }
+    {
+        let c = cfg();
+        let mut heat = HEAT.lock().unwrap_or_else(|e| e.into_inner());
+        for &(_, _, at, f) in &opened {
+            heat.entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+        }
+    }
+    FAULTED.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(_, _, at, _)| at & !(PAGE - 1)));
+    OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(lo, hi, _, _)| (lo, hi)));
+}
+
+fn was_ours(at: usize) -> bool {
+    EVER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|e| e.contains(&(at & !(BLOCK - 1))))
+}
+
+unsafe fn fault(at: usize, window: usize) -> bool {
+    let f = frame();
+    let mut open = [(0usize, 0usize, 0u32); WINDOW_PARTS];
+    let mut k = 0;
+    let (lo, hi);
+    {
+        let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+        let found = cold.range(..=at).next_back().filter(|(_, c)| at < c.end && c.parts.iter().any(|&(a, n, _)| a <= at && at < a + n));
+        let Some((&s, c)) = found else {
+            drop(cold);
+            let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+            let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0
+                && m.State == MEM_COMMIT
+                && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE);
+            return now && was_ours(at);
+        };
+        let c_end = c.end;
+        let w = at & !(window - 1);
+        let w_end = w.saturating_add(window);
+        let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+        let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa);
+        (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(c_end)) };
+        let mut over = false;
+        let mut push_parts = |parts: &[(usize, usize, u32)]| -> bool {
+            for &(a, n, p) in parts {
+                let (ps, pe) = (a.max(lo), (a + n).min(hi));
+                if ps < pe {
+                    if k == WINDOW_PARTS {
+                        return true;
+                    }
+                    open[k] = (ps, pe - ps, p);
+                    k += 1;
+                }
+            }
+            false
+        };
+        if multi {
+            let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&b, _)| b);
+            for (_, span) in cold.range(from..hi) {
+                if push_parts(&span.parts) {
+                    over = true;
+                    break;
+                }
+            }
+        } else {
+            over = push_parts(&c.parts);
+        }
+        if over {
+            let Some((lo, hi)) = open_window(&mut cold, at, window) else { return false };
+            drop(cold);
+            let c = cfg();
+            HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+            FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1));
+            OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi));
+            return true;
+        }
+        HANDLING.fetch_add(1, Ordering::AcqRel);
+    }
+    thaw(&open[..k]);
+    HANDLING.fetch_sub(1, Ordering::AcqRel);
+    let mut ring = OPENED.lock().unwrap_or_else(|e| e.into_inner());
+    if ring.n < ring.e.len() {
+        let i = ring.n;
+        ring.e[i] = (lo, hi, at, f);
+        ring.n += 1;
+        return true;
+    }
+    drop(ring);
+    carve(&mut COLD.lock().unwrap_or_else(|e| e.into_inner()), lo, hi);
+    let c = cfg();
+    HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold);
+    FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1));
+    OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi));
+    true
+}
+
+unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
+    let r = &*(*info).ExceptionRecord;
+    if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1 {
+        if fault(r.ExceptionInformation[1], cfg().window) {
+            return -1;
+        }
+    }
+    0
+}
+
+fn install() {
+    HANDLER.call_once(|| unsafe {
+        AddVectoredExceptionHandler(1, Some(handler));
+    });
+}
+
+fn pin(a: usize, n: usize, d: isize) {
+    let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+    let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n));
+    while b < end {
+        if d > 0 {
+            *g.entry(b).or_default() += 1;
+        } else if let Some(c) = g.get_mut(&b) {
+            *c -= 1;
+            if *c == 0 {
+                g.remove(&b);
+            }
+        }
+        let Some(next) = b.checked_add(BLOCK) else { break };
+        b = next;
+    }
+}
+
+fn pinned(a: usize, n: usize) -> bool {
+    let g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+    let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n));
+    while b < end {
+        if g.contains_key(&b) {
+            return true;
+        }
+        let Some(next) = b.checked_add(BLOCK) else { break };
+        b = next;
+    }
+    false
+}
+
+unsafe fn changed_now(a: usize, n: usize) {
+    if n == 0 || !ACTIVE.load(Ordering::Acquire) {
+        return;
+    }
+    apply_faults();
+    let end = a.saturating_add(n);
+    loop {
+        {
+            let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner());
+            let fe = FREEZE_END.load(Ordering::Acquire);
+            if fe == 0 || FREEZE_AT.load(Ordering::Acquire) >= end || a >= fe {
+                thaw_range(&mut cold, a, n);
+                break;
+            }
+        }
+        std::thread::yield_now();
+    }
+    while HANDLING.load(Ordering::Acquire) != 0 {
+        std::thread::yield_now();
+    }
+}
+
+pub struct Guard(usize, usize);
+impl Drop for Guard {
+    fn drop(&mut self) {
+        if self.1 != 0 {
+            pin(self.0, self.1, -1);
+        }
+    }
+}
+
+pub unsafe fn guard(a: usize, n: usize) -> Guard {
+    if n == 0 || !on() {
+        return Guard(0, 0);
+    }
+    pin(a, n, 1);
+    changed_now(a, n);
+    Guard(a, n)
+}
+
+pub unsafe fn guard_free(a: usize, n: usize) -> Guard {
+    if a == 0 || !on() {
+        return Guard(0, 0);
+    }
+    let len = if n != 0 {
+        n
+    } else {
+        let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
+        if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 {
+            m.RegionSize
+        } else {
+            0
+        }
+    };
+    guard(a, len)
+}
+
+pub unsafe fn changed(a: usize, n: usize) {
+    if on() {
+        changed_now(a, n);
+    }
+}
+
+/// Freeze `[a, a + n)` read-only if all committed parts are read-write, unpinned, and outside
+/// guarded views / imported coherent UMA. Calls `take_after` after protecting so writes racing
+/// with `VirtualProtect` are never lost.
+unsafe fn freeze(a: usize, n: usize, mut take_after: impl FnMut(usize, usize)) -> bool {

Medium: look_with and freeze never check on() or guest_write::enabled(), while guard, guard_free and changed do nothing when the switch is off. If the follow-up wiring calls look_with without the on() gate (it's pub), or XCL_WATCH_COLD=1 is set without XCL_GUEST_WRITE_GUARD=1, pages are still frozen read-only. Then title decommits and protects skip changed_now because on() is false, and guest_write's open doesn't touch pages, so kernel reads into frozen memory fail with ERROR_NOACCESS and frozen state outlives decommit. Returning early from look_with/freeze unless both switches are on would make the module safe to wire up.

<!-- greyfinch-sync:ivall/xcl:review-comment:4773491509 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#discussion_r4773491509). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:36:28Z. **Code review location:** `crates/xcl/src/hle/d3d12x/watch_cold.rs`; line 456 ~~~~diff @@ -0,0 +1,702 @@ +//! `XCL_WATCH_COLD=1` (default off; requires `XCL_GUEST_WRITE_GUARD=1`): cold watched title memory +//! is made `PAGE_READONLY` and excluded from per-submit `GetWriteWatch` scans. +//! +//! - A write fault opens an aligned window (`XCL_WATCH_COLD_WINDOW_KB`, 4..=4096 KiB, default +//! 2048 KiB) via a fixed ring so the VEH handler does not allocate on the common path. +//! - Nearby taken pieces within one watched range separated by up to `XCL_WATCH_COLD_GAP_MB` +//! (default 4 MiB) are coalesced into one `GetWriteWatch` call. +//! - Imported coherent UMA windows (`!uma.shadowed() && uma.in_committed_window`) are skipped +//! upfront in O(1) because `dxgkrnl` rejects `PAGE_READONLY` with error 87. +//! - Page protection is serialized against kernel writes via `guest_write::while_unpinned`, and +//! against title commits/decommits/protects via `guard` / `guard_free` / `changed`. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, Once, OnceLock}; + +use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS}; +use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, EXCEPTION_POINTERS}; +use windows_sys::Win32::System::Memory::{ + VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, + PAGE_EXECUTE_READWRITE, PAGE_NOCACHE, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOMBINE, +}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; +const BLOCK: usize = 2 << 20; +const FREEZE_AFTER: u8 = 4; +const FREEZE_PER_LOOK: usize = 64; +const MODIFIERS: u32 = PAGE_NOCACHE | PAGE_WRITECOMBINE; +const WINDOW_PARTS: usize = 8; + +struct Cfg { + on: bool, + window: usize, + gap: usize, + hot_streak: u8, + hot_hold: u64, +} + +fn env_num(name: &str, default: u64) -> u64 { + std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default) +} + +fn cfg() -> &'static Cfg { + static CFG: OnceLock<Cfg> = OnceLock::new(); + CFG.get_or_init(|| { + let asked = std::env::var("XCL_WATCH_COLD").is_ok_and(|v| v.trim() == "1"); + let on = asked && guest_write::enabled(); + if asked && !on { + crate::xlog_warn!("XCL_WATCH_COLD=1 ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + } + let kb = (env_num("XCL_WATCH_COLD_WINDOW_KB", 2048) as usize).clamp(4, 4096); + let window = (kb * 1024).next_power_of_two().min(4 << 20); + let gap = (env_num("XCL_WATCH_COLD_GAP_MB", 4) as usize).min(64) << 20; + let hot_streak = (env_num("XCL_WATCH_COLD_HOT_STREAK", 3) as u8).max(1); + let hot_hold = env_num("XCL_WATCH_COLD_HOT_HOLD", 600); + if on { + crate::xlog_info!( + "D3D12.X: XCL_WATCH_COLD=1 – cold memory read-only ({} KiB window, {} MiB gap, hot {hot_streak}f/{hot_hold}f)", + window >> 10, + gap >> 20 + ); + } + Cfg { on, window, gap, hot_streak, hot_hold } + }) +} + +pub fn on() -> bool { + cfg().on +} + +fn in_imported_uma(a: usize, n: usize) -> bool { + crate::gpu::uma::get().is_some_and(|u| !u.shadowed() && u.in_committed_window(a, n)) +} + +struct Cold { + end: usize, + parts: Vec<(usize, usize, u32)>, +} + +struct Opened { + e: [(usize, usize, usize, u64); 1024], + n: usize, +} +impl Opened { + const fn new() -> Self { + Self { e: [(0, 0, 0, 0); 1024], n: 0 } + } +} + +#[derive(Default)] +struct Heat { + last_frame: u64, + streak: u8, + hot_until: u64, +} +impl Heat { + fn fault(&mut self, f: u64, streak_at: u8, hold: u64) { + if f == self.last_frame { + return; + } + self.streak = if self.last_frame != 0 && f <= self.last_frame.saturating_add(1) { + self.streak.saturating_add(1) + } else { + 1 + }; + self.last_frame = f; + if self.streak >= streak_at && hold > 0 { + self.hot_until = self.hot_until.max(f.saturating_add(hold)); + self.streak = 0; + } + } + fn hot(&self, f: u64) -> bool { + f < self.hot_until + } +} + +#[derive(Default)] +struct Looks { + clean: HashMap<(usize, usize), u8>, + registered: Vec<(usize, usize)>, + ranges: Option<Arc<Vec<(usize, usize)>>>, + cold_gen: u64, + pieces: Vec<(usize, usize)>, +} + +static COLD: Mutex<BTreeMap<usize, Cold>> = Mutex::new(BTreeMap::new()); +static PINS: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); +static FAULTED: Mutex<Vec<usize>> = Mutex::new(Vec::new()); +static OPENED_RANGES: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new()); +static OPENED: Mutex<Opened> = Mutex::new(Opened::new()); +static HANDLING: AtomicUsize = AtomicUsize::new(0); +static FREEZE_AT: AtomicUsize = AtomicUsize::new(0); +static FREEZE_END: AtomicUsize = AtomicUsize::new(0); +static COLD_GEN: AtomicU64 = AtomicU64::new(0); +static LOOKS: Mutex<Option<Looks>> = Mutex::new(None); +static EVER: Mutex<Option<HashSet<usize>>> = Mutex::new(None); +static HEAT: Mutex<BTreeMap<usize, Heat>> = Mutex::new(BTreeMap::new()); +static HANDLER: Once = Once::new(); +static ACTIVE: AtomicBool = AtomicBool::new(false); + +fn frame() -> u64 { + super::present::activity().0.max(1) +} + +fn read_only(p: u32) -> u32 { + let m = p & MODIFIERS; + match p & !MODIFIERS { + PAGE_EXECUTE_READWRITE => PAGE_EXECUTE_READ | m, + _ => PAGE_READONLY | m, + } +} + +fn clip(parts: &[(usize, usize, u32)], lo: usize, hi: usize) -> Vec<(usize, usize, u32)> { + parts.iter().filter_map(|&(a, n, p)| { + let (s, e) = (a.max(lo), (a + n).min(hi)); + (s < e).then_some((s, e - s, p)) + }).collect() +} + +unsafe fn thaw(parts: &[(usize, usize, u32)]) { + for &(a, n, p) in parts { + let mut at = a; + let end = a + n; + while at < end { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) == 0 || m.RegionSize == 0 { + break; + } + let next = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(end); + if next <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == read_only(p) { + let mut old = 0; + let _ = VirtualProtect(at as *const c_void, next - at, p, &mut old); + } + at = next; + } + } +} + +fn carve(cold: &mut BTreeMap<usize, Cold>, lo: usize, hi: usize) { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..hi).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + let c = cold.remove(&s).unwrap(); + if s < lo { + cold.insert(s, Cold { end: lo, parts: clip(&c.parts, s, lo) }); + } + if hi < c.end { + cold.insert(hi, Cold { end: c.end, parts: clip(&c.parts, hi, c.end) }); + } + } +} + +unsafe fn thaw_range(cold: &mut BTreeMap<usize, Cold>, a: usize, n: usize) { + let end = a.saturating_add(n); + let from = cold.range(..=a).next_back().filter(|(_, c)| c.end > a).map_or(a, |(&s, _)| s); + let hit: Vec<usize> = cold.range(from..end).map(|(&s, _)| s).collect(); + if !hit.is_empty() { + COLD_GEN.fetch_add(1, Ordering::AcqRel); + } + for s in hit { + if let Some(c) = cold.remove(&s) { + thaw(&c.parts); + } + } +} + +unsafe fn open_window(cold: &mut BTreeMap<usize, Cold>, at: usize, window: usize) -> Option<(usize, usize)> { + let s = cold.range(..=at).next_back().filter(|(_, c)| at < c.end).map(|(&s, _)| s)?; + if !cold[&s].parts.iter().any(|&(a, n, _)| a <= at && at < a + n) { + return None; + } + let end = cold[&s].end; + let w = at & !(window - 1); + let w_end = w.saturating_add(window); + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa); + let (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(end)) }; + let open: Vec<(usize, usize, u32)> = if multi { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&k, _)| k); + cold.range(from..hi).flat_map(|(_, c)| clip(&c.parts, lo, hi)).collect() + } else { + clip(&cold[&s].parts, lo, hi) + }; + thaw(&open); + carve(cold, lo, hi); + Some((lo, hi)) +} + +fn apply_faults() { + let opened: Vec<(usize, usize, usize, u64)> = { + let mut r = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + let n = std::mem::take(&mut r.n); + r.e[..n].to_vec() + }; + if opened.is_empty() { + return; + } + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + for &(lo, hi, _, _) in &opened { + carve(&mut cold, lo, hi); + } + } + { + let c = cfg(); + let mut heat = HEAT.lock().unwrap_or_else(|e| e.into_inner()); + for &(_, _, at, f) in &opened { + heat.entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + } + } + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(_, _, at, _)| at & !(PAGE - 1))); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).extend(opened.iter().map(|&(lo, hi, _, _)| (lo, hi))); +} + +fn was_ours(at: usize) -> bool { + EVER.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|e| e.contains(&(at & !(BLOCK - 1)))) +} + +unsafe fn fault(at: usize, window: usize) -> bool { + let f = frame(); + let mut open = [(0usize, 0usize, 0u32); WINDOW_PARTS]; + let mut k = 0; + let (lo, hi); + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let found = cold.range(..=at).next_back().filter(|(_, c)| at < c.end && c.parts.iter().any(|&(a, n, _)| a <= at && at < a + n)); + let Some((&s, c)) = found else { + drop(cold); + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + let now = VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 + && m.State == MEM_COMMIT + && matches!(m.Protect & !MODIFIERS, PAGE_READWRITE | PAGE_EXECUTE_READWRITE); + return now && was_ours(at); + }; + let c_end = c.end; + let w = at & !(window - 1); + let w_end = w.saturating_add(window); + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + let multi = window >= BLOCK && (fe == 0 || fe <= w || w_end <= fa); + (lo, hi) = if multi { (w, w_end) } else { (w.max(s), w_end.min(c_end)) }; + let mut over = false; + let mut push_parts = |parts: &[(usize, usize, u32)]| -> bool { + for &(a, n, p) in parts { + let (ps, pe) = (a.max(lo), (a + n).min(hi)); + if ps < pe { + if k == WINDOW_PARTS { + return true; + } + open[k] = (ps, pe - ps, p); + k += 1; + } + } + false + }; + if multi { + let from = cold.range(..=lo).next_back().filter(|(_, c)| c.end > lo).map_or(lo, |(&b, _)| b); + for (_, span) in cold.range(from..hi) { + if push_parts(&span.parts) { + over = true; + break; + } + } + } else { + over = push_parts(&c.parts); + } + if over { + let Some((lo, hi)) = open_window(&mut cold, at, window) else { return false }; + drop(cold); + let c = cfg(); + HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1)); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi)); + return true; + } + HANDLING.fetch_add(1, Ordering::AcqRel); + } + thaw(&open[..k]); + HANDLING.fetch_sub(1, Ordering::AcqRel); + let mut ring = OPENED.lock().unwrap_or_else(|e| e.into_inner()); + if ring.n < ring.e.len() { + let i = ring.n; + ring.e[i] = (lo, hi, at, f); + ring.n += 1; + return true; + } + drop(ring); + carve(&mut COLD.lock().unwrap_or_else(|e| e.into_inner()), lo, hi); + let c = cfg(); + HEAT.lock().unwrap_or_else(|e| e.into_inner()).entry(at & !(BLOCK - 1)).or_default().fault(f, c.hot_streak, c.hot_hold); + FAULTED.lock().unwrap_or_else(|e| e.into_inner()).push(at & !(PAGE - 1)); + OPENED_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((lo, hi)); + true +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + let r = &*(*info).ExceptionRecord; + if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS && r.NumberParameters >= 2 && r.ExceptionInformation[0] == 1 { + if fault(r.ExceptionInformation[1], cfg().window) { + return -1; + } + } + 0 +} + +fn install() { + HANDLER.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +fn pin(a: usize, n: usize, d: isize) { + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n)); + while b < end { + if d > 0 { + *g.entry(b).or_default() += 1; + } else if let Some(c) = g.get_mut(&b) { + *c -= 1; + if *c == 0 { + g.remove(&b); + } + } + let Some(next) = b.checked_add(BLOCK) else { break }; + b = next; + } +} + +fn pinned(a: usize, n: usize) -> bool { + let g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let (mut b, end) = (a & !(BLOCK - 1), a.saturating_add(n)); + while b < end { + if g.contains_key(&b) { + return true; + } + let Some(next) = b.checked_add(BLOCK) else { break }; + b = next; + } + false +} + +unsafe fn changed_now(a: usize, n: usize) { + if n == 0 || !ACTIVE.load(Ordering::Acquire) { + return; + } + apply_faults(); + let end = a.saturating_add(n); + loop { + { + let mut cold = COLD.lock().unwrap_or_else(|e| e.into_inner()); + let fe = FREEZE_END.load(Ordering::Acquire); + if fe == 0 || FREEZE_AT.load(Ordering::Acquire) >= end || a >= fe { + thaw_range(&mut cold, a, n); + break; + } + } + std::thread::yield_now(); + } + while HANDLING.load(Ordering::Acquire) != 0 { + std::thread::yield_now(); + } +} + +pub struct Guard(usize, usize); +impl Drop for Guard { + fn drop(&mut self) { + if self.1 != 0 { + pin(self.0, self.1, -1); + } + } +} + +pub unsafe fn guard(a: usize, n: usize) -> Guard { + if n == 0 || !on() { + return Guard(0, 0); + } + pin(a, n, 1); + changed_now(a, n); + Guard(a, n) +} + +pub unsafe fn guard_free(a: usize, n: usize) -> Guard { + if a == 0 || !on() { + return Guard(0, 0); + } + let len = if n != 0 { + n + } else { + let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(a as *const c_void, &mut m, std::mem::size_of_val(&m)) != 0 { + m.RegionSize + } else { + 0 + } + }; + guard(a, len) +} + +pub unsafe fn changed(a: usize, n: usize) { + if on() { + changed_now(a, n); + } +} + +/// Freeze `[a, a + n)` read-only if all committed parts are read-write, unpinned, and outside +/// guarded views / imported coherent UMA. Calls `take_after` after protecting so writes racing +/// with `VirtualProtect` are never lost. +unsafe fn freeze(a: usize, n: usize, mut take_after: impl FnMut(usize, usize)) -> bool { ~~~~ --- **Medium**: `look_with` and `freeze` never check `on()` or `guest_write::enabled()`, while `guard`, `guard_free` and `changed` do nothing when the switch is off. If the follow-up wiring calls `look_with` without the `on()` gate (it's `pub`), or XCL_WATCH_COLD=1 is set without XCL_GUEST_WRITE_GUARD=1, pages are still frozen read-only. Then title decommits and protects skip `changed_now` because `on()` is false, and guest_write's `open` doesn't touch pages, so kernel reads into frozen memory fail with ERROR_NOACCESS and frozen state outlives decommit. Returning early from `look_with`/`freeze` unless both switches are on would make the module safe to wire up.
bmjask commented 2026-12-02 17:36:28 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:36:28Z.

Review: COMMENTED


Review of a2a329de: 5 finding(s) (2 critical, 2 high, 1 medium), most severe first.

  1. Critical crates/xcl/src/hle/d3d12x/watch_cold.rs:250: apply_faults carves queued fault windows out of COLD without thawing them, so any span freeze added inside that window after the fault was queued is dropped while its pages are still PAGE_READONLY. (inline)
  2. Critical crates/xcl/src/hle/d3d12x/watch_cold.rs:326: A fault during freeze's VirtualProtect loop over a multi-part span thaws only the parts already protected; the loop then protects the rest, and the queued window later removes the whole span from COLD. (inline)
  3. High crates/xcl/src/hle/d3d12x/watch_cold.rs:572: When the watched ranges change, look_with unregisters the old ranges from guest_write but doesn't thaw cold spans inside ranges that were dropped. (inline)
  4. High crates/xcl/src/hle/d3d12x/watch_cold.rs:438: For guard_free(a, 0) the length comes from VirtualQuery's RegionSize at a, which covers only the first region with uniform attributes, and freezing itself splits allocations into read-only and read-write regions. (inline)
  5. Medium crates/xcl/src/hle/d3d12x/watch_cold.rs:456: look_with and freeze never check on() or guest_write::enabled(), while guard, guard_free and changed do nothing when the switch is off. (inline)

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

<!-- greyfinch-sync:ivall/xcl:review:6155873335 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#pullrequestreview-6155873335). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:36:28Z. **Review:** COMMENTED --- Review of `a2a329de`: 5 finding(s) (2 critical, 2 high, 1 medium), most severe first. 1. **Critical** `crates/xcl/src/hle/d3d12x/watch_cold.rs:250`: `apply_faults` carves queued fault windows out of COLD without thawing them, so any span `freeze` added inside that window after the fault was queued is dropped while its pages are still PAGE_READONLY. (inline) 2. **Critical** `crates/xcl/src/hle/d3d12x/watch_cold.rs:326`: A fault during `freeze`'s VirtualProtect loop over a multi-part span thaws only the parts already protected; the loop then protects the rest, and the queued window later removes the whole span from COLD. (inline) 3. **High** `crates/xcl/src/hle/d3d12x/watch_cold.rs:572`: When the watched ranges change, `look_with` unregisters the old ranges from guest_write but doesn't thaw cold spans inside ranges that were dropped. (inline) 4. **High** `crates/xcl/src/hle/d3d12x/watch_cold.rs:438`: For `guard_free(a, 0)` the length comes from VirtualQuery's RegionSize at `a`, which covers only the first region with uniform attributes, and freezing itself splits allocations into read-only and read-write regions. (inline) 5. **Medium** `crates/xcl/src/hle/d3d12x/watch_cold.rs:456`: `look_with` and `freeze` never check `on()` or `guest_write::enabled()`, while `guard`, `guard_free` and `changed` do nothing when the switch is off. (inline) --- _These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it._
bmjask commented 2026-12-02 17:36:30 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T17:36:30Z.


@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.

<!-- greyfinch-sync:ivall/xcl:comment:7353470559 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3639#issuecomment-7353470559). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T17:36:30Z. --- @Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
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/3639:upstream-pr/3639'
git switch 'upstream-pr/3639'

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 'amd-dev'
git merge --no-ff 'upstream-pr/3639'
git switch 'upstream-pr/3639'
git rebase 'amd-dev'
git switch 'amd-dev'
git merge --ff-only 'upstream-pr/3639'
git switch 'upstream-pr/3639'
git rebase 'amd-dev'
git switch 'amd-dev'
git merge --no-ff 'upstream-pr/3639'
git switch 'amd-dev'
git merge --squash 'upstream-pr/3639'
git switch 'amd-dev'
git merge --ff-only 'upstream-pr/3639'
git switch 'amd-dev'
git merge 'upstream-pr/3639'
git push origin 'amd-dev'
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
xcl-dev/xcl!3639
No description provided.