D3D12.X: opt-in XCL_COPY_BACK=fault for GPU-written kept textures #3601

Open
iggyvilla wants to merge 3 commits from upstream-pr/3601 into amd-dev
iggyvilla commented 2026-12-01 18:15:00 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by iggyvilla on 2026-12-01T18:15:00Z.


Stacked on #3597 and #3675; only the top commit (97098ee9, +538/-1 across 5 files) belongs here.

Adds opt-in XCL_COPY_BACK=fault (default off; requires XCL_GUEST_WRITE_GUARD=1 from #3597) for GPU-written kept title_textures (#2663), split per review out of the previous monolithic commit (read-back helpers are now in #3675; GPU-owned RT/DS/UAV tracking will follow in a separate stacked PR on this one).

TL;DR — Before vs After

Metric Before (origin/amd-dev 41aa60ce) After (97098ee9, XCL_COPY_BACK unset)
Own-commit diff size 1,685 lines (monolithic) +538 / -1 (431 runtime + 107 test lines)
First-arm VEH race (arm()) protect_rw_runs ran before install() / ANY_ARMED install() and ANY_ARMED = true run under STATE before protect_rw_runs
60 s smoke frames / peak commit 1,654 / 15,902 MB (0 crashes) 1,646 / 16,607 MB (0 crashes)

What is in it (top commit 97098ee9 only)

  • crates/xcl/src/hle/d3d12x/copy_back.rs: XCL_COPY_BACK=fault state machine for kept textures: records list writes (note_write), arms whole committed 4 KiB title pages PAGE_NOACCESS behind a native per-queue fence (after_submit → signal → arm), skips imported coherent UMA (!uma.shadowed() && uma.in_committed_window) and guarded views upfront, serializes VirtualProtect against pinned writes via guest_write::while_unpinned, installs the VEH handler and sets ANY_ARMED under STATE before protecting pages, downloads via title_textures::read_back_after on fault, and disarms overlapping ranges (disarm_overlapping) before eager publish_download writes.
  • crates/xcl/src/hle/d3d12x/list_x.rs, present.rs, title_textures.rs, mod.rs: wires note_write, list_reset, after_submit, forget, forget_queue, and disarm_overlapping (all no-ops when off), plus GPU fault + fence-wait + disarm_overlapping test copy_back_a_cpu_read_of_a_gpu_written_texture_sees_the_gpu_texels.

Tested

  • Hardware: AMD Radeon RX 6650 XT 8 GB (RDNA2, driver 32.0.21045.29003), AMD Ryzen 7 5700X, Windows 11 x64, rustc 1.100.0 (0ef1bc386 2026-11-09), debug tests + release smoke.
  • XCL_ADAPTER=warp cargo test -p xcl --lib -- hle::d3d12x::title_textures::tests -- --test-threads=4 (3 consecutive runs on 97098ee9): copy_back_a_cpu_read_of_a_gpu_written_texture_sees_the_gpu_texels passed 3/3 cleanly (fixed test setup clearing pending + calling Table::mark_gpu_written so concurrent refresh() cannot read PAGE_NOACCESS pages during round=1's 200 ms fence wait).
  • cargo test --workspace --no-fail-fast -- --test-threads=4: 2,960 passed, 16 pre-existing failed, 49 ignored, 7 SKIPPED (same pre-existing failures as clean origin/amd-dev 41aa60ce).

Regression run
Base (main, required by pr_check.py):

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

Base (origin/amd-dev merge base):

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 (97098ee9, XCL_COPY_BACK unset):

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

Not tested

  • GPU-owned RT/DS/UAV tracking (split into the next stacked PR on top of this one).
  • NVIDIA and Intel GPUs, and Wine.

AI use

  • Antigravity (Gemini 4 Neon High) split #3601 into stacked PRs (#3675 helpers, this PR kept-texture fault mode, follow-up GPU-owned RT/DS/UAV), fixed the install() / ANY_ARMED ordering race in arm(), ran the GPU tests and 60 s smoke, and updated this description.
<!-- greyfinch-sync:ivall/xcl:issue:5591704384 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601). Originally posted by [iggyvilla](https://github.com/iggyvilla) on 2026-12-01T18:15:00Z. --- Stacked on #3597 and #3675; only the top commit (`97098ee9`, `+538/-1` across 5 files) belongs here. Adds opt-in `XCL_COPY_BACK=fault` (default off; requires `XCL_GUEST_WRITE_GUARD=1` from #3597) for GPU-written kept `title_textures` (#2663), split per review out of the previous monolithic commit (read-back helpers are now in #3675; GPU-owned RT/DS/UAV tracking will follow in a separate stacked PR on this one). ### TL;DR — Before vs After | Metric | Before (`origin/amd-dev` `41aa60ce`) | After (`97098ee9`, `XCL_COPY_BACK` unset) | |---|---|---| | **Own-commit diff size** | `1,685` lines (monolithic) | **`+538 / -1`** (`431` runtime + `107` test lines) | | **First-arm VEH race (`arm()`)** | `protect_rw_runs` ran before `install()` / `ANY_ARMED` | `install()` and `ANY_ARMED = true` run under `STATE` **before** `protect_rw_runs` | | **60 s smoke frames / peak commit** | `1,654` / `15,902 MB` (`0` crashes) | `1,646` / `16,607 MB` (`0` crashes) | **What is in it** (top commit `97098ee9` only) - `crates/xcl/src/hle/d3d12x/copy_back.rs`: `XCL_COPY_BACK=fault` state machine for kept textures: records list writes (`note_write`), arms whole committed 4 KiB title pages `PAGE_NOACCESS` behind a native per-queue fence (`after_submit` → `signal` → `arm`), skips imported coherent UMA (`!uma.shadowed() && uma.in_committed_window`) and guarded views upfront, serializes `VirtualProtect` against pinned writes via `guest_write::while_unpinned`, installs the VEH handler and sets `ANY_ARMED` under `STATE` before protecting pages, downloads via `title_textures::read_back_after` on fault, and disarms overlapping ranges (`disarm_overlapping`) before eager `publish_download` writes. - `crates/xcl/src/hle/d3d12x/list_x.rs`, `present.rs`, `title_textures.rs`, `mod.rs`: wires `note_write`, `list_reset`, `after_submit`, `forget`, `forget_queue`, and `disarm_overlapping` (all no-ops when off), plus GPU fault + fence-wait + `disarm_overlapping` test `copy_back_a_cpu_read_of_a_gpu_written_texture_sees_the_gpu_texels`. **Tested** - Hardware: AMD Radeon RX 6650 XT 8 GB (RDNA2, driver `32.0.21045.29003`), AMD Ryzen 7 5700X, Windows 11 x64, `rustc 1.100.0 (0ef1bc386 2026-11-09)`, debug tests + release smoke. - `XCL_ADAPTER=warp cargo test -p xcl --lib -- hle::d3d12x::title_textures::tests -- --test-threads=4` (3 consecutive runs on `97098ee9`): `copy_back_a_cpu_read_of_a_gpu_written_texture_sees_the_gpu_texels` passed **3/3** cleanly (fixed test setup clearing `pending` + calling `Table::mark_gpu_written` so concurrent `refresh()` cannot read `PAGE_NOACCESS` pages during `round=1`'s 200 ms fence wait). - `cargo test --workspace --no-fail-fast -- --test-threads=4`: **2,960 passed, 16 pre-existing failed, 49 ignored, 7 SKIPPED** (same pre-existing failures as clean `origin/amd-dev` `41aa60ce`). **Regression run** Base (`main`, required by `pr_check.py`): ``` 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 ``` Base (`origin/amd-dev` merge base): ``` 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 (`97098ee9`, `XCL_COPY_BACK` unset): ``` xcl-smoke v1 commit: 06f793199057f2da142c742ba510e7bec9fac509 gpu: AMD Radeon RX 6650 XT title: 1778c2d9 seconds: 60 exit: 0x0 frames shown: 1657 (PresentX 1657) presents per 2 s (last 3): 60 61 60 device removals: 0 crashes: 0 peak commit: 16649 MB ``` **Not tested** - GPU-owned RT/DS/UAV tracking (split into the next stacked PR on top of this one). - NVIDIA and Intel GPUs, and Wine. **AI use** - Antigravity (Gemini 4 Neon High) split #3601 into stacked PRs (#3675 helpers, this PR kept-texture fault mode, follow-up GPU-owned RT/DS/UAV), fixed the `install()` / `ANY_ARMED` ordering race in `arm()`, ran the GPU tests and 60 s smoke, and updated this description.
Foniass commented 2026-12-01 20:34:02 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T20:34:02Z.


Review (head 6950d2e5, diff read, not a merge-check):

  • Too large to review as one PR. 2,703 changed lines, none of them generated or test data; 1,018 are #3597 (1b6f6748) and this PR's own commit is 1,685 lines, with no reason given for going over ~800. Please split it along CONTRIBUTING.md and stack the parts on #3597, each under ~400 lines, for example: (1) gpu::texture::download plus title_textures::write_subresources / write_writable and their round-trip tests, not yet called; (2) copy_back.rs fault mode for kept textures with the after_submit / list_reset / forget hooks and the kept-texture GPU test; (3) the GPU-owned RT/DS/UAV registry (register_gpu_owned, note_transitions, the clear / OMSetRenderTargets / UAV-barrier hooks in device_x.rs, real.rs, list_x.rs) with its test; (4) the disarm_overlapping call in publish_download; (5) the census and line() diagnostics in submit_cost.rs. guest_write::while_unpinned belongs with #3597 or in its own PR.
  • Pages become no-access before the handler accepts faults on them. In copy_back.rs arm, protect_rw_runs makes the pages PAGE_NOACCESS at ~469, but install() only runs at ~477 and ANY_ARMED is set at ~480, and handler returns EXCEPTION_CONTINUE_SEARCH while ANY_ARMED is false (~616). On the first arm, or whenever nothing else is armed, a touch of those pages in that window is an unhandled access violation, including guest_write::open_with, which waits exactly until while_unpinned's protect returns and then touches the page (guest_write.rs ~330-338). Installing the handler and setting ANY_ARMED before protecting fixes it; fault already waits on STATE until the entry is inserted.

Not reviewed line by line because of the size. Fine: everything is behind copy_back::on() and stays off unless both XCL_COPY_BACK=fault and XCL_GUEST_WRITE_GUARD=1 are set; pages are reopened after a failed read-back; download keeps its objects alive when the wait fails.

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

<!-- greyfinch-sync:ivall/xcl:comment:7324905377 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#issuecomment-7324905377). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T20:34:02Z. --- Review (head 6950d2e5, diff read, not a merge-check): - **Too large to review as one PR.** 2,703 changed lines, none of them generated or test data; 1,018 are #3597 (`1b6f6748`) and this PR's own commit is 1,685 lines, with no reason given for going over ~800. Please split it along CONTRIBUTING.md and stack the parts on #3597, each under ~400 lines, for example: (1) `gpu::texture::download` plus `title_textures::write_subresources` / `write_writable` and their round-trip tests, not yet called; (2) `copy_back.rs` fault mode for kept textures with the `after_submit` / `list_reset` / `forget` hooks and the kept-texture GPU test; (3) the GPU-owned RT/DS/UAV registry (`register_gpu_owned`, `note_transitions`, the clear / `OMSetRenderTargets` / UAV-barrier hooks in `device_x.rs`, `real.rs`, `list_x.rs`) with its test; (4) the `disarm_overlapping` call in `publish_download`; (5) the census and `line()` diagnostics in `submit_cost.rs`. `guest_write::while_unpinned` belongs with #3597 or in its own PR. - **Pages become no-access before the handler accepts faults on them.** In `copy_back.rs` `arm`, `protect_rw_runs` makes the pages `PAGE_NOACCESS` at ~469, but `install()` only runs at ~477 and `ANY_ARMED` is set at ~480, and `handler` returns `EXCEPTION_CONTINUE_SEARCH` while `ANY_ARMED` is false (~616). On the first arm, or whenever nothing else is armed, a touch of those pages in that window is an unhandled access violation, including `guest_write::open_with`, which waits exactly until `while_unpinned`'s protect returns and then `touch`es the page (`guest_write.rs` ~330-338). Installing the handler and setting `ANY_ARMED` before protecting fixes it; `fault` already waits on `STATE` until the entry is inserted. Not reviewed line by line because of the size. Fine: everything is behind `copy_back::on()` and stays off unless both `XCL_COPY_BACK=fault` and `XCL_GUEST_WRITE_GUARD=1` are set; pages are reopened after a failed read-back; `download` keeps its objects alive when the wait fails. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
iggyvilla commented 2026-12-02 06:50:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by iggyvilla on 2026-12-02T06:50:48Z.


Split and updated to 4cd5273d addressing @Foniass's review:\n- Split into small stacked PRs: moved guest_write::while_unpinned / meets_guarded_view into #3597 (07d529ea), split gpu::texture::download + title_textures read-back helpers into standalone #3675 (effdc0a8, 384 lines), narrowed this PR strictly to kept-texture fault mode + disarm_overlapping (own commit +532/-1, 431 runtime + 101 test lines, down from 1,685), and deferred GPU-owned RT/DS/UAV tracking to a follow-up stacked PR.\n- Fixed first-arm VEH race: arm() now calls install() and sets ANY_ARMED = true under STATE before protect_rw_runs makes pages PAGE_NOACCESS, so any concurrent touch immediately enters handler and waits on STATE.\n- Added whole-workspace GPU test counts and 41aa60ce merge-base smoke.

<!-- greyfinch-sync:ivall/xcl:comment:7337474512 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#issuecomment-7337474512). Originally posted by [iggyvilla](https://github.com/iggyvilla) on 2026-12-02T06:50:48Z. --- Split and updated to `4cd5273d` addressing @Foniass's review:\n- **Split into small stacked PRs**: moved `guest_write::while_unpinned` / `meets_guarded_view` into #3597 (`07d529ea`), split `gpu::texture::download` + `title_textures` read-back helpers into standalone #3675 (`effdc0a8`, 384 lines), narrowed this PR strictly to kept-texture fault mode + `disarm_overlapping` (own commit `+532/-1`, 431 runtime + 101 test lines, down from 1,685), and deferred GPU-owned RT/DS/UAV tracking to a follow-up stacked PR.\n- **Fixed first-arm VEH race**: `arm()` now calls `install()` and sets `ANY_ARMED = true` under `STATE` **before** `protect_rw_runs` makes pages `PAGE_NOACCESS`, so any concurrent touch immediately enters `handler` and waits on `STATE`.\n- Added whole-workspace GPU test counts and `41aa60ce` merge-base smoke.
Foniass commented 2026-12-02 06:56:36 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T06:56:36Z.


Follow-up review (head 4cd5273d, since 6950d2e5, diff read, not a merge-check):

  • Too large to review as one PR: fixed. The branch is now #3675 (effdc0a8), #3597 (f601ec43, the same patch as its head 07d529ea) and this PR's own 4cd5273d, +532/-1 (about 430 runtime).
  • Pages become no-access before the handler accepts faults on them: fixed. arm calls install() and sets ANY_ARMED (copy_back.rs ~200-201) before protect_rw_runs (~205), under STATE, so a concurrent touch faults and waits in fault until the entry is in (~214).

New:

  • A second thread touching an armed texture during a read-back crashes. fault removes the entry and clears ANY_ARMED (~349-350), then waits in read_back_after (~359) for the fence and the download before opening the pages. A second thread reading the same pages in that window gets EXCEPTION_CONTINUE_SEARCH from handler: it returns at ~328 when ANY_ARMED is false, and otherwise fault finds no entry and accessible sees PAGE_NOACCESS (~340), so the access violation is unhandled. forget (~309) and disarm_overlapping (~291) leave the same window. The earlier head serialized faults with a lock, so a late fault found the page already open; that lock is gone.
  • This makes #3597's open_with lost wakeup reachable. This is the first caller of guest_write::register (~203) and while_unpinned (~234), so with XCL_COPY_BACK=fault a ReadFile or DirectStorage write over a texture being armed can spin forever at guest_write.rs ~336 (see the follow-up on #3597).
  • Every fault goes through #3675's helpers as they are. fault → read_back_after → download_and_write_after queues a native_queue_wait for the title-queue fence on the shared upload queue (title_textures.rs ~4323), so every XCL upload sent after it waits for the title queue; write_writable (~4260) skips unwritable pages and still reports Ok; a TEXTURES lock held over 200 ms (~4346) turns the fault into an error, marks the texture refused, and the title reads stale bytes.
  • The wiring and the claimed results lack evidence. The new test calls copy_back::note_write / after_submit directly with a made-up list key (0x7E57_0001, title_textures.rs ~8821), so nothing goes through the new list_x.rs hooks; no smoke run sets XCL_COPY_BACK=fault; and Tested reports the whole suite only on d8d9399b (22 failed), not on 4cd5273d.

Fine: off unless both XCL_COPY_BACK=fault and XCL_GUEST_WRITE_GUARD=1 are set, with every hook returning early when off; imported coherent UMA and guarded views are skipped before anything is protected; armed ranges cannot overlap; publish_download disarms before reading title bytes; the lock order is TEXTURES → STATE.

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

<!-- greyfinch-sync:ivall/xcl:comment:7337586303 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#issuecomment-7337586303). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T06:56:36Z. --- Follow-up review (head 4cd5273d, since 6950d2e5, diff read, not a merge-check): - **Too large to review as one PR:** fixed. The branch is now #3675 (`effdc0a8`), #3597 (`f601ec43`, the same patch as its head `07d529ea`) and this PR's own `4cd5273d`, +532/-1 (about 430 runtime). - **Pages become no-access before the handler accepts faults on them:** fixed. `arm` calls `install()` and sets `ANY_ARMED` (`copy_back.rs` ~200-201) before `protect_rw_runs` (~205), under `STATE`, so a concurrent touch faults and waits in `fault` until the entry is in (~214). New: - **A second thread touching an armed texture during a read-back crashes.** `fault` removes the entry and clears `ANY_ARMED` (~349-350), then waits in `read_back_after` (~359) for the fence and the download before opening the pages. A second thread reading the same pages in that window gets `EXCEPTION_CONTINUE_SEARCH` from `handler`: it returns at ~328 when `ANY_ARMED` is false, and otherwise `fault` finds no entry and `accessible` sees `PAGE_NOACCESS` (~340), so the access violation is unhandled. `forget` (~309) and `disarm_overlapping` (~291) leave the same window. The earlier head serialized faults with a lock, so a late fault found the page already open; that lock is gone. - **This makes #3597's `open_with` lost wakeup reachable.** This is the first caller of `guest_write::register` (~203) and `while_unpinned` (~234), so with `XCL_COPY_BACK=fault` a `ReadFile` or DirectStorage write over a texture being armed can spin forever at `guest_write.rs` ~336 (see the follow-up on #3597). - **Every fault goes through #3675's helpers as they are.** `fault` → `read_back_after` → `download_and_write_after` queues a `native_queue_wait` for the title-queue fence on the shared upload queue (`title_textures.rs` ~4323), so every XCL upload sent after it waits for the title queue; `write_writable` (~4260) skips unwritable pages and still reports `Ok`; a `TEXTURES` lock held over 200 ms (~4346) turns the fault into an error, marks the texture `refused`, and the title reads stale bytes. - **The wiring and the claimed results lack evidence.** The new test calls `copy_back::note_write` / `after_submit` directly with a made-up list key (`0x7E57_0001`, `title_textures.rs` ~8821), so nothing goes through the new `list_x.rs` hooks; no smoke run sets `XCL_COPY_BACK=fault`; and **Tested** reports the whole suite only on `d8d9399b` (22 failed), not on `4cd5273d`. Fine: off unless both `XCL_COPY_BACK=fault` and `XCL_GUEST_WRITE_GUARD=1` are set, with every hook returning early when off; imported coherent UMA and guarded views are skipped before anything is protected; armed ranges cannot overlap; `publish_download` disarms before reading title bytes; the lock order is `TEXTURES` → `STATE`. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Foniass commented 2026-12-02 07:59:37 +00:00 (Migrated from github.com)

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


Follow-up review (head 97098ee9, since 4cd5273d, diff read, not a merge-check):

  • Earlier points: unchanged. Since 4cd5273d only the GPU test changed: it now marks the texture GPU-written directly under TEXTURES instead of going through capture_gpu_write / publish_submission_effects (title_textures.rs ~8836-8847). Still open: a second thread touching an armed texture during a read-back gets an unhandled access violation (copy_back.rs ~349-366), #3597's open_with lost wakeup is reachable through this PR's register / while_unpinned calls, the fault path's reliance on #3675's helpers, and no run with XCL_COPY_BACK=fault or through the list_x.rs hooks.

New: none.

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

<!-- greyfinch-sync:ivall/xcl:comment:7338868283 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#issuecomment-7338868283). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T07:59:37Z. --- Follow-up review (head 97098ee9, since 4cd5273d, diff read, not a merge-check): - **Earlier points:** unchanged. Since `4cd5273d` only the GPU test changed: it now marks the texture GPU-written directly under `TEXTURES` instead of going through `capture_gpu_write` / `publish_submission_effects` (`title_textures.rs` ~8836-8847). Still open: a second thread touching an armed texture during a read-back gets an unhandled access violation (`copy_back.rs` ~349-366), #3597's `open_with` lost wakeup is reachable through this PR's `register` / `while_unpinned` calls, the fault path's reliance on #3675's helpers, and no run with `XCL_COPY_BACK=fault` or through the `list_x.rs` hooks. New: none. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Foniass commented 2026-12-02 08:14:41 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T08:14:41Z.


Follow-up review (head 06f79319, since 97098ee9, diff read, not a merge-check; checks red):

  • Earlier points: unchanged; since 97098ee9 only the GPU test changed, now also decrementing PENDING when it clears a texture's pending flag (title_textures.rs ~8843). The open points from the previous review stand.

New: none.

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

<!-- greyfinch-sync:ivall/xcl:comment:7339189925 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#issuecomment-7339189925). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T08:14:41Z. --- Follow-up review (head 06f79319, since 97098ee9, diff read, not a merge-check; checks red): - **Earlier points:** unchanged; since `97098ee9` only the GPU test changed, now also decrementing `PENDING` when it clears a texture's `pending` flag (`title_textures.rs` ~8843). The open points from the previous review stand. New: none. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Foniass commented 2026-12-02 13:35:47 +00:00 (Migrated from github.com)

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


merge-check
base: 41aa60ce84
head: 06f7931990
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/3601#issuecomment-7339189925 and its findings stand. Most serious: fault() (copy_back.rs ~345) removes the armed entry before read_back_after, so a second thread touching the same pages meanwhile finds no entry and gets an unhandled access violation.
performance: 60 s smoke of a retail title, amd-dev 41aa60ce vs this merge (06f79319): 1671 -> 1691 frames shown (101 %; last presents per 2 s: 60 60 60), peak commit 16722 -> 16857 MB, 0 device removals, 0 crashes.
verdict: not yet: fault() (copy_back.rs ~345) removes the armed entry before read_back_after, so a second thread touching the same pages meanwhile finds no entry and gets 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:7347130176 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#issuecomment-7347130176). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T13:35:47Z. --- merge-check base: 41aa60ce842060a597b7e8724896f7bf6a031af5 head: 06f793199057f2da142c742ba510e7bec9fac509 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/3601#issuecomment-7339189925 and its findings stand. Most serious: `fault()` (`copy_back.rs` ~345) removes the armed entry before `read_back_after`, so a second thread touching the same pages meanwhile finds no entry and gets an unhandled access violation. performance: 60 s smoke of a retail title, amd-dev 41aa60ce vs this merge (06f79319): 1671 -> 1691 frames shown (101 %; last presents per 2 s: 60 60 60), peak commit 16722 -> 16857 MB, 0 device removals, 0 crashes. verdict: not yet: `fault()` (`copy_back.rs` ~345) removes the armed entry before `read_back_after`, so a second thread touching the same pages meanwhile finds no entry and gets 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 15:45:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:29Z.

Code review location: crates/xcl/src/hle/d3d12x/copy_back.rs; line 349

@@ -0,0 +1,410 @@
+//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires
+//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663).
+//!
+//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the
+//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS`
+//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence
+//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and
+//! re-tiles changed pages back into console layout.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, Once, OnceLock};
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+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_NOACCESS, PAGE_READWRITE};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+
+fn mode_on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) {
+            return false;
+        }
+        if !guest_write::enabled() {
+            crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+            return false;
+        }
+        crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch");
+        true
+    })
+}
+
+#[cfg(test)]
+static FORCE: AtomicBool = AtomicBool::new(false);
+
+pub fn on() -> bool {
+    #[cfg(test)]
+    if FORCE.load(Ordering::Acquire) {
+        return true;
+    }
+    mode_on()
+}
+
+/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87).
+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 Shared<T>(T);
+unsafe impl<T> Send for Shared<T> {}
+
+struct Armed {
+    res: usize,
+    lo: usize,
+    hi: usize,
+    runs: Vec<(usize, usize)>,
+    fence: Shared<ID3D12Fence>,
+    value: u64,
+}
+
+#[derive(Default)]
+struct State {
+    pending: HashMap<usize, Vec<usize>>,
+    armed: BTreeMap<usize, Armed>,
+    by_res: HashMap<usize, usize>,
+    refused: HashSet<usize>,
+    fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static ANY_ARMED: AtomicBool = AtomicBool::new(false);
+static HANDLER: Once = Once::new();
+#[cfg(test)]
+static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)];
+static ERRORS: AtomicU64 = AtomicU64::new(0);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+pub fn note_write(list: usize, res: usize) {
+    if !on() || list == 0 || res == 0 {
+        return;
+    }
+    with(|s| {
+        let v = s.pending.entry(list).or_default();
+        if !v.contains(&res) {
+            v.push(res);
+        }
+    });
+}
+
+pub fn list_reset(list: usize) {
+    if !on() || list == 0 {
+        return;
+    }
+    with(|s| {
+        s.pending.remove(&list);
+    });
+}
+
+pub fn forget_queue(queue: usize) {
+    if !on() || queue == 0 {
+        return;
+    }
+    with(|s| {
+        s.fences.remove(&queue);
+    });
+}
+
+pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) {
+    if !on() || queue.is_null() || lists.is_empty() {
+        return;
+    }
+    let textures: Vec<usize> = with(|s| {
+        let mut out = Vec::new();
+        for &l in lists {
+            if let Some(v) = s.pending.get(&(l as usize)) {
+                for &r in v {
+                    if !out.contains(&r) {
+                        out.push(r);
+                    }
+                }
+            }
+        }
+        out
+    });
+    if textures.is_empty() {
+        return;
+    }
+    let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
+    let Some((fence, value)) = signal(q) else { return };
+    for res in textures {
+        arm(res, &fence, value);
+    }
+}
+
+unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> {
+    let key = q.as_raw() as usize;
+    let (fence, value) = with(|s| {
+        if let Some((f, v)) = s.fences.get_mut(&key) {
+            *v += 1;
+            return Some((f.0.clone(), *v));
+        }
+        let mut dev: Option<ID3D12Device> = None;
+        q.GetDevice(&mut dev).ok()?;
+        let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
+        s.fences.insert(key, (Shared(f.clone()), 1));
+        Some((f, 1))
+    })?;
+    super::real::native_queue_signal(q, &fence, value).ok()?;
+    Some((fence, value))
+}
+
+unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) {
+    let Some((va, len)) = super::title_textures::copy_back_range(res) else { return };
+    let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1));
+    if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) {
+        return;
+    }
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let s = g.get_or_insert_with(State::default);
+    if s.refused.contains(&res) {
+        return;
+    }
+    if let Some(&at) = s.by_res.get(&res) {
+        if let Some(a) = s.armed.get_mut(&at) {
+            a.fence = Shared(fence.clone());
+            a.value = value;
+        }
+        return;
+    }
+    if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() {
+        if other.hi > lo {
+            if other_lo == lo && other.hi == hi {
+                let old_res = other.res;
+                s.by_res.remove(&old_res);
+                if let Some(a) = s.armed.get_mut(&other_lo) {
+                    a.res = res;
+                    a.fence = Shared(fence.clone());
+                    a.value = value;
+                }
+                s.by_res.insert(res, lo);
+                #[cfg(test)]
+                TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+            }
+            return;
+        }
+    }
+    // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while
+    // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE.
+    install();
+    ANY_ARMED.store(true, Ordering::Release);
+    if guest_write::enabled() {
+        guest_write::register(lo, hi - lo);
+    }
+    let runs = protect_rw_runs(lo, hi);
+    if runs.is_empty() {
+        if guest_write::enabled() {
+            guest_write::unregister(lo, hi - lo);
+        }
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        return;
+    }
+    s.by_res.insert(res, lo);
+    s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value });
+    #[cfg(test)]
+    TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+}
+
+unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> {
+    let mut runs = Vec::new();
+    let mut at = lo;
+    while at < hi {
+        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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+        if end <= at {
+            break;
+        }
+        if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE {
+            let n = end - at;
+            let done = if guest_write::enabled() {
+                guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS))
+            } else {
+                protect(at, n, PAGE_NOACCESS)
+            };
+            if done {
+                runs.push((at, n));
+            }
+        }
+        at = end;
+    }
+    runs
+}
+
+unsafe fn protect(a: usize, n: usize, p: u32) -> bool {
+    let mut old = 0;
+    VirtualProtect(a as *const c_void, n, p, &mut old) != 0
+}
+
+unsafe fn open_runs(runs: &[(usize, usize)]) {
+    for &(a, n) in runs {
+        let mut at = a;
+        let hi = a + n;
+        while at < hi {
+            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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+            if end <= at {
+                break;
+            }
+            if m.State == MEM_COMMIT && m.Protect == PAGE_NOACCESS {
+                let _ = protect(at, end - at, PAGE_READWRITE);
+            }
+            at = end;
+        }
+    }
+}
+
+/// Disarm armed entries overlapping `[va, va + len)` before eager `publish_download` writes there.
+pub(super) fn disarm_overlapping(va: usize, len: usize) {
+    if !ANY_ARMED.load(Ordering::Acquire) || len == 0 {
+        return;
+    }
+    let hi = va.saturating_add(len);
+    let gone: Vec<Armed> = with(|s| {
+        let keys: Vec<usize> = s.armed.range(..hi).filter(|(_, a)| a.hi > va).map(|(&k, _)| k).collect();
+        let mut out = Vec::with_capacity(keys.len());
+        for k in keys {
+            if let Some(a) = s.armed.remove(&k) {
+                s.by_res.remove(&a.res);
+                out.push(a);
+            }
+        }
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        out
+    });
+    for a in gone {
+        disarm(&a);
+    }
+}
+
+pub fn forget(res: usize) {
+    if !on() || res == 0 {
+        return;
+    }
+    let gone = with(|s| {
+        s.refused.remove(&res);
+        for v in s.pending.values_mut() {
+            v.retain(|&r| r != res);
+        }
+        let a = s.by_res.remove(&res).and_then(|lo| s.armed.remove(&lo));
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        a
+    });
+    if let Some(a) = gone {
+        disarm(&a);
+    }
+}
+
+fn disarm(a: &Armed) {
+    unsafe { open_runs(&a.runs) };
+    if guest_write::enabled() {
+        guest_write::unregister(a.lo, a.hi - a.lo);
+    }
+}
+
+fn install() {
+    HANDLER.call_once(|| unsafe {
+        AddVectoredExceptionHandler(1, Some(handler));
+    });
+}
+
+unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
+    if !ANY_ARMED.load(Ordering::Acquire) {
+        return 0;
+    }
+    let r = &*(*info).ExceptionRecord;
+    if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 {
+        return 0;
+    }
+    let kind = r.ExceptionInformation[0];
+    if kind != 0 && kind != 1 {
+        return 0;
+    }
+    let at = r.ExceptionInformation[1];
+    if fault(at) || accessible(at, kind == 1) { -1 } else { 0 }
+}
+
+fn fault(at: usize) -> bool {
+    let armed = with(|s| {
+        let (&lo, a) = s.armed.range(..=at).next_back()?;
+        if at >= a.hi {
+            return None;
+        }
+        let a = s.armed.remove(&lo)?;

Critical: fault() removes the armed entry from STATE before the long fence wait and readback, so a second thread touching the same still-PAGE_NOACCESS pages finds no entry, accessible() is false, and the handler returns EXCEPTION_CONTINUE_SEARCH: an unhandled access violation. Thread A reads texture T and faults; fault() takes T's entry and blocks in read_back_after on the queue fence. Thread B (another title worker, or guest_write::open's touch()) reads T before A's before_write opens the pages, so B's fault() returns false and the process crashes. Keeping the entry (marked in-progress) until the pages are opened, and having other faulters wait on it, would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772202888 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#discussion_r4772202888). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:29Z. **Code review location:** `crates/xcl/src/hle/d3d12x/copy_back.rs`; line 349 ~~~~diff @@ -0,0 +1,410 @@ +//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires +//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663). +//! +//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the +//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS` +//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence +//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and +//! re-tiles changed pages back into console layout. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, Once, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +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_NOACCESS, PAGE_READWRITE}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; + +fn mode_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) { + return false; + } + if !guest_write::enabled() { + crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + return false; + } + crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch"); + true + }) +} + +#[cfg(test)] +static FORCE: AtomicBool = AtomicBool::new(false); + +pub fn on() -> bool { + #[cfg(test)] + if FORCE.load(Ordering::Acquire) { + return true; + } + mode_on() +} + +/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87). +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 Shared<T>(T); +unsafe impl<T> Send for Shared<T> {} + +struct Armed { + res: usize, + lo: usize, + hi: usize, + runs: Vec<(usize, usize)>, + fence: Shared<ID3D12Fence>, + value: u64, +} + +#[derive(Default)] +struct State { + pending: HashMap<usize, Vec<usize>>, + armed: BTreeMap<usize, Armed>, + by_res: HashMap<usize, usize>, + refused: HashSet<usize>, + fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); +static ANY_ARMED: AtomicBool = AtomicBool::new(false); +static HANDLER: Once = Once::new(); +#[cfg(test)] +static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; +static ERRORS: AtomicU64 = AtomicU64::new(0); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +pub fn note_write(list: usize, res: usize) { + if !on() || list == 0 || res == 0 { + return; + } + with(|s| { + let v = s.pending.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + }); +} + +pub fn list_reset(list: usize) { + if !on() || list == 0 { + return; + } + with(|s| { + s.pending.remove(&list); + }); +} + +pub fn forget_queue(queue: usize) { + if !on() || queue == 0 { + return; + } + with(|s| { + s.fences.remove(&queue); + }); +} + +pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || queue.is_null() || lists.is_empty() { + return; + } + let textures: Vec<usize> = with(|s| { + let mut out = Vec::new(); + for &l in lists { + if let Some(v) = s.pending.get(&(l as usize)) { + for &r in v { + if !out.contains(&r) { + out.push(r); + } + } + } + } + out + }); + if textures.is_empty() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some((fence, value)) = signal(q) else { return }; + for res in textures { + arm(res, &fence, value); + } +} + +unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + let key = q.as_raw() as usize; + let (fence, value) = with(|s| { + if let Some((f, v)) = s.fences.get_mut(&key) { + *v += 1; + return Some((f.0.clone(), *v)); + } + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + s.fences.insert(key, (Shared(f.clone()), 1)); + Some((f, 1)) + })?; + super::real::native_queue_signal(q, &fence, value).ok()?; + Some((fence, value)) +} + +unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) { + let Some((va, len)) = super::title_textures::copy_back_range(res) else { return }; + let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1)); + if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) { + return; + } + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(State::default); + if s.refused.contains(&res) { + return; + } + if let Some(&at) = s.by_res.get(&res) { + if let Some(a) = s.armed.get_mut(&at) { + a.fence = Shared(fence.clone()); + a.value = value; + } + return; + } + if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() { + if other.hi > lo { + if other_lo == lo && other.hi == hi { + let old_res = other.res; + s.by_res.remove(&old_res); + if let Some(a) = s.armed.get_mut(&other_lo) { + a.res = res; + a.fence = Shared(fence.clone()); + a.value = value; + } + s.by_res.insert(res, lo); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); + } + return; + } + } + // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while + // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE. + install(); + ANY_ARMED.store(true, Ordering::Release); + if guest_write::enabled() { + guest_write::register(lo, hi - lo); + } + let runs = protect_rw_runs(lo, hi); + if runs.is_empty() { + if guest_write::enabled() { + guest_write::unregister(lo, hi - lo); + } + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + return; + } + s.by_res.insert(res, lo); + s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value }); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); +} + +unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> { + let mut runs = Vec::new(); + let mut at = lo; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE { + let n = end - at; + let done = if guest_write::enabled() { + guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS)) + } else { + protect(at, n, PAGE_NOACCESS) + }; + if done { + runs.push((at, n)); + } + } + at = end; + } + runs +} + +unsafe fn protect(a: usize, n: usize, p: u32) -> bool { + let mut old = 0; + VirtualProtect(a as *const c_void, n, p, &mut old) != 0 +} + +unsafe fn open_runs(runs: &[(usize, usize)]) { + for &(a, n) in runs { + let mut at = a; + let hi = a + n; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_NOACCESS { + let _ = protect(at, end - at, PAGE_READWRITE); + } + at = end; + } + } +} + +/// Disarm armed entries overlapping `[va, va + len)` before eager `publish_download` writes there. +pub(super) fn disarm_overlapping(va: usize, len: usize) { + if !ANY_ARMED.load(Ordering::Acquire) || len == 0 { + return; + } + let hi = va.saturating_add(len); + let gone: Vec<Armed> = with(|s| { + let keys: Vec<usize> = s.armed.range(..hi).filter(|(_, a)| a.hi > va).map(|(&k, _)| k).collect(); + let mut out = Vec::with_capacity(keys.len()); + for k in keys { + if let Some(a) = s.armed.remove(&k) { + s.by_res.remove(&a.res); + out.push(a); + } + } + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + out + }); + for a in gone { + disarm(&a); + } +} + +pub fn forget(res: usize) { + if !on() || res == 0 { + return; + } + let gone = with(|s| { + s.refused.remove(&res); + for v in s.pending.values_mut() { + v.retain(|&r| r != res); + } + let a = s.by_res.remove(&res).and_then(|lo| s.armed.remove(&lo)); + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + a + }); + if let Some(a) = gone { + disarm(&a); + } +} + +fn disarm(a: &Armed) { + unsafe { open_runs(&a.runs) }; + if guest_write::enabled() { + guest_write::unregister(a.lo, a.hi - a.lo); + } +} + +fn install() { + HANDLER.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + if !ANY_ARMED.load(Ordering::Acquire) { + return 0; + } + let r = &*(*info).ExceptionRecord; + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 { + return 0; + } + let kind = r.ExceptionInformation[0]; + if kind != 0 && kind != 1 { + return 0; + } + let at = r.ExceptionInformation[1]; + if fault(at) || accessible(at, kind == 1) { -1 } else { 0 } +} + +fn fault(at: usize) -> bool { + let armed = with(|s| { + let (&lo, a) = s.armed.range(..=at).next_back()?; + if at >= a.hi { + return None; + } + let a = s.armed.remove(&lo)?; ~~~~ --- **Critical**: `fault()` removes the armed entry from STATE before the long fence wait and readback, so a second thread touching the same still-PAGE_NOACCESS pages finds no entry, `accessible()` is false, and the handler returns EXCEPTION_CONTINUE_SEARCH: an unhandled access violation. Thread A reads texture T and faults; `fault()` takes T's entry and blocks in `read_back_after` on the queue fence. Thread B (another title worker, or `guest_write::open`'s `touch()`) reads T before A's `before_write` opens the pages, so B's `fault()` returns false and the process crashes. Keeping the entry (marked in-progress) until the pages are opened, and having other faulters wait on it, would fix it.
bmjask commented 2026-12-02 15:45:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:29Z.

Code review location: crates/xcl/src/hle/d3d12x/copy_back.rs; line 359

@@ -0,0 +1,410 @@
+//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires
+//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663).
+//!
+//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the
+//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS`
+//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence
+//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and
+//! re-tiles changed pages back into console layout.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, Once, OnceLock};
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+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_NOACCESS, PAGE_READWRITE};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+
+fn mode_on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) {
+            return false;
+        }
+        if !guest_write::enabled() {
+            crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+            return false;
+        }
+        crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch");
+        true
+    })
+}
+
+#[cfg(test)]
+static FORCE: AtomicBool = AtomicBool::new(false);
+
+pub fn on() -> bool {
+    #[cfg(test)]
+    if FORCE.load(Ordering::Acquire) {
+        return true;
+    }
+    mode_on()
+}
+
+/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87).
+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 Shared<T>(T);
+unsafe impl<T> Send for Shared<T> {}
+
+struct Armed {
+    res: usize,
+    lo: usize,
+    hi: usize,
+    runs: Vec<(usize, usize)>,
+    fence: Shared<ID3D12Fence>,
+    value: u64,
+}
+
+#[derive(Default)]
+struct State {
+    pending: HashMap<usize, Vec<usize>>,
+    armed: BTreeMap<usize, Armed>,
+    by_res: HashMap<usize, usize>,
+    refused: HashSet<usize>,
+    fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static ANY_ARMED: AtomicBool = AtomicBool::new(false);
+static HANDLER: Once = Once::new();
+#[cfg(test)]
+static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)];
+static ERRORS: AtomicU64 = AtomicU64::new(0);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+pub fn note_write(list: usize, res: usize) {
+    if !on() || list == 0 || res == 0 {
+        return;
+    }
+    with(|s| {
+        let v = s.pending.entry(list).or_default();
+        if !v.contains(&res) {
+            v.push(res);
+        }
+    });
+}
+
+pub fn list_reset(list: usize) {
+    if !on() || list == 0 {
+        return;
+    }
+    with(|s| {
+        s.pending.remove(&list);
+    });
+}
+
+pub fn forget_queue(queue: usize) {
+    if !on() || queue == 0 {
+        return;
+    }
+    with(|s| {
+        s.fences.remove(&queue);
+    });
+}
+
+pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) {
+    if !on() || queue.is_null() || lists.is_empty() {
+        return;
+    }
+    let textures: Vec<usize> = with(|s| {
+        let mut out = Vec::new();
+        for &l in lists {
+            if let Some(v) = s.pending.get(&(l as usize)) {
+                for &r in v {
+                    if !out.contains(&r) {
+                        out.push(r);
+                    }
+                }
+            }
+        }
+        out
+    });
+    if textures.is_empty() {
+        return;
+    }
+    let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
+    let Some((fence, value)) = signal(q) else { return };
+    for res in textures {
+        arm(res, &fence, value);
+    }
+}
+
+unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> {
+    let key = q.as_raw() as usize;
+    let (fence, value) = with(|s| {
+        if let Some((f, v)) = s.fences.get_mut(&key) {
+            *v += 1;
+            return Some((f.0.clone(), *v));
+        }
+        let mut dev: Option<ID3D12Device> = None;
+        q.GetDevice(&mut dev).ok()?;
+        let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
+        s.fences.insert(key, (Shared(f.clone()), 1));
+        Some((f, 1))
+    })?;
+    super::real::native_queue_signal(q, &fence, value).ok()?;
+    Some((fence, value))
+}
+
+unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) {
+    let Some((va, len)) = super::title_textures::copy_back_range(res) else { return };
+    let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1));
+    if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) {
+        return;
+    }
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let s = g.get_or_insert_with(State::default);
+    if s.refused.contains(&res) {
+        return;
+    }
+    if let Some(&at) = s.by_res.get(&res) {
+        if let Some(a) = s.armed.get_mut(&at) {
+            a.fence = Shared(fence.clone());
+            a.value = value;
+        }
+        return;
+    }
+    if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() {
+        if other.hi > lo {
+            if other_lo == lo && other.hi == hi {
+                let old_res = other.res;
+                s.by_res.remove(&old_res);
+                if let Some(a) = s.armed.get_mut(&other_lo) {
+                    a.res = res;
+                    a.fence = Shared(fence.clone());
+                    a.value = value;
+                }
+                s.by_res.insert(res, lo);
+                #[cfg(test)]
+                TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+            }
+            return;
+        }
+    }
+    // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while
+    // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE.
+    install();
+    ANY_ARMED.store(true, Ordering::Release);
+    if guest_write::enabled() {
+        guest_write::register(lo, hi - lo);
+    }
+    let runs = protect_rw_runs(lo, hi);
+    if runs.is_empty() {
+        if guest_write::enabled() {
+            guest_write::unregister(lo, hi - lo);
+        }
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        return;
+    }
+    s.by_res.insert(res, lo);
+    s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value });
+    #[cfg(test)]
+    TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+}
+
+unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> {
+    let mut runs = Vec::new();
+    let mut at = lo;
+    while at < hi {
+        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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+        if end <= at {
+            break;
+        }
+        if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE {
+            let n = end - at;
+            let done = if guest_write::enabled() {
+                guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS))
+            } else {
+                protect(at, n, PAGE_NOACCESS)
+            };
+            if done {
+                runs.push((at, n));
+            }
+        }
+        at = end;
+    }
+    runs
+}
+
+unsafe fn protect(a: usize, n: usize, p: u32) -> bool {
+    let mut old = 0;
+    VirtualProtect(a as *const c_void, n, p, &mut old) != 0
+}
+
+unsafe fn open_runs(runs: &[(usize, usize)]) {
+    for &(a, n) in runs {
+        let mut at = a;
+        let hi = a + n;
+        while at < hi {
+            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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+            if end <= at {
+                break;
+            }
+            if m.State == MEM_COMMIT && m.Protect == PAGE_NOACCESS {
+                let _ = protect(at, end - at, PAGE_READWRITE);
+            }
+            at = end;
+        }
+    }
+}
+
+/// Disarm armed entries overlapping `[va, va + len)` before eager `publish_download` writes there.
+pub(super) fn disarm_overlapping(va: usize, len: usize) {
+    if !ANY_ARMED.load(Ordering::Acquire) || len == 0 {
+        return;
+    }
+    let hi = va.saturating_add(len);
+    let gone: Vec<Armed> = with(|s| {
+        let keys: Vec<usize> = s.armed.range(..hi).filter(|(_, a)| a.hi > va).map(|(&k, _)| k).collect();
+        let mut out = Vec::with_capacity(keys.len());
+        for k in keys {
+            if let Some(a) = s.armed.remove(&k) {
+                s.by_res.remove(&a.res);
+                out.push(a);
+            }
+        }
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        out
+    });
+    for a in gone {
+        disarm(&a);
+    }
+}
+
+pub fn forget(res: usize) {
+    if !on() || res == 0 {
+        return;
+    }
+    let gone = with(|s| {
+        s.refused.remove(&res);
+        for v in s.pending.values_mut() {
+            v.retain(|&r| r != res);
+        }
+        let a = s.by_res.remove(&res).and_then(|lo| s.armed.remove(&lo));
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        a
+    });
+    if let Some(a) = gone {
+        disarm(&a);
+    }
+}
+
+fn disarm(a: &Armed) {
+    unsafe { open_runs(&a.runs) };
+    if guest_write::enabled() {
+        guest_write::unregister(a.lo, a.hi - a.lo);
+    }
+}
+
+fn install() {
+    HANDLER.call_once(|| unsafe {
+        AddVectoredExceptionHandler(1, Some(handler));
+    });
+}
+
+unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
+    if !ANY_ARMED.load(Ordering::Acquire) {
+        return 0;
+    }
+    let r = &*(*info).ExceptionRecord;
+    if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 {
+        return 0;
+    }
+    let kind = r.ExceptionInformation[0];
+    if kind != 0 && kind != 1 {
+        return 0;
+    }
+    let at = r.ExceptionInformation[1];
+    if fault(at) || accessible(at, kind == 1) { -1 } else { 0 }
+}
+
+fn fault(at: usize) -> bool {
+    let armed = with(|s| {
+        let (&lo, a) = s.armed.range(..=at).next_back()?;
+        if at >= a.hi {
+            return None;
+        }
+        let a = s.armed.remove(&lo)?;
+        s.by_res.remove(&a.res);
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        Some(a)
+    });
+    let Some(a) = armed else { return false };
+    #[cfg(test)]
+    TEST_STATS[1].fetch_add(1, Ordering::Relaxed);
+    let mut opened = false;
+    let r = unsafe {
+        super::title_textures::read_back_after(a.res, &a.fence.0, a.value, || {

Critical: Not certain about this one: the VEH handler blocks the faulting thread until the title queue's native fence completes (native_queue_wait plus texture::download). If that GPU work waits on something the faulting thread itself will signal later, the thread deadlocks inside the exception handler. Say the title submits a copy into kept texture T on a queue that first does queue.Wait(fenceX, N), where fenceX is signalled from the CPU by thread A after it fills data. If A writes into one of T's pages before signalling, it faults and waits forever on a fence queued behind Wait(fenceX, N), so the title hangs. The test's round=1 avoids this only because a different thread signals the gate. A bounded wait that opens the pages with stale data (and logs) would avoid the hang.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772202902 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#discussion_r4772202902). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:29Z. **Code review location:** `crates/xcl/src/hle/d3d12x/copy_back.rs`; line 359 ~~~~diff @@ -0,0 +1,410 @@ +//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires +//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663). +//! +//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the +//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS` +//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence +//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and +//! re-tiles changed pages back into console layout. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, Once, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +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_NOACCESS, PAGE_READWRITE}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; + +fn mode_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) { + return false; + } + if !guest_write::enabled() { + crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + return false; + } + crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch"); + true + }) +} + +#[cfg(test)] +static FORCE: AtomicBool = AtomicBool::new(false); + +pub fn on() -> bool { + #[cfg(test)] + if FORCE.load(Ordering::Acquire) { + return true; + } + mode_on() +} + +/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87). +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 Shared<T>(T); +unsafe impl<T> Send for Shared<T> {} + +struct Armed { + res: usize, + lo: usize, + hi: usize, + runs: Vec<(usize, usize)>, + fence: Shared<ID3D12Fence>, + value: u64, +} + +#[derive(Default)] +struct State { + pending: HashMap<usize, Vec<usize>>, + armed: BTreeMap<usize, Armed>, + by_res: HashMap<usize, usize>, + refused: HashSet<usize>, + fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); +static ANY_ARMED: AtomicBool = AtomicBool::new(false); +static HANDLER: Once = Once::new(); +#[cfg(test)] +static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; +static ERRORS: AtomicU64 = AtomicU64::new(0); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +pub fn note_write(list: usize, res: usize) { + if !on() || list == 0 || res == 0 { + return; + } + with(|s| { + let v = s.pending.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + }); +} + +pub fn list_reset(list: usize) { + if !on() || list == 0 { + return; + } + with(|s| { + s.pending.remove(&list); + }); +} + +pub fn forget_queue(queue: usize) { + if !on() || queue == 0 { + return; + } + with(|s| { + s.fences.remove(&queue); + }); +} + +pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || queue.is_null() || lists.is_empty() { + return; + } + let textures: Vec<usize> = with(|s| { + let mut out = Vec::new(); + for &l in lists { + if let Some(v) = s.pending.get(&(l as usize)) { + for &r in v { + if !out.contains(&r) { + out.push(r); + } + } + } + } + out + }); + if textures.is_empty() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some((fence, value)) = signal(q) else { return }; + for res in textures { + arm(res, &fence, value); + } +} + +unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + let key = q.as_raw() as usize; + let (fence, value) = with(|s| { + if let Some((f, v)) = s.fences.get_mut(&key) { + *v += 1; + return Some((f.0.clone(), *v)); + } + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + s.fences.insert(key, (Shared(f.clone()), 1)); + Some((f, 1)) + })?; + super::real::native_queue_signal(q, &fence, value).ok()?; + Some((fence, value)) +} + +unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) { + let Some((va, len)) = super::title_textures::copy_back_range(res) else { return }; + let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1)); + if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) { + return; + } + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(State::default); + if s.refused.contains(&res) { + return; + } + if let Some(&at) = s.by_res.get(&res) { + if let Some(a) = s.armed.get_mut(&at) { + a.fence = Shared(fence.clone()); + a.value = value; + } + return; + } + if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() { + if other.hi > lo { + if other_lo == lo && other.hi == hi { + let old_res = other.res; + s.by_res.remove(&old_res); + if let Some(a) = s.armed.get_mut(&other_lo) { + a.res = res; + a.fence = Shared(fence.clone()); + a.value = value; + } + s.by_res.insert(res, lo); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); + } + return; + } + } + // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while + // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE. + install(); + ANY_ARMED.store(true, Ordering::Release); + if guest_write::enabled() { + guest_write::register(lo, hi - lo); + } + let runs = protect_rw_runs(lo, hi); + if runs.is_empty() { + if guest_write::enabled() { + guest_write::unregister(lo, hi - lo); + } + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + return; + } + s.by_res.insert(res, lo); + s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value }); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); +} + +unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> { + let mut runs = Vec::new(); + let mut at = lo; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE { + let n = end - at; + let done = if guest_write::enabled() { + guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS)) + } else { + protect(at, n, PAGE_NOACCESS) + }; + if done { + runs.push((at, n)); + } + } + at = end; + } + runs +} + +unsafe fn protect(a: usize, n: usize, p: u32) -> bool { + let mut old = 0; + VirtualProtect(a as *const c_void, n, p, &mut old) != 0 +} + +unsafe fn open_runs(runs: &[(usize, usize)]) { + for &(a, n) in runs { + let mut at = a; + let hi = a + n; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_NOACCESS { + let _ = protect(at, end - at, PAGE_READWRITE); + } + at = end; + } + } +} + +/// Disarm armed entries overlapping `[va, va + len)` before eager `publish_download` writes there. +pub(super) fn disarm_overlapping(va: usize, len: usize) { + if !ANY_ARMED.load(Ordering::Acquire) || len == 0 { + return; + } + let hi = va.saturating_add(len); + let gone: Vec<Armed> = with(|s| { + let keys: Vec<usize> = s.armed.range(..hi).filter(|(_, a)| a.hi > va).map(|(&k, _)| k).collect(); + let mut out = Vec::with_capacity(keys.len()); + for k in keys { + if let Some(a) = s.armed.remove(&k) { + s.by_res.remove(&a.res); + out.push(a); + } + } + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + out + }); + for a in gone { + disarm(&a); + } +} + +pub fn forget(res: usize) { + if !on() || res == 0 { + return; + } + let gone = with(|s| { + s.refused.remove(&res); + for v in s.pending.values_mut() { + v.retain(|&r| r != res); + } + let a = s.by_res.remove(&res).and_then(|lo| s.armed.remove(&lo)); + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + a + }); + if let Some(a) = gone { + disarm(&a); + } +} + +fn disarm(a: &Armed) { + unsafe { open_runs(&a.runs) }; + if guest_write::enabled() { + guest_write::unregister(a.lo, a.hi - a.lo); + } +} + +fn install() { + HANDLER.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + if !ANY_ARMED.load(Ordering::Acquire) { + return 0; + } + let r = &*(*info).ExceptionRecord; + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 { + return 0; + } + let kind = r.ExceptionInformation[0]; + if kind != 0 && kind != 1 { + return 0; + } + let at = r.ExceptionInformation[1]; + if fault(at) || accessible(at, kind == 1) { -1 } else { 0 } +} + +fn fault(at: usize) -> bool { + let armed = with(|s| { + let (&lo, a) = s.armed.range(..=at).next_back()?; + if at >= a.hi { + return None; + } + let a = s.armed.remove(&lo)?; + s.by_res.remove(&a.res); + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + Some(a) + }); + let Some(a) = armed else { return false }; + #[cfg(test)] + TEST_STATS[1].fetch_add(1, Ordering::Relaxed); + let mut opened = false; + let r = unsafe { + super::title_textures::read_back_after(a.res, &a.fence.0, a.value, || { ~~~~ --- **Critical**: Not certain about this one: the VEH handler blocks the faulting thread until the title queue's native fence completes (`native_queue_wait` plus `texture::download`). If that GPU work waits on something the faulting thread itself will signal later, the thread deadlocks inside the exception handler. Say the title submits a copy into kept texture T on a queue that first does `queue.Wait(fenceX, N)`, where fenceX is signalled from the CPU by thread A after it fills data. If A writes into one of T's pages before signalling, it faults and waits forever on a fence queued behind Wait(fenceX, N), so the title hangs. The test's round=1 avoids this only because a different thread signals the gate. A bounded wait that opens the pages with stale data (and logs) would avoid the hang.
bmjask commented 2026-12-02 15:45:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:29Z.

Code review location: crates/xcl/src/hle/d3d12x/copy_back.rs; line 234

@@ -0,0 +1,410 @@
+//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires
+//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663).
+//!
+//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the
+//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS`
+//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence
+//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and
+//! re-tiles changed pages back into console layout.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, Once, OnceLock};
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+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_NOACCESS, PAGE_READWRITE};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+
+fn mode_on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) {
+            return false;
+        }
+        if !guest_write::enabled() {
+            crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+            return false;
+        }
+        crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch");
+        true
+    })
+}
+
+#[cfg(test)]
+static FORCE: AtomicBool = AtomicBool::new(false);
+
+pub fn on() -> bool {
+    #[cfg(test)]
+    if FORCE.load(Ordering::Acquire) {
+        return true;
+    }
+    mode_on()
+}
+
+/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87).
+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 Shared<T>(T);
+unsafe impl<T> Send for Shared<T> {}
+
+struct Armed {
+    res: usize,
+    lo: usize,
+    hi: usize,
+    runs: Vec<(usize, usize)>,
+    fence: Shared<ID3D12Fence>,
+    value: u64,
+}
+
+#[derive(Default)]
+struct State {
+    pending: HashMap<usize, Vec<usize>>,
+    armed: BTreeMap<usize, Armed>,
+    by_res: HashMap<usize, usize>,
+    refused: HashSet<usize>,
+    fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static ANY_ARMED: AtomicBool = AtomicBool::new(false);
+static HANDLER: Once = Once::new();
+#[cfg(test)]
+static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)];
+static ERRORS: AtomicU64 = AtomicU64::new(0);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+pub fn note_write(list: usize, res: usize) {
+    if !on() || list == 0 || res == 0 {
+        return;
+    }
+    with(|s| {
+        let v = s.pending.entry(list).or_default();
+        if !v.contains(&res) {
+            v.push(res);
+        }
+    });
+}
+
+pub fn list_reset(list: usize) {
+    if !on() || list == 0 {
+        return;
+    }
+    with(|s| {
+        s.pending.remove(&list);
+    });
+}
+
+pub fn forget_queue(queue: usize) {
+    if !on() || queue == 0 {
+        return;
+    }
+    with(|s| {
+        s.fences.remove(&queue);
+    });
+}
+
+pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) {
+    if !on() || queue.is_null() || lists.is_empty() {
+        return;
+    }
+    let textures: Vec<usize> = with(|s| {
+        let mut out = Vec::new();
+        for &l in lists {
+            if let Some(v) = s.pending.get(&(l as usize)) {
+                for &r in v {
+                    if !out.contains(&r) {
+                        out.push(r);
+                    }
+                }
+            }
+        }
+        out
+    });
+    if textures.is_empty() {
+        return;
+    }
+    let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
+    let Some((fence, value)) = signal(q) else { return };
+    for res in textures {
+        arm(res, &fence, value);
+    }
+}
+
+unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> {
+    let key = q.as_raw() as usize;
+    let (fence, value) = with(|s| {
+        if let Some((f, v)) = s.fences.get_mut(&key) {
+            *v += 1;
+            return Some((f.0.clone(), *v));
+        }
+        let mut dev: Option<ID3D12Device> = None;
+        q.GetDevice(&mut dev).ok()?;
+        let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
+        s.fences.insert(key, (Shared(f.clone()), 1));
+        Some((f, 1))
+    })?;
+    super::real::native_queue_signal(q, &fence, value).ok()?;
+    Some((fence, value))
+}
+
+unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) {
+    let Some((va, len)) = super::title_textures::copy_back_range(res) else { return };
+    let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1));
+    if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) {
+        return;
+    }
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let s = g.get_or_insert_with(State::default);
+    if s.refused.contains(&res) {
+        return;
+    }
+    if let Some(&at) = s.by_res.get(&res) {
+        if let Some(a) = s.armed.get_mut(&at) {
+            a.fence = Shared(fence.clone());
+            a.value = value;
+        }
+        return;
+    }
+    if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() {
+        if other.hi > lo {
+            if other_lo == lo && other.hi == hi {
+                let old_res = other.res;
+                s.by_res.remove(&old_res);
+                if let Some(a) = s.armed.get_mut(&other_lo) {
+                    a.res = res;
+                    a.fence = Shared(fence.clone());
+                    a.value = value;
+                }
+                s.by_res.insert(res, lo);
+                #[cfg(test)]
+                TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+            }
+            return;
+        }
+    }
+    // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while
+    // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE.
+    install();
+    ANY_ARMED.store(true, Ordering::Release);
+    if guest_write::enabled() {
+        guest_write::register(lo, hi - lo);
+    }
+    let runs = protect_rw_runs(lo, hi);
+    if runs.is_empty() {
+        if guest_write::enabled() {
+            guest_write::unregister(lo, hi - lo);
+        }
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        return;
+    }
+    s.by_res.insert(res, lo);
+    s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value });
+    #[cfg(test)]
+    TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+}
+
+unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> {
+    let mut runs = Vec::new();
+    let mut at = lo;
+    while at < hi {
+        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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+        if end <= at {
+            break;
+        }
+        if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE {
+            let n = end - at;
+            let done = if guest_write::enabled() {
+                guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS))

High: Armed pages are PAGE_NOACCESS for reads too, but guest_write only brackets kernel and XCL writes. Kernel reads (a title WriteFile/send from texture memory) and XCL's ReadProcessMemory-based read_committed / with_title_bytes never fault, so they fail or read zero-filled holes instead of triggering copy-back. A title saving a GPU-rendered kept texture with WriteFile(buffer = texture VA) gets ERROR_NOACCESS. An XCL refresh or upload that reads an overlapping CPU-watched resource gets zeros for armed pages and can upload them over the GPU copy.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772202916 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#discussion_r4772202916). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:29Z. **Code review location:** `crates/xcl/src/hle/d3d12x/copy_back.rs`; line 234 ~~~~diff @@ -0,0 +1,410 @@ +//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires +//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663). +//! +//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the +//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS` +//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence +//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and +//! re-tiles changed pages back into console layout. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, Once, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +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_NOACCESS, PAGE_READWRITE}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; + +fn mode_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) { + return false; + } + if !guest_write::enabled() { + crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + return false; + } + crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch"); + true + }) +} + +#[cfg(test)] +static FORCE: AtomicBool = AtomicBool::new(false); + +pub fn on() -> bool { + #[cfg(test)] + if FORCE.load(Ordering::Acquire) { + return true; + } + mode_on() +} + +/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87). +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 Shared<T>(T); +unsafe impl<T> Send for Shared<T> {} + +struct Armed { + res: usize, + lo: usize, + hi: usize, + runs: Vec<(usize, usize)>, + fence: Shared<ID3D12Fence>, + value: u64, +} + +#[derive(Default)] +struct State { + pending: HashMap<usize, Vec<usize>>, + armed: BTreeMap<usize, Armed>, + by_res: HashMap<usize, usize>, + refused: HashSet<usize>, + fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); +static ANY_ARMED: AtomicBool = AtomicBool::new(false); +static HANDLER: Once = Once::new(); +#[cfg(test)] +static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; +static ERRORS: AtomicU64 = AtomicU64::new(0); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +pub fn note_write(list: usize, res: usize) { + if !on() || list == 0 || res == 0 { + return; + } + with(|s| { + let v = s.pending.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + }); +} + +pub fn list_reset(list: usize) { + if !on() || list == 0 { + return; + } + with(|s| { + s.pending.remove(&list); + }); +} + +pub fn forget_queue(queue: usize) { + if !on() || queue == 0 { + return; + } + with(|s| { + s.fences.remove(&queue); + }); +} + +pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || queue.is_null() || lists.is_empty() { + return; + } + let textures: Vec<usize> = with(|s| { + let mut out = Vec::new(); + for &l in lists { + if let Some(v) = s.pending.get(&(l as usize)) { + for &r in v { + if !out.contains(&r) { + out.push(r); + } + } + } + } + out + }); + if textures.is_empty() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some((fence, value)) = signal(q) else { return }; + for res in textures { + arm(res, &fence, value); + } +} + +unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + let key = q.as_raw() as usize; + let (fence, value) = with(|s| { + if let Some((f, v)) = s.fences.get_mut(&key) { + *v += 1; + return Some((f.0.clone(), *v)); + } + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + s.fences.insert(key, (Shared(f.clone()), 1)); + Some((f, 1)) + })?; + super::real::native_queue_signal(q, &fence, value).ok()?; + Some((fence, value)) +} + +unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) { + let Some((va, len)) = super::title_textures::copy_back_range(res) else { return }; + let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1)); + if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) { + return; + } + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(State::default); + if s.refused.contains(&res) { + return; + } + if let Some(&at) = s.by_res.get(&res) { + if let Some(a) = s.armed.get_mut(&at) { + a.fence = Shared(fence.clone()); + a.value = value; + } + return; + } + if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() { + if other.hi > lo { + if other_lo == lo && other.hi == hi { + let old_res = other.res; + s.by_res.remove(&old_res); + if let Some(a) = s.armed.get_mut(&other_lo) { + a.res = res; + a.fence = Shared(fence.clone()); + a.value = value; + } + s.by_res.insert(res, lo); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); + } + return; + } + } + // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while + // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE. + install(); + ANY_ARMED.store(true, Ordering::Release); + if guest_write::enabled() { + guest_write::register(lo, hi - lo); + } + let runs = protect_rw_runs(lo, hi); + if runs.is_empty() { + if guest_write::enabled() { + guest_write::unregister(lo, hi - lo); + } + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + return; + } + s.by_res.insert(res, lo); + s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value }); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); +} + +unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> { + let mut runs = Vec::new(); + let mut at = lo; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE { + let n = end - at; + let done = if guest_write::enabled() { + guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS)) ~~~~ --- **High**: Armed pages are PAGE_NOACCESS for reads too, but guest_write only brackets kernel and XCL writes. Kernel reads (a title WriteFile/send from texture memory) and XCL's ReadProcessMemory-based `read_committed` / `with_title_bytes` never fault, so they fail or read zero-filled holes instead of triggering copy-back. A title saving a GPU-rendered kept texture with WriteFile(buffer = texture VA) gets ERROR_NOACCESS. An XCL refresh or upload that reads an overlapping CPU-watched resource gets zeros for armed pages and can upload them over the GPU copy.
bmjask commented 2026-12-02 15:45:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:29Z.

Code review location: crates/xcl/src/hle/d3d12x/copy_back.rs; line 231

@@ -0,0 +1,410 @@
+//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires
+//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663).
+//!
+//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the
+//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS`
+//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence
+//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and
+//! re-tiles changed pages back into console layout.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, Once, OnceLock};
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+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_NOACCESS, PAGE_READWRITE};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+
+fn mode_on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) {
+            return false;
+        }
+        if !guest_write::enabled() {
+            crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+            return false;
+        }
+        crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch");
+        true
+    })
+}
+
+#[cfg(test)]
+static FORCE: AtomicBool = AtomicBool::new(false);
+
+pub fn on() -> bool {
+    #[cfg(test)]
+    if FORCE.load(Ordering::Acquire) {
+        return true;
+    }
+    mode_on()
+}
+
+/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87).
+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 Shared<T>(T);
+unsafe impl<T> Send for Shared<T> {}
+
+struct Armed {
+    res: usize,
+    lo: usize,
+    hi: usize,
+    runs: Vec<(usize, usize)>,
+    fence: Shared<ID3D12Fence>,
+    value: u64,
+}
+
+#[derive(Default)]
+struct State {
+    pending: HashMap<usize, Vec<usize>>,
+    armed: BTreeMap<usize, Armed>,
+    by_res: HashMap<usize, usize>,
+    refused: HashSet<usize>,
+    fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static ANY_ARMED: AtomicBool = AtomicBool::new(false);
+static HANDLER: Once = Once::new();
+#[cfg(test)]
+static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)];
+static ERRORS: AtomicU64 = AtomicU64::new(0);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+pub fn note_write(list: usize, res: usize) {
+    if !on() || list == 0 || res == 0 {
+        return;
+    }
+    with(|s| {
+        let v = s.pending.entry(list).or_default();
+        if !v.contains(&res) {
+            v.push(res);
+        }
+    });
+}
+
+pub fn list_reset(list: usize) {
+    if !on() || list == 0 {
+        return;
+    }
+    with(|s| {
+        s.pending.remove(&list);
+    });
+}
+
+pub fn forget_queue(queue: usize) {
+    if !on() || queue == 0 {
+        return;
+    }
+    with(|s| {
+        s.fences.remove(&queue);
+    });
+}
+
+pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) {
+    if !on() || queue.is_null() || lists.is_empty() {
+        return;
+    }
+    let textures: Vec<usize> = with(|s| {
+        let mut out = Vec::new();
+        for &l in lists {
+            if let Some(v) = s.pending.get(&(l as usize)) {
+                for &r in v {
+                    if !out.contains(&r) {
+                        out.push(r);
+                    }
+                }
+            }
+        }
+        out
+    });
+    if textures.is_empty() {
+        return;
+    }
+    let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
+    let Some((fence, value)) = signal(q) else { return };
+    for res in textures {
+        arm(res, &fence, value);
+    }
+}
+
+unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> {
+    let key = q.as_raw() as usize;
+    let (fence, value) = with(|s| {
+        if let Some((f, v)) = s.fences.get_mut(&key) {
+            *v += 1;
+            return Some((f.0.clone(), *v));
+        }
+        let mut dev: Option<ID3D12Device> = None;
+        q.GetDevice(&mut dev).ok()?;
+        let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
+        s.fences.insert(key, (Shared(f.clone()), 1));
+        Some((f, 1))
+    })?;
+    super::real::native_queue_signal(q, &fence, value).ok()?;
+    Some((fence, value))
+}
+
+unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) {
+    let Some((va, len)) = super::title_textures::copy_back_range(res) else { return };
+    let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1));
+    if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) {
+        return;
+    }
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let s = g.get_or_insert_with(State::default);
+    if s.refused.contains(&res) {
+        return;
+    }
+    if let Some(&at) = s.by_res.get(&res) {
+        if let Some(a) = s.armed.get_mut(&at) {
+            a.fence = Shared(fence.clone());
+            a.value = value;
+        }
+        return;
+    }
+    if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() {
+        if other.hi > lo {
+            if other_lo == lo && other.hi == hi {
+                let old_res = other.res;
+                s.by_res.remove(&old_res);
+                if let Some(a) = s.armed.get_mut(&other_lo) {
+                    a.res = res;
+                    a.fence = Shared(fence.clone());
+                    a.value = value;
+                }
+                s.by_res.insert(res, lo);
+                #[cfg(test)]
+                TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+            }
+            return;
+        }
+    }
+    // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while
+    // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE.
+    install();
+    ANY_ARMED.store(true, Ordering::Release);
+    if guest_write::enabled() {
+        guest_write::register(lo, hi - lo);
+    }
+    let runs = protect_rw_runs(lo, hi);
+    if runs.is_empty() {
+        if guest_write::enabled() {
+            guest_write::unregister(lo, hi - lo);
+        }
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        return;
+    }
+    s.by_res.insert(res, lo);
+    s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value });
+    #[cfg(test)]
+    TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+}
+
+unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> {
+    let mut runs = Vec::new();
+    let mut at = lo;
+    while at < hi {
+        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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+        if end <= at {
+            break;
+        }
+        if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE {

High: arm() during an in-flight fault() or disarm_overlapping() (entry already removed, pages not yet reopened) finds the pages PAGE_NOACCESS, and protect_rw_runs skips them as non-RW, so the new GPU write is never tracked or copied back. If thread A faults on T and blocks on fence v1 while the title submits another copy into T, after_submit -> arm(T) finds no T in by_res and every page NOACCESS, so runs is empty and nothing is registered. A then reads back only up to v1 and opens the pages, so the v2 write never reaches CPU memory and later reads see stale texels with no further fault.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772202930 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#discussion_r4772202930). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:29Z. **Code review location:** `crates/xcl/src/hle/d3d12x/copy_back.rs`; line 231 ~~~~diff @@ -0,0 +1,410 @@ +//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires +//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663). +//! +//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the +//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS` +//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence +//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and +//! re-tiles changed pages back into console layout. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, Once, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +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_NOACCESS, PAGE_READWRITE}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; + +fn mode_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) { + return false; + } + if !guest_write::enabled() { + crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + return false; + } + crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch"); + true + }) +} + +#[cfg(test)] +static FORCE: AtomicBool = AtomicBool::new(false); + +pub fn on() -> bool { + #[cfg(test)] + if FORCE.load(Ordering::Acquire) { + return true; + } + mode_on() +} + +/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87). +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 Shared<T>(T); +unsafe impl<T> Send for Shared<T> {} + +struct Armed { + res: usize, + lo: usize, + hi: usize, + runs: Vec<(usize, usize)>, + fence: Shared<ID3D12Fence>, + value: u64, +} + +#[derive(Default)] +struct State { + pending: HashMap<usize, Vec<usize>>, + armed: BTreeMap<usize, Armed>, + by_res: HashMap<usize, usize>, + refused: HashSet<usize>, + fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); +static ANY_ARMED: AtomicBool = AtomicBool::new(false); +static HANDLER: Once = Once::new(); +#[cfg(test)] +static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; +static ERRORS: AtomicU64 = AtomicU64::new(0); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +pub fn note_write(list: usize, res: usize) { + if !on() || list == 0 || res == 0 { + return; + } + with(|s| { + let v = s.pending.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + }); +} + +pub fn list_reset(list: usize) { + if !on() || list == 0 { + return; + } + with(|s| { + s.pending.remove(&list); + }); +} + +pub fn forget_queue(queue: usize) { + if !on() || queue == 0 { + return; + } + with(|s| { + s.fences.remove(&queue); + }); +} + +pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || queue.is_null() || lists.is_empty() { + return; + } + let textures: Vec<usize> = with(|s| { + let mut out = Vec::new(); + for &l in lists { + if let Some(v) = s.pending.get(&(l as usize)) { + for &r in v { + if !out.contains(&r) { + out.push(r); + } + } + } + } + out + }); + if textures.is_empty() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some((fence, value)) = signal(q) else { return }; + for res in textures { + arm(res, &fence, value); + } +} + +unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + let key = q.as_raw() as usize; + let (fence, value) = with(|s| { + if let Some((f, v)) = s.fences.get_mut(&key) { + *v += 1; + return Some((f.0.clone(), *v)); + } + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + s.fences.insert(key, (Shared(f.clone()), 1)); + Some((f, 1)) + })?; + super::real::native_queue_signal(q, &fence, value).ok()?; + Some((fence, value)) +} + +unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) { + let Some((va, len)) = super::title_textures::copy_back_range(res) else { return }; + let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1)); + if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) { + return; + } + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(State::default); + if s.refused.contains(&res) { + return; + } + if let Some(&at) = s.by_res.get(&res) { + if let Some(a) = s.armed.get_mut(&at) { + a.fence = Shared(fence.clone()); + a.value = value; + } + return; + } + if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() { + if other.hi > lo { + if other_lo == lo && other.hi == hi { + let old_res = other.res; + s.by_res.remove(&old_res); + if let Some(a) = s.armed.get_mut(&other_lo) { + a.res = res; + a.fence = Shared(fence.clone()); + a.value = value; + } + s.by_res.insert(res, lo); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); + } + return; + } + } + // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while + // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE. + install(); + ANY_ARMED.store(true, Ordering::Release); + if guest_write::enabled() { + guest_write::register(lo, hi - lo); + } + let runs = protect_rw_runs(lo, hi); + if runs.is_empty() { + if guest_write::enabled() { + guest_write::unregister(lo, hi - lo); + } + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + return; + } + s.by_res.insert(res, lo); + s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value }); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); +} + +unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> { + let mut runs = Vec::new(); + let mut at = lo; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE { ~~~~ --- **High**: `arm()` during an in-flight `fault()` or `disarm_overlapping()` (entry already removed, pages not yet reopened) finds the pages PAGE_NOACCESS, and `protect_rw_runs` skips them as non-RW, so the new GPU write is never tracked or copied back. If thread A faults on T and blocks on fence v1 while the title submits another copy into T, `after_submit` -> `arm(T)` finds no T in by_res and every page NOACCESS, so `runs` is empty and nothing is registered. A then reads back only up to v1 and opens the pages, so the v2 write never reaches CPU memory and later reads see stale texels with no further fault.
bmjask commented 2026-12-02 15:45:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:29Z.

Code review location: crates/xcl/src/hle/d3d12x/copy_back.rs; line 176

@@ -0,0 +1,410 @@
+//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires
+//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663).
+//!
+//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the
+//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS`
+//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence
+//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and
+//! re-tiles changed pages back into console layout.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, Once, OnceLock};
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+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_NOACCESS, PAGE_READWRITE};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+
+fn mode_on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) {
+            return false;
+        }
+        if !guest_write::enabled() {
+            crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+            return false;
+        }
+        crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch");
+        true
+    })
+}
+
+#[cfg(test)]
+static FORCE: AtomicBool = AtomicBool::new(false);
+
+pub fn on() -> bool {
+    #[cfg(test)]
+    if FORCE.load(Ordering::Acquire) {
+        return true;
+    }
+    mode_on()
+}
+
+/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87).
+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 Shared<T>(T);
+unsafe impl<T> Send for Shared<T> {}
+
+struct Armed {
+    res: usize,
+    lo: usize,
+    hi: usize,
+    runs: Vec<(usize, usize)>,
+    fence: Shared<ID3D12Fence>,
+    value: u64,
+}
+
+#[derive(Default)]
+struct State {
+    pending: HashMap<usize, Vec<usize>>,
+    armed: BTreeMap<usize, Armed>,
+    by_res: HashMap<usize, usize>,
+    refused: HashSet<usize>,
+    fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static ANY_ARMED: AtomicBool = AtomicBool::new(false);
+static HANDLER: Once = Once::new();
+#[cfg(test)]
+static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)];
+static ERRORS: AtomicU64 = AtomicU64::new(0);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+pub fn note_write(list: usize, res: usize) {
+    if !on() || list == 0 || res == 0 {
+        return;
+    }
+    with(|s| {
+        let v = s.pending.entry(list).or_default();
+        if !v.contains(&res) {
+            v.push(res);
+        }
+    });
+}
+
+pub fn list_reset(list: usize) {
+    if !on() || list == 0 {
+        return;
+    }
+    with(|s| {
+        s.pending.remove(&list);
+    });
+}
+
+pub fn forget_queue(queue: usize) {
+    if !on() || queue == 0 {
+        return;
+    }
+    with(|s| {
+        s.fences.remove(&queue);
+    });
+}
+
+pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) {
+    if !on() || queue.is_null() || lists.is_empty() {
+        return;
+    }
+    let textures: Vec<usize> = with(|s| {
+        let mut out = Vec::new();
+        for &l in lists {
+            if let Some(v) = s.pending.get(&(l as usize)) {
+                for &r in v {
+                    if !out.contains(&r) {
+                        out.push(r);
+                    }
+                }
+            }
+        }
+        out
+    });
+    if textures.is_empty() {
+        return;
+    }
+    let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
+    let Some((fence, value)) = signal(q) else { return };
+    for res in textures {
+        arm(res, &fence, value);
+    }
+}
+
+unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> {
+    let key = q.as_raw() as usize;
+    let (fence, value) = with(|s| {
+        if let Some((f, v)) = s.fences.get_mut(&key) {
+            *v += 1;
+            return Some((f.0.clone(), *v));
+        }
+        let mut dev: Option<ID3D12Device> = None;
+        q.GetDevice(&mut dev).ok()?;
+        let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
+        s.fences.insert(key, (Shared(f.clone()), 1));
+        Some((f, 1))
+    })?;
+    super::real::native_queue_signal(q, &fence, value).ok()?;
+    Some((fence, value))
+}
+
+unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) {
+    let Some((va, len)) = super::title_textures::copy_back_range(res) else { return };
+    let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1));
+    if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) {
+        return;
+    }
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let s = g.get_or_insert_with(State::default);
+    if s.refused.contains(&res) {
+        return;
+    }
+    if let Some(&at) = s.by_res.get(&res) {
+        if let Some(a) = s.armed.get_mut(&at) {
+            a.fence = Shared(fence.clone());

High: Re-arming an already-armed texture replaces its (fence, value) with the latest submit's, so when the latest write is on a different queue the readback waits only on that queue and can read before an earlier write on the first queue finishes. If a long compute-queue copy writes T (armed with computeFence=5) and a quick direct-queue copy then writes another subresource of T (replaced with directFence=9), a CPU read faults, waits only for directFence >= 9, and downloads T while the compute write is still running. Keeping one (fence, value) per queue and waiting on all of them would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772202947 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#discussion_r4772202947). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:29Z. **Code review location:** `crates/xcl/src/hle/d3d12x/copy_back.rs`; line 176 ~~~~diff @@ -0,0 +1,410 @@ +//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires +//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663). +//! +//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the +//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS` +//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence +//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and +//! re-tiles changed pages back into console layout. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, Once, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +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_NOACCESS, PAGE_READWRITE}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; + +fn mode_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) { + return false; + } + if !guest_write::enabled() { + crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + return false; + } + crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch"); + true + }) +} + +#[cfg(test)] +static FORCE: AtomicBool = AtomicBool::new(false); + +pub fn on() -> bool { + #[cfg(test)] + if FORCE.load(Ordering::Acquire) { + return true; + } + mode_on() +} + +/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87). +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 Shared<T>(T); +unsafe impl<T> Send for Shared<T> {} + +struct Armed { + res: usize, + lo: usize, + hi: usize, + runs: Vec<(usize, usize)>, + fence: Shared<ID3D12Fence>, + value: u64, +} + +#[derive(Default)] +struct State { + pending: HashMap<usize, Vec<usize>>, + armed: BTreeMap<usize, Armed>, + by_res: HashMap<usize, usize>, + refused: HashSet<usize>, + fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); +static ANY_ARMED: AtomicBool = AtomicBool::new(false); +static HANDLER: Once = Once::new(); +#[cfg(test)] +static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; +static ERRORS: AtomicU64 = AtomicU64::new(0); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +pub fn note_write(list: usize, res: usize) { + if !on() || list == 0 || res == 0 { + return; + } + with(|s| { + let v = s.pending.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + }); +} + +pub fn list_reset(list: usize) { + if !on() || list == 0 { + return; + } + with(|s| { + s.pending.remove(&list); + }); +} + +pub fn forget_queue(queue: usize) { + if !on() || queue == 0 { + return; + } + with(|s| { + s.fences.remove(&queue); + }); +} + +pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || queue.is_null() || lists.is_empty() { + return; + } + let textures: Vec<usize> = with(|s| { + let mut out = Vec::new(); + for &l in lists { + if let Some(v) = s.pending.get(&(l as usize)) { + for &r in v { + if !out.contains(&r) { + out.push(r); + } + } + } + } + out + }); + if textures.is_empty() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some((fence, value)) = signal(q) else { return }; + for res in textures { + arm(res, &fence, value); + } +} + +unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + let key = q.as_raw() as usize; + let (fence, value) = with(|s| { + if let Some((f, v)) = s.fences.get_mut(&key) { + *v += 1; + return Some((f.0.clone(), *v)); + } + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + s.fences.insert(key, (Shared(f.clone()), 1)); + Some((f, 1)) + })?; + super::real::native_queue_signal(q, &fence, value).ok()?; + Some((fence, value)) +} + +unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) { + let Some((va, len)) = super::title_textures::copy_back_range(res) else { return }; + let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1)); + if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) { + return; + } + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(State::default); + if s.refused.contains(&res) { + return; + } + if let Some(&at) = s.by_res.get(&res) { + if let Some(a) = s.armed.get_mut(&at) { + a.fence = Shared(fence.clone()); ~~~~ --- **High**: Re-arming an already-armed texture replaces its (fence, value) with the latest submit's, so when the latest write is on a different queue the readback waits only on that queue and can read before an earlier write on the first queue finishes. If a long compute-queue copy writes T (armed with computeFence=5) and a quick direct-queue copy then writes another subresource of T (replaced with directFence=9), a CPU read faults, waits only for directFence >= 9, and downloads T while the compute write is still running. Keeping one (fence, value) per queue and waiting on all of them would fix it.
bmjask commented 2026-12-02 15:45:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:29Z.

Code review location: crates/xcl/src/hle/d3d12x/copy_back.rs; line 181

@@ -0,0 +1,410 @@
+//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires
+//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663).
+//!
+//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the
+//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS`
+//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence
+//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and
+//! re-tiles changed pages back into console layout.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, Once, OnceLock};
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+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_NOACCESS, PAGE_READWRITE};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+
+fn mode_on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) {
+            return false;
+        }
+        if !guest_write::enabled() {
+            crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+            return false;
+        }
+        crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch");
+        true
+    })
+}
+
+#[cfg(test)]
+static FORCE: AtomicBool = AtomicBool::new(false);
+
+pub fn on() -> bool {
+    #[cfg(test)]
+    if FORCE.load(Ordering::Acquire) {
+        return true;
+    }
+    mode_on()
+}
+
+/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87).
+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 Shared<T>(T);
+unsafe impl<T> Send for Shared<T> {}
+
+struct Armed {
+    res: usize,
+    lo: usize,
+    hi: usize,
+    runs: Vec<(usize, usize)>,
+    fence: Shared<ID3D12Fence>,
+    value: u64,
+}
+
+#[derive(Default)]
+struct State {
+    pending: HashMap<usize, Vec<usize>>,
+    armed: BTreeMap<usize, Armed>,
+    by_res: HashMap<usize, usize>,
+    refused: HashSet<usize>,
+    fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static ANY_ARMED: AtomicBool = AtomicBool::new(false);
+static HANDLER: Once = Once::new();
+#[cfg(test)]
+static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)];
+static ERRORS: AtomicU64 = AtomicU64::new(0);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+pub fn note_write(list: usize, res: usize) {
+    if !on() || list == 0 || res == 0 {
+        return;
+    }
+    with(|s| {
+        let v = s.pending.entry(list).or_default();
+        if !v.contains(&res) {
+            v.push(res);
+        }
+    });
+}
+
+pub fn list_reset(list: usize) {
+    if !on() || list == 0 {
+        return;
+    }
+    with(|s| {
+        s.pending.remove(&list);
+    });
+}
+
+pub fn forget_queue(queue: usize) {
+    if !on() || queue == 0 {
+        return;
+    }
+    with(|s| {
+        s.fences.remove(&queue);
+    });
+}
+
+pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) {
+    if !on() || queue.is_null() || lists.is_empty() {
+        return;
+    }
+    let textures: Vec<usize> = with(|s| {
+        let mut out = Vec::new();
+        for &l in lists {
+            if let Some(v) = s.pending.get(&(l as usize)) {
+                for &r in v {
+                    if !out.contains(&r) {
+                        out.push(r);
+                    }
+                }
+            }
+        }
+        out
+    });
+    if textures.is_empty() {
+        return;
+    }
+    let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
+    let Some((fence, value)) = signal(q) else { return };
+    for res in textures {
+        arm(res, &fence, value);
+    }
+}
+
+unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> {
+    let key = q.as_raw() as usize;
+    let (fence, value) = with(|s| {
+        if let Some((f, v)) = s.fences.get_mut(&key) {
+            *v += 1;
+            return Some((f.0.clone(), *v));
+        }
+        let mut dev: Option<ID3D12Device> = None;
+        q.GetDevice(&mut dev).ok()?;
+        let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
+        s.fences.insert(key, (Shared(f.clone()), 1));
+        Some((f, 1))
+    })?;
+    super::real::native_queue_signal(q, &fence, value).ok()?;
+    Some((fence, value))
+}
+
+unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) {
+    let Some((va, len)) = super::title_textures::copy_back_range(res) else { return };
+    let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1));
+    if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) {
+        return;
+    }
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let s = g.get_or_insert_with(State::default);
+    if s.refused.contains(&res) {
+        return;
+    }
+    if let Some(&at) = s.by_res.get(&res) {
+        if let Some(a) = s.armed.get_mut(&at) {
+            a.fence = Shared(fence.clone());
+            a.value = value;
+        }
+        return;
+    }
+    if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() {

High: A new texture whose range partially overlaps an armed one is silently not armed, and an exact-range overlap re-labels the entry to the new res, so aliased placed textures either lose copy-back or read back the wrong resource's texels. With placed A=[0x10000,0x30000) and B=[0x20000,0x40000) aliasing one heap, the GPU writes A (armed) then B, and arm(B) sees the overlap and returns. A CPU read in B's range faults on A's entry and re-tiles A's stale GPU contents over the shared pages, B's newer texels never reach the CPU, and B's non-overlapping pages are never protected.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772202961 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#discussion_r4772202961). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:29Z. **Code review location:** `crates/xcl/src/hle/d3d12x/copy_back.rs`; line 181 ~~~~diff @@ -0,0 +1,410 @@ +//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires +//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663). +//! +//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the +//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS` +//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence +//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and +//! re-tiles changed pages back into console layout. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, Once, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +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_NOACCESS, PAGE_READWRITE}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; + +fn mode_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) { + return false; + } + if !guest_write::enabled() { + crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + return false; + } + crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch"); + true + }) +} + +#[cfg(test)] +static FORCE: AtomicBool = AtomicBool::new(false); + +pub fn on() -> bool { + #[cfg(test)] + if FORCE.load(Ordering::Acquire) { + return true; + } + mode_on() +} + +/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87). +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 Shared<T>(T); +unsafe impl<T> Send for Shared<T> {} + +struct Armed { + res: usize, + lo: usize, + hi: usize, + runs: Vec<(usize, usize)>, + fence: Shared<ID3D12Fence>, + value: u64, +} + +#[derive(Default)] +struct State { + pending: HashMap<usize, Vec<usize>>, + armed: BTreeMap<usize, Armed>, + by_res: HashMap<usize, usize>, + refused: HashSet<usize>, + fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); +static ANY_ARMED: AtomicBool = AtomicBool::new(false); +static HANDLER: Once = Once::new(); +#[cfg(test)] +static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; +static ERRORS: AtomicU64 = AtomicU64::new(0); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +pub fn note_write(list: usize, res: usize) { + if !on() || list == 0 || res == 0 { + return; + } + with(|s| { + let v = s.pending.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + }); +} + +pub fn list_reset(list: usize) { + if !on() || list == 0 { + return; + } + with(|s| { + s.pending.remove(&list); + }); +} + +pub fn forget_queue(queue: usize) { + if !on() || queue == 0 { + return; + } + with(|s| { + s.fences.remove(&queue); + }); +} + +pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || queue.is_null() || lists.is_empty() { + return; + } + let textures: Vec<usize> = with(|s| { + let mut out = Vec::new(); + for &l in lists { + if let Some(v) = s.pending.get(&(l as usize)) { + for &r in v { + if !out.contains(&r) { + out.push(r); + } + } + } + } + out + }); + if textures.is_empty() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some((fence, value)) = signal(q) else { return }; + for res in textures { + arm(res, &fence, value); + } +} + +unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + let key = q.as_raw() as usize; + let (fence, value) = with(|s| { + if let Some((f, v)) = s.fences.get_mut(&key) { + *v += 1; + return Some((f.0.clone(), *v)); + } + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + s.fences.insert(key, (Shared(f.clone()), 1)); + Some((f, 1)) + })?; + super::real::native_queue_signal(q, &fence, value).ok()?; + Some((fence, value)) +} + +unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) { + let Some((va, len)) = super::title_textures::copy_back_range(res) else { return }; + let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1)); + if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) { + return; + } + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(State::default); + if s.refused.contains(&res) { + return; + } + if let Some(&at) = s.by_res.get(&res) { + if let Some(a) = s.armed.get_mut(&at) { + a.fence = Shared(fence.clone()); + a.value = value; + } + return; + } + if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() { ~~~~ --- **High**: A new texture whose range partially overlaps an armed one is silently not armed, and an exact-range overlap re-labels the entry to the new res, so aliased placed textures either lose copy-back or read back the wrong resource's texels. With placed A=[0x10000,0x30000) and B=[0x20000,0x40000) aliasing one heap, the GPU writes A (armed) then B, and `arm(B)` sees the overlap and returns. A CPU read in B's range faults on A's entry and re-tiles A's stale GPU contents over the shared pages, B's newer texels never reach the CPU, and B's non-overlapping pages are never protected.
bmjask commented 2026-12-02 15:45:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:29Z.

Code review location: crates/xcl/src/hle/d3d12x/copy_back.rs; line 280

@@ -0,0 +1,410 @@
+//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires
+//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663).
+//!
+//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the
+//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS`
+//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence
+//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and
+//! re-tiles changed pages back into console layout.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, Once, OnceLock};
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+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_NOACCESS, PAGE_READWRITE};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+
+fn mode_on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) {
+            return false;
+        }
+        if !guest_write::enabled() {
+            crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+            return false;
+        }
+        crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch");
+        true
+    })
+}
+
+#[cfg(test)]
+static FORCE: AtomicBool = AtomicBool::new(false);
+
+pub fn on() -> bool {
+    #[cfg(test)]
+    if FORCE.load(Ordering::Acquire) {
+        return true;
+    }
+    mode_on()
+}
+
+/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87).
+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 Shared<T>(T);
+unsafe impl<T> Send for Shared<T> {}
+
+struct Armed {
+    res: usize,
+    lo: usize,
+    hi: usize,
+    runs: Vec<(usize, usize)>,
+    fence: Shared<ID3D12Fence>,
+    value: u64,
+}
+
+#[derive(Default)]
+struct State {
+    pending: HashMap<usize, Vec<usize>>,
+    armed: BTreeMap<usize, Armed>,
+    by_res: HashMap<usize, usize>,
+    refused: HashSet<usize>,
+    fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static ANY_ARMED: AtomicBool = AtomicBool::new(false);
+static HANDLER: Once = Once::new();
+#[cfg(test)]
+static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)];
+static ERRORS: AtomicU64 = AtomicU64::new(0);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+pub fn note_write(list: usize, res: usize) {
+    if !on() || list == 0 || res == 0 {
+        return;
+    }
+    with(|s| {
+        let v = s.pending.entry(list).or_default();
+        if !v.contains(&res) {
+            v.push(res);
+        }
+    });
+}
+
+pub fn list_reset(list: usize) {
+    if !on() || list == 0 {
+        return;
+    }
+    with(|s| {
+        s.pending.remove(&list);
+    });
+}
+
+pub fn forget_queue(queue: usize) {
+    if !on() || queue == 0 {
+        return;
+    }
+    with(|s| {
+        s.fences.remove(&queue);
+    });
+}
+
+pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) {
+    if !on() || queue.is_null() || lists.is_empty() {
+        return;
+    }
+    let textures: Vec<usize> = with(|s| {
+        let mut out = Vec::new();
+        for &l in lists {
+            if let Some(v) = s.pending.get(&(l as usize)) {
+                for &r in v {
+                    if !out.contains(&r) {
+                        out.push(r);
+                    }
+                }
+            }
+        }
+        out
+    });
+    if textures.is_empty() {
+        return;
+    }
+    let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
+    let Some((fence, value)) = signal(q) else { return };
+    for res in textures {
+        arm(res, &fence, value);
+    }
+}
+
+unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> {
+    let key = q.as_raw() as usize;
+    let (fence, value) = with(|s| {
+        if let Some((f, v)) = s.fences.get_mut(&key) {
+            *v += 1;
+            return Some((f.0.clone(), *v));
+        }
+        let mut dev: Option<ID3D12Device> = None;
+        q.GetDevice(&mut dev).ok()?;
+        let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
+        s.fences.insert(key, (Shared(f.clone()), 1));
+        Some((f, 1))
+    })?;
+    super::real::native_queue_signal(q, &fence, value).ok()?;
+    Some((fence, value))
+}
+
+unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) {
+    let Some((va, len)) = super::title_textures::copy_back_range(res) else { return };
+    let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1));
+    if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) {
+        return;
+    }
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let s = g.get_or_insert_with(State::default);
+    if s.refused.contains(&res) {
+        return;
+    }
+    if let Some(&at) = s.by_res.get(&res) {
+        if let Some(a) = s.armed.get_mut(&at) {
+            a.fence = Shared(fence.clone());
+            a.value = value;
+        }
+        return;
+    }
+    if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() {
+        if other.hi > lo {
+            if other_lo == lo && other.hi == hi {
+                let old_res = other.res;
+                s.by_res.remove(&old_res);
+                if let Some(a) = s.armed.get_mut(&other_lo) {
+                    a.res = res;
+                    a.fence = Shared(fence.clone());
+                    a.value = value;
+                }
+                s.by_res.insert(res, lo);
+                #[cfg(test)]
+                TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+            }
+            return;
+        }
+    }
+    // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while
+    // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE.
+    install();
+    ANY_ARMED.store(true, Ordering::Release);
+    if guest_write::enabled() {
+        guest_write::register(lo, hi - lo);
+    }
+    let runs = protect_rw_runs(lo, hi);
+    if runs.is_empty() {
+        if guest_write::enabled() {
+            guest_write::unregister(lo, hi - lo);
+        }
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        return;
+    }
+    s.by_res.insert(res, lo);
+    s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value });
+    #[cfg(test)]
+    TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+}
+
+unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> {
+    let mut runs = Vec::new();
+    let mut at = lo;
+    while at < hi {
+        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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+        if end <= at {
+            break;
+        }
+        if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE {
+            let n = end - at;
+            let done = if guest_write::enabled() {
+                guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS))
+            } else {
+                protect(at, n, PAGE_NOACCESS)
+            };
+            if done {
+                runs.push((at, n));
+            }
+        }
+        at = end;
+    }
+    runs
+}
+
+unsafe fn protect(a: usize, n: usize, p: u32) -> bool {
+    let mut old = 0;
+    VirtualProtect(a as *const c_void, n, p, &mut old) != 0
+}
+
+unsafe fn open_runs(runs: &[(usize, usize)]) {
+    for &(a, n) in runs {
+        let mut at = a;
+        let hi = a + n;
+        while at < hi {
+            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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+            if end <= at {
+                break;
+            }
+            if m.State == MEM_COMMIT && m.Protect == PAGE_NOACCESS {
+                let _ = protect(at, end - at, PAGE_READWRITE);
+            }
+            at = end;
+        }
+    }
+}
+
+/// Disarm armed entries overlapping `[va, va + len)` before eager `publish_download` writes there.
+pub(super) fn disarm_overlapping(va: usize, len: usize) {
+    if !ANY_ARMED.load(Ordering::Acquire) || len == 0 {
+        return;
+    }
+    let hi = va.saturating_add(len);
+    let gone: Vec<Armed> = with(|s| {
+        let keys: Vec<usize> = s.armed.range(..hi).filter(|(_, a)| a.hi > va).map(|(&k, _)| k).collect();

High: disarm_overlapping drops every armed entry overlapping the download target and reopens its whole range without reading back, so GPU writes of an overlapping texture outside the eager download's bytes are lost. If kept texture T (armed, GPU-written, 1 MiB) overlaps a smaller eager publish_download target at T's first 64 KiB, disarm_overlapping reopens all of T's runs, the download fills only the 64 KiB, and CPU reads of T's other pages return pre-GPU contents with no fault. Reading back T first, or reopening only the download's pages, would avoid it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772202980 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#discussion_r4772202980). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:29Z. **Code review location:** `crates/xcl/src/hle/d3d12x/copy_back.rs`; line 280 ~~~~diff @@ -0,0 +1,410 @@ +//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires +//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663). +//! +//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the +//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS` +//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence +//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and +//! re-tiles changed pages back into console layout. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, Once, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +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_NOACCESS, PAGE_READWRITE}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; + +fn mode_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) { + return false; + } + if !guest_write::enabled() { + crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + return false; + } + crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch"); + true + }) +} + +#[cfg(test)] +static FORCE: AtomicBool = AtomicBool::new(false); + +pub fn on() -> bool { + #[cfg(test)] + if FORCE.load(Ordering::Acquire) { + return true; + } + mode_on() +} + +/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87). +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 Shared<T>(T); +unsafe impl<T> Send for Shared<T> {} + +struct Armed { + res: usize, + lo: usize, + hi: usize, + runs: Vec<(usize, usize)>, + fence: Shared<ID3D12Fence>, + value: u64, +} + +#[derive(Default)] +struct State { + pending: HashMap<usize, Vec<usize>>, + armed: BTreeMap<usize, Armed>, + by_res: HashMap<usize, usize>, + refused: HashSet<usize>, + fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); +static ANY_ARMED: AtomicBool = AtomicBool::new(false); +static HANDLER: Once = Once::new(); +#[cfg(test)] +static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; +static ERRORS: AtomicU64 = AtomicU64::new(0); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +pub fn note_write(list: usize, res: usize) { + if !on() || list == 0 || res == 0 { + return; + } + with(|s| { + let v = s.pending.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + }); +} + +pub fn list_reset(list: usize) { + if !on() || list == 0 { + return; + } + with(|s| { + s.pending.remove(&list); + }); +} + +pub fn forget_queue(queue: usize) { + if !on() || queue == 0 { + return; + } + with(|s| { + s.fences.remove(&queue); + }); +} + +pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || queue.is_null() || lists.is_empty() { + return; + } + let textures: Vec<usize> = with(|s| { + let mut out = Vec::new(); + for &l in lists { + if let Some(v) = s.pending.get(&(l as usize)) { + for &r in v { + if !out.contains(&r) { + out.push(r); + } + } + } + } + out + }); + if textures.is_empty() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some((fence, value)) = signal(q) else { return }; + for res in textures { + arm(res, &fence, value); + } +} + +unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + let key = q.as_raw() as usize; + let (fence, value) = with(|s| { + if let Some((f, v)) = s.fences.get_mut(&key) { + *v += 1; + return Some((f.0.clone(), *v)); + } + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + s.fences.insert(key, (Shared(f.clone()), 1)); + Some((f, 1)) + })?; + super::real::native_queue_signal(q, &fence, value).ok()?; + Some((fence, value)) +} + +unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) { + let Some((va, len)) = super::title_textures::copy_back_range(res) else { return }; + let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1)); + if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) { + return; + } + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(State::default); + if s.refused.contains(&res) { + return; + } + if let Some(&at) = s.by_res.get(&res) { + if let Some(a) = s.armed.get_mut(&at) { + a.fence = Shared(fence.clone()); + a.value = value; + } + return; + } + if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() { + if other.hi > lo { + if other_lo == lo && other.hi == hi { + let old_res = other.res; + s.by_res.remove(&old_res); + if let Some(a) = s.armed.get_mut(&other_lo) { + a.res = res; + a.fence = Shared(fence.clone()); + a.value = value; + } + s.by_res.insert(res, lo); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); + } + return; + } + } + // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while + // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE. + install(); + ANY_ARMED.store(true, Ordering::Release); + if guest_write::enabled() { + guest_write::register(lo, hi - lo); + } + let runs = protect_rw_runs(lo, hi); + if runs.is_empty() { + if guest_write::enabled() { + guest_write::unregister(lo, hi - lo); + } + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + return; + } + s.by_res.insert(res, lo); + s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value }); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); +} + +unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> { + let mut runs = Vec::new(); + let mut at = lo; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE { + let n = end - at; + let done = if guest_write::enabled() { + guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS)) + } else { + protect(at, n, PAGE_NOACCESS) + }; + if done { + runs.push((at, n)); + } + } + at = end; + } + runs +} + +unsafe fn protect(a: usize, n: usize, p: u32) -> bool { + let mut old = 0; + VirtualProtect(a as *const c_void, n, p, &mut old) != 0 +} + +unsafe fn open_runs(runs: &[(usize, usize)]) { + for &(a, n) in runs { + let mut at = a; + let hi = a + n; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_NOACCESS { + let _ = protect(at, end - at, PAGE_READWRITE); + } + at = end; + } + } +} + +/// Disarm armed entries overlapping `[va, va + len)` before eager `publish_download` writes there. +pub(super) fn disarm_overlapping(va: usize, len: usize) { + if !ANY_ARMED.load(Ordering::Acquire) || len == 0 { + return; + } + let hi = va.saturating_add(len); + let gone: Vec<Armed> = with(|s| { + let keys: Vec<usize> = s.armed.range(..hi).filter(|(_, a)| a.hi > va).map(|(&k, _)| k).collect(); ~~~~ --- **High**: `disarm_overlapping` drops every armed entry overlapping the download target and reopens its whole range without reading back, so GPU writes of an overlapping texture outside the eager download's bytes are lost. If kept texture T (armed, GPU-written, 1 MiB) overlaps a smaller eager `publish_download` target at T's first 64 KiB, `disarm_overlapping` reopens all of T's runs, the download fills only the 64 KiB, and CPU reads of T's other pages return pre-GPU contents with no fault. Reading back T first, or reopening only the download's pages, would avoid it.
bmjask commented 2026-12-02 15:45:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:29Z.

Code review location: crates/xcl/src/hle/d3d12x/copy_back.rs; line 378

@@ -0,0 +1,410 @@
+//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires
+//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663).
+//!
+//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the
+//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS`
+//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence
+//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and
+//! re-tiles changed pages back into console layout.
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, Once, OnceLock};
+
+use windows::core::Interface;
+use windows::Win32::Graphics::Direct3D12::*;
+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_NOACCESS, PAGE_READWRITE};
+
+use crate::hle::kernelx::guest_write;
+
+const PAGE: usize = 0x1000;
+
+fn mode_on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) {
+            return false;
+        }
+        if !guest_write::enabled() {
+            crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first");
+            return false;
+        }
+        crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch");
+        true
+    })
+}
+
+#[cfg(test)]
+static FORCE: AtomicBool = AtomicBool::new(false);
+
+pub fn on() -> bool {
+    #[cfg(test)]
+    if FORCE.load(Ordering::Acquire) {
+        return true;
+    }
+    mode_on()
+}
+
+/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87).
+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 Shared<T>(T);
+unsafe impl<T> Send for Shared<T> {}
+
+struct Armed {
+    res: usize,
+    lo: usize,
+    hi: usize,
+    runs: Vec<(usize, usize)>,
+    fence: Shared<ID3D12Fence>,
+    value: u64,
+}
+
+#[derive(Default)]
+struct State {
+    pending: HashMap<usize, Vec<usize>>,
+    armed: BTreeMap<usize, Armed>,
+    by_res: HashMap<usize, usize>,
+    refused: HashSet<usize>,
+    fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+static ANY_ARMED: AtomicBool = AtomicBool::new(false);
+static HANDLER: Once = Once::new();
+#[cfg(test)]
+static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)];
+static ERRORS: AtomicU64 = AtomicU64::new(0);
+
+fn with<R>(f: impl FnOnce(&mut State) -> R) -> R {
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    f(g.get_or_insert_with(State::default))
+}
+
+pub fn note_write(list: usize, res: usize) {
+    if !on() || list == 0 || res == 0 {
+        return;
+    }
+    with(|s| {
+        let v = s.pending.entry(list).or_default();
+        if !v.contains(&res) {
+            v.push(res);
+        }
+    });
+}
+
+pub fn list_reset(list: usize) {
+    if !on() || list == 0 {
+        return;
+    }
+    with(|s| {
+        s.pending.remove(&list);
+    });
+}
+
+pub fn forget_queue(queue: usize) {
+    if !on() || queue == 0 {
+        return;
+    }
+    with(|s| {
+        s.fences.remove(&queue);
+    });
+}
+
+pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) {
+    if !on() || queue.is_null() || lists.is_empty() {
+        return;
+    }
+    let textures: Vec<usize> = with(|s| {
+        let mut out = Vec::new();
+        for &l in lists {
+            if let Some(v) = s.pending.get(&(l as usize)) {
+                for &r in v {
+                    if !out.contains(&r) {
+                        out.push(r);
+                    }
+                }
+            }
+        }
+        out
+    });
+    if textures.is_empty() {
+        return;
+    }
+    let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return };
+    let Some((fence, value)) = signal(q) else { return };
+    for res in textures {
+        arm(res, &fence, value);
+    }
+}
+
+unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> {
+    let key = q.as_raw() as usize;
+    let (fence, value) = with(|s| {
+        if let Some((f, v)) = s.fences.get_mut(&key) {
+            *v += 1;
+            return Some((f.0.clone(), *v));
+        }
+        let mut dev: Option<ID3D12Device> = None;
+        q.GetDevice(&mut dev).ok()?;
+        let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
+        s.fences.insert(key, (Shared(f.clone()), 1));
+        Some((f, 1))
+    })?;
+    super::real::native_queue_signal(q, &fence, value).ok()?;
+    Some((fence, value))
+}
+
+unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) {
+    let Some((va, len)) = super::title_textures::copy_back_range(res) else { return };
+    let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1));
+    if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) {
+        return;
+    }
+    let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner());
+    let s = g.get_or_insert_with(State::default);
+    if s.refused.contains(&res) {
+        return;
+    }
+    if let Some(&at) = s.by_res.get(&res) {
+        if let Some(a) = s.armed.get_mut(&at) {
+            a.fence = Shared(fence.clone());
+            a.value = value;
+        }
+        return;
+    }
+    if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() {
+        if other.hi > lo {
+            if other_lo == lo && other.hi == hi {
+                let old_res = other.res;
+                s.by_res.remove(&old_res);
+                if let Some(a) = s.armed.get_mut(&other_lo) {
+                    a.res = res;
+                    a.fence = Shared(fence.clone());
+                    a.value = value;
+                }
+                s.by_res.insert(res, lo);
+                #[cfg(test)]
+                TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+            }
+            return;
+        }
+    }
+    // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while
+    // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE.
+    install();
+    ANY_ARMED.store(true, Ordering::Release);
+    if guest_write::enabled() {
+        guest_write::register(lo, hi - lo);
+    }
+    let runs = protect_rw_runs(lo, hi);
+    if runs.is_empty() {
+        if guest_write::enabled() {
+            guest_write::unregister(lo, hi - lo);
+        }
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        return;
+    }
+    s.by_res.insert(res, lo);
+    s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value });
+    #[cfg(test)]
+    TEST_STATS[0].fetch_add(1, Ordering::Relaxed);
+}
+
+unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> {
+    let mut runs = Vec::new();
+    let mut at = lo;
+    while at < hi {
+        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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+        if end <= at {
+            break;
+        }
+        if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE {
+            let n = end - at;
+            let done = if guest_write::enabled() {
+                guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS))
+            } else {
+                protect(at, n, PAGE_NOACCESS)
+            };
+            if done {
+                runs.push((at, n));
+            }
+        }
+        at = end;
+    }
+    runs
+}
+
+unsafe fn protect(a: usize, n: usize, p: u32) -> bool {
+    let mut old = 0;
+    VirtualProtect(a as *const c_void, n, p, &mut old) != 0
+}
+
+unsafe fn open_runs(runs: &[(usize, usize)]) {
+    for &(a, n) in runs {
+        let mut at = a;
+        let hi = a + n;
+        while at < hi {
+            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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi);
+            if end <= at {
+                break;
+            }
+            if m.State == MEM_COMMIT && m.Protect == PAGE_NOACCESS {
+                let _ = protect(at, end - at, PAGE_READWRITE);
+            }
+            at = end;
+        }
+    }
+}
+
+/// Disarm armed entries overlapping `[va, va + len)` before eager `publish_download` writes there.
+pub(super) fn disarm_overlapping(va: usize, len: usize) {
+    if !ANY_ARMED.load(Ordering::Acquire) || len == 0 {
+        return;
+    }
+    let hi = va.saturating_add(len);
+    let gone: Vec<Armed> = with(|s| {
+        let keys: Vec<usize> = s.armed.range(..hi).filter(|(_, a)| a.hi > va).map(|(&k, _)| k).collect();
+        let mut out = Vec::with_capacity(keys.len());
+        for k in keys {
+            if let Some(a) = s.armed.remove(&k) {
+                s.by_res.remove(&a.res);
+                out.push(a);
+            }
+        }
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        out
+    });
+    for a in gone {
+        disarm(&a);
+    }
+}
+
+pub fn forget(res: usize) {
+    if !on() || res == 0 {
+        return;
+    }
+    let gone = with(|s| {
+        s.refused.remove(&res);
+        for v in s.pending.values_mut() {
+            v.retain(|&r| r != res);
+        }
+        let a = s.by_res.remove(&res).and_then(|lo| s.armed.remove(&lo));
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        a
+    });
+    if let Some(a) = gone {
+        disarm(&a);
+    }
+}
+
+fn disarm(a: &Armed) {
+    unsafe { open_runs(&a.runs) };
+    if guest_write::enabled() {
+        guest_write::unregister(a.lo, a.hi - a.lo);
+    }
+}
+
+fn install() {
+    HANDLER.call_once(|| unsafe {
+        AddVectoredExceptionHandler(1, Some(handler));
+    });
+}
+
+unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
+    if !ANY_ARMED.load(Ordering::Acquire) {
+        return 0;
+    }
+    let r = &*(*info).ExceptionRecord;
+    if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 {
+        return 0;
+    }
+    let kind = r.ExceptionInformation[0];
+    if kind != 0 && kind != 1 {
+        return 0;
+    }
+    let at = r.ExceptionInformation[1];
+    if fault(at) || accessible(at, kind == 1) { -1 } else { 0 }
+}
+
+fn fault(at: usize) -> bool {
+    let armed = with(|s| {
+        let (&lo, a) = s.armed.range(..=at).next_back()?;
+        if at >= a.hi {
+            return None;
+        }
+        let a = s.armed.remove(&lo)?;
+        s.by_res.remove(&a.res);
+        ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release);
+        Some(a)
+    });
+    let Some(a) = armed else { return false };
+    #[cfg(test)]
+    TEST_STATS[1].fetch_add(1, Ordering::Relaxed);
+    let mut opened = false;
+    let r = unsafe {
+        super::title_textures::read_back_after(a.res, &a.fence.0, a.value, || {
+            open_runs(&a.runs);
+            opened = true;
+        })
+    };
+    if !opened {
+        unsafe { open_runs(&a.runs) };
+    }
+    if guest_write::enabled() {
+        guest_write::unregister(a.lo, a.hi - a.lo);
+    }
+    match r {
+        Ok(n) => {
+            #[cfg(test)]
+            TEST_STATS[2].fetch_add(n as u64, Ordering::Relaxed);
+            let _ = n;
+        }
+        Err(e) => {
+            with(|s| {
+                s.refused.insert(a.res);

Medium: Any read_back_after error, including the transient "texture registry stayed busy" after 200 ms of TEXTURES contention, puts the texture in refused, which only forget() clears, so one contended fault disables copy-back for that texture for good. If another thread holds TEXTURES for more than 200 ms (refresh scanning a large title) when a title thread faults on T, T is opened with stale CPU data and refused, every later GPU write to T is ignored by arm(), and the title reads stale texels for the rest of the session. Retrying transient errors would avoid it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772202988 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#discussion_r4772202988). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:29Z. **Code review location:** `crates/xcl/src/hle/d3d12x/copy_back.rs`; line 378 ~~~~diff @@ -0,0 +1,410 @@ +//! Fault-driven GPU → CPU texture copy-back (`XCL_COPY_BACK=fault`; default off, requires +//! `XCL_GUEST_WRITE_GUARD=1`) for kept `title_textures` (#2663). +//! +//! After a submit whose lists wrote a kept texture, whole committed 4 KiB title pages inside the +//! texture's VA range (outside imported coherent UMA and guarded views) are made `PAGE_NOACCESS` +//! behind a native per-queue fence. A CPU touch faults into the VEH handler, waits on the fence +//! via XCL's upload queue, downloads via `title_textures::read_back_after`, opens the pages, and +//! re-tiles changed pages back into console layout. + +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Mutex, Once, OnceLock}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::*; +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_NOACCESS, PAGE_READWRITE}; + +use crate::hle::kernelx::guest_write; + +const PAGE: usize = 0x1000; + +fn mode_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + if !std::env::var("XCL_COPY_BACK").is_ok_and(|v| v.trim().eq_ignore_ascii_case("fault")) { + return false; + } + if !guest_write::enabled() { + crate::xlog_warn!("XCL_COPY_BACK=fault ignored: set XCL_GUEST_WRITE_GUARD=1 first"); + return false; + } + crate::xlog_info!("XCL_COPY_BACK=fault: GPU-written kept textures read back on CPU touch"); + true + }) +} + +#[cfg(test)] +static FORCE: AtomicBool = AtomicBool::new(false); + +pub fn on() -> bool { + #[cfg(test)] + if FORCE.load(Ordering::Acquire) { + return true; + } + mode_on() +} + +/// Imported coherent UMA (`OpenExistingHeapFromAddress`) VADs reject `PAGE_NOACCESS` (error 87). +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 Shared<T>(T); +unsafe impl<T> Send for Shared<T> {} + +struct Armed { + res: usize, + lo: usize, + hi: usize, + runs: Vec<(usize, usize)>, + fence: Shared<ID3D12Fence>, + value: u64, +} + +#[derive(Default)] +struct State { + pending: HashMap<usize, Vec<usize>>, + armed: BTreeMap<usize, Armed>, + by_res: HashMap<usize, usize>, + refused: HashSet<usize>, + fences: HashMap<usize, (Shared<ID3D12Fence>, u64)>, +} + +static STATE: Mutex<Option<State>> = Mutex::new(None); +static ANY_ARMED: AtomicBool = AtomicBool::new(false); +static HANDLER: Once = Once::new(); +#[cfg(test)] +static TEST_STATS: [AtomicU64; 3] = [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)]; +static ERRORS: AtomicU64 = AtomicU64::new(0); + +fn with<R>(f: impl FnOnce(&mut State) -> R) -> R { + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + f(g.get_or_insert_with(State::default)) +} + +pub fn note_write(list: usize, res: usize) { + if !on() || list == 0 || res == 0 { + return; + } + with(|s| { + let v = s.pending.entry(list).or_default(); + if !v.contains(&res) { + v.push(res); + } + }); +} + +pub fn list_reset(list: usize) { + if !on() || list == 0 { + return; + } + with(|s| { + s.pending.remove(&list); + }); +} + +pub fn forget_queue(queue: usize) { + if !on() || queue == 0 { + return; + } + with(|s| { + s.fences.remove(&queue); + }); +} + +pub unsafe fn after_submit(queue: *mut c_void, lists: &[*mut c_void]) { + if !on() || queue.is_null() || lists.is_empty() { + return; + } + let textures: Vec<usize> = with(|s| { + let mut out = Vec::new(); + for &l in lists { + if let Some(v) = s.pending.get(&(l as usize)) { + for &r in v { + if !out.contains(&r) { + out.push(r); + } + } + } + } + out + }); + if textures.is_empty() { + return; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some((fence, value)) = signal(q) else { return }; + for res in textures { + arm(res, &fence, value); + } +} + +unsafe fn signal(q: &ID3D12CommandQueue) -> Option<(ID3D12Fence, u64)> { + let key = q.as_raw() as usize; + let (fence, value) = with(|s| { + if let Some((f, v)) = s.fences.get_mut(&key) { + *v += 1; + return Some((f.0.clone(), *v)); + } + let mut dev: Option<ID3D12Device> = None; + q.GetDevice(&mut dev).ok()?; + let f: ID3D12Fence = dev?.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?; + s.fences.insert(key, (Shared(f.clone()), 1)); + Some((f, 1)) + })?; + super::real::native_queue_signal(q, &fence, value).ok()?; + Some((fence, value)) +} + +unsafe fn arm(res: usize, fence: &ID3D12Fence, value: u64) { + let Some((va, len)) = super::title_textures::copy_back_range(res) else { return }; + let (lo, hi) = (va.next_multiple_of(PAGE), (va + len) & !(PAGE - 1)); + if lo >= hi || guest_write::meets_guarded_view(lo, hi - lo) || in_imported_uma(lo, hi - lo) { + return; + } + let mut g = STATE.lock().unwrap_or_else(|e| e.into_inner()); + let s = g.get_or_insert_with(State::default); + if s.refused.contains(&res) { + return; + } + if let Some(&at) = s.by_res.get(&res) { + if let Some(a) = s.armed.get_mut(&at) { + a.fence = Shared(fence.clone()); + a.value = value; + } + return; + } + if let Some((&other_lo, other)) = s.armed.range(..hi).next_back() { + if other.hi > lo { + if other_lo == lo && other.hi == hi { + let old_res = other.res; + s.by_res.remove(&old_res); + if let Some(a) = s.armed.get_mut(&other_lo) { + a.res = res; + a.fence = Shared(fence.clone()); + a.value = value; + } + s.by_res.insert(res, lo); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); + } + return; + } + } + // Install the VEH handler and set ANY_ARMED before VirtualProtect(PAGE_NOACCESS) while + // holding STATE so any concurrent touch immediately faults into `handler` and waits on STATE. + install(); + ANY_ARMED.store(true, Ordering::Release); + if guest_write::enabled() { + guest_write::register(lo, hi - lo); + } + let runs = protect_rw_runs(lo, hi); + if runs.is_empty() { + if guest_write::enabled() { + guest_write::unregister(lo, hi - lo); + } + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + return; + } + s.by_res.insert(res, lo); + s.armed.insert(lo, Armed { res, lo, hi, runs, fence: Shared(fence.clone()), value }); + #[cfg(test)] + TEST_STATS[0].fetch_add(1, Ordering::Relaxed); +} + +unsafe fn protect_rw_runs(lo: usize, hi: usize) -> Vec<(usize, usize)> { + let mut runs = Vec::new(); + let mut at = lo; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_READWRITE { + let n = end - at; + let done = if guest_write::enabled() { + guest_write::while_unpinned(at, n, || protect(at, n, PAGE_NOACCESS)) + } else { + protect(at, n, PAGE_NOACCESS) + }; + if done { + runs.push((at, n)); + } + } + at = end; + } + runs +} + +unsafe fn protect(a: usize, n: usize, p: u32) -> bool { + let mut old = 0; + VirtualProtect(a as *const c_void, n, p, &mut old) != 0 +} + +unsafe fn open_runs(runs: &[(usize, usize)]) { + for &(a, n) in runs { + let mut at = a; + let hi = a + n; + while at < hi { + 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 end = (m.BaseAddress as usize).saturating_add(m.RegionSize).min(hi); + if end <= at { + break; + } + if m.State == MEM_COMMIT && m.Protect == PAGE_NOACCESS { + let _ = protect(at, end - at, PAGE_READWRITE); + } + at = end; + } + } +} + +/// Disarm armed entries overlapping `[va, va + len)` before eager `publish_download` writes there. +pub(super) fn disarm_overlapping(va: usize, len: usize) { + if !ANY_ARMED.load(Ordering::Acquire) || len == 0 { + return; + } + let hi = va.saturating_add(len); + let gone: Vec<Armed> = with(|s| { + let keys: Vec<usize> = s.armed.range(..hi).filter(|(_, a)| a.hi > va).map(|(&k, _)| k).collect(); + let mut out = Vec::with_capacity(keys.len()); + for k in keys { + if let Some(a) = s.armed.remove(&k) { + s.by_res.remove(&a.res); + out.push(a); + } + } + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + out + }); + for a in gone { + disarm(&a); + } +} + +pub fn forget(res: usize) { + if !on() || res == 0 { + return; + } + let gone = with(|s| { + s.refused.remove(&res); + for v in s.pending.values_mut() { + v.retain(|&r| r != res); + } + let a = s.by_res.remove(&res).and_then(|lo| s.armed.remove(&lo)); + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + a + }); + if let Some(a) = gone { + disarm(&a); + } +} + +fn disarm(a: &Armed) { + unsafe { open_runs(&a.runs) }; + if guest_write::enabled() { + guest_write::unregister(a.lo, a.hi - a.lo); + } +} + +fn install() { + HANDLER.call_once(|| unsafe { + AddVectoredExceptionHandler(1, Some(handler)); + }); +} + +unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 { + if !ANY_ARMED.load(Ordering::Acquire) { + return 0; + } + let r = &*(*info).ExceptionRecord; + if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS || r.NumberParameters < 2 { + return 0; + } + let kind = r.ExceptionInformation[0]; + if kind != 0 && kind != 1 { + return 0; + } + let at = r.ExceptionInformation[1]; + if fault(at) || accessible(at, kind == 1) { -1 } else { 0 } +} + +fn fault(at: usize) -> bool { + let armed = with(|s| { + let (&lo, a) = s.armed.range(..=at).next_back()?; + if at >= a.hi { + return None; + } + let a = s.armed.remove(&lo)?; + s.by_res.remove(&a.res); + ANY_ARMED.store(!s.armed.is_empty(), Ordering::Release); + Some(a) + }); + let Some(a) = armed else { return false }; + #[cfg(test)] + TEST_STATS[1].fetch_add(1, Ordering::Relaxed); + let mut opened = false; + let r = unsafe { + super::title_textures::read_back_after(a.res, &a.fence.0, a.value, || { + open_runs(&a.runs); + opened = true; + }) + }; + if !opened { + unsafe { open_runs(&a.runs) }; + } + if guest_write::enabled() { + guest_write::unregister(a.lo, a.hi - a.lo); + } + match r { + Ok(n) => { + #[cfg(test)] + TEST_STATS[2].fetch_add(n as u64, Ordering::Relaxed); + let _ = n; + } + Err(e) => { + with(|s| { + s.refused.insert(a.res); ~~~~ --- **Medium**: Any `read_back_after` error, including the transient "texture registry stayed busy" after 200 ms of TEXTURES contention, puts the texture in `refused`, which only `forget()` clears, so one contended fault disables copy-back for that texture for good. If another thread holds TEXTURES for more than 200 ms (refresh scanning a large title) when a title thread faults on T, T is opened with stale CPU data and refused, every later GPU write to T is ignored by `arm()`, and the title reads stale texels for the rest of the session. Retrying transient errors would avoid it.
bmjask commented 2026-12-02 15:45:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:29Z.

Review: COMMENTED


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

  1. Critical crates/xcl/src/hle/d3d12x/copy_back.rs:349: fault() removes the armed entry from STATE before the long fence wait and readback, so a second thread touching the same still-PAGE_NOACCESS pages finds no entry, accessible() is false, and the handler returns EXCEPTION_CONTINUE_SEAR.... (inline)
  2. Critical crates/xcl/src/hle/d3d12x/copy_back.rs:359: Not certain about this one: the VEH handler blocks the faulting thread until the title queue's native fence completes (native_queue_wait plus texture::download). (inline)
  3. High crates/xcl/src/hle/d3d12x/copy_back.rs:234: Armed pages are PAGE_NOACCESS for reads too, but guest_write only brackets kernel and XCL writes. (inline)
  4. High crates/xcl/src/hle/d3d12x/copy_back.rs:231: arm() during an in-flight fault() or disarm_overlapping() (entry already removed, pages not yet reopened) finds the pages PAGE_NOACCESS, and protect_rw_runs skips them as non-RW, so the new GPU write is never tracked or copied back. (inline)
  5. High crates/xcl/src/hle/d3d12x/copy_back.rs:176: Re-arming an already-armed texture replaces its (fence, value) with the latest submit's, so when the latest write is on a different queue the readback waits only on that queue and can read before an earlier write on the first queue finishes. (inline)
  6. High crates/xcl/src/hle/d3d12x/copy_back.rs:181: A new texture whose range partially overlaps an armed one is silently not armed, and an exact-range overlap re-labels the entry to the new res, so aliased placed textures either lose copy-back or read back the wrong resource's texels. (inline)
  7. High crates/xcl/src/hle/d3d12x/copy_back.rs:280: disarm_overlapping drops every armed entry overlapping the download target and reopens its whole range without reading back, so GPU writes of an overlapping texture outside the eager download's bytes are lost. (inline)
  8. Medium crates/xcl/src/hle/d3d12x/copy_back.rs:378: Any read_back_after error, including the transient "texture registry stayed busy" after 200 ms of TEXTURES contention, puts the texture in refused, which only forget() clears, so one contended fault disables copy-back for that text.... (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:6154172959 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#pullrequestreview-6154172959). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:29Z. **Review:** COMMENTED --- Review of `06f79319`: 8 finding(s) (2 critical, 5 high, 1 medium), most severe first. 1. **Critical** `crates/xcl/src/hle/d3d12x/copy_back.rs:349`: `fault()` removes the armed entry from STATE before the long fence wait and readback, so a second thread touching the same still-PAGE_NOACCESS pages finds no entry, `accessible()` is false, and the handler returns EXCEPTION_CONTINUE_SEAR.... (inline) 2. **Critical** `crates/xcl/src/hle/d3d12x/copy_back.rs:359`: Not certain about this one: the VEH handler blocks the faulting thread until the title queue's native fence completes (`native_queue_wait` plus `texture::download`). (inline) 3. **High** `crates/xcl/src/hle/d3d12x/copy_back.rs:234`: Armed pages are PAGE_NOACCESS for reads too, but guest_write only brackets kernel and XCL writes. (inline) 4. **High** `crates/xcl/src/hle/d3d12x/copy_back.rs:231`: `arm()` during an in-flight `fault()` or `disarm_overlapping()` (entry already removed, pages not yet reopened) finds the pages PAGE_NOACCESS, and `protect_rw_runs` skips them as non-RW, so the new GPU write is never tracked or copied back. (inline) 5. **High** `crates/xcl/src/hle/d3d12x/copy_back.rs:176`: Re-arming an already-armed texture replaces its (fence, value) with the latest submit's, so when the latest write is on a different queue the readback waits only on that queue and can read before an earlier write on the first queue finishes. (inline) 6. **High** `crates/xcl/src/hle/d3d12x/copy_back.rs:181`: A new texture whose range partially overlaps an armed one is silently not armed, and an exact-range overlap re-labels the entry to the new res, so aliased placed textures either lose copy-back or read back the wrong resource's texels. (inline) 7. **High** `crates/xcl/src/hle/d3d12x/copy_back.rs:280`: `disarm_overlapping` drops every armed entry overlapping the download target and reopens its whole range without reading back, so GPU writes of an overlapping texture outside the eager download's bytes are lost. (inline) 8. **Medium** `crates/xcl/src/hle/d3d12x/copy_back.rs:378`: Any `read_back_after` error, including the transient "texture registry stayed busy" after 200 ms of TEXTURES contention, puts the texture in `refused`, which only `forget()` clears, so one contended fault disables copy-back for that text.... (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 15:45:32 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:45:32Z.


@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:7350869604 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3601#issuecomment-7350869604). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:45:32Z. --- @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/3601:upstream-pr/3601'
git switch 'upstream-pr/3601'

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