D3D12.X: XCL_VRAM_BUDGET keeps XCL's pools under the adapter's budget #3587

Open
iggyvilla wants to merge 1 commit from upstream-pr/3587 into amd-dev
iggyvilla commented 2026-12-01 17:03:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by iggyvilla on 2026-12-01T17:03:58Z.


Adds opt-in XCL_VRAM_BUDGET=1 (off by default: zero behavior change) to keep XCL's paged texture pools and sparse tiles under the adapter's DXGI local video-memory budget on 8 GB cards (#1337, #1585). Supersedes #3335 (now closed).

TL;DR — Before vs After (RX 6650 XT 8 GB, lockhart)

Metric Before (XCL_VRAM_BUDGET=0) After (XCL_VRAM_BUDGET=1) Delta
60 s smoke (41aa60ce vs 2ddf8227, off) 1,654 frames / 15,902 MB 1,659 frames / 16,495 MB Parity (0 crashes)
In-world peak local VRAM (vs 6,808 MB budget) 7,688 MB (+880 MB over, 85 warns) 6,024–6,534 MB (-257 to -783 MB under, 0 warns; MARGIN=2500) −1,154 to −1,664 MB
In-world steady frame rate / frame time 1.59 → 1.12 fps (WDDM paging) 2.19 fps (456 ms/frame, 6.58 GB < 6.8 GB) +38% to +95% FPS
Default margin (2048 MiB) loading commit (41aa60ce) 23,819 MB commit (5,746 MB local) 20,737 MB commit (5,629 MB local, 256 MB L0) −3,082 MB commit

What is in it (~400 runtime lines + ~215 test lines across 5 files; cohesive budget sampler + pool placement + reporting)

  • crates/xcl/src/hle/d3d12x/vram_budget.rs: opt-in XCL_VRAM_BUDGET=1 pressure tracker (Room / Near / Over with 256 MiB hysteresis), sampling DXGI local budget every 250 ms (XCL_VRAM_BUDGET_MARGIN_MB, default 2048; XCL_VRAM_BUDGET_MB fixed target) + unit tests.
  • crates/xcl/src/hle/d3d12x/memory_report.rs: caches IDXGIAdapter3 per adapter LUID (no factory creation on 250 ms samples), adds local_segment(), and reports "target pools in system memory" via uma_segment(non_local) (non-local on discrete GPUs, local on single-segment/UMA adapters).
  • crates/xcl/src/hle/d3d12x/vram.rs: per-device PoolHeaps L0 tracking (is_sys, sys_live) and page_bytes_split_for; under pressure, sampled textures spill new tiles to 64 MiB L0 heaps (CUSTOM, CPU_PAGE_PROPERTY_NOT_AVAILABLE, MEMORY_POOL_L0) only after free VRAM pool tiles are exhausted, and empty pools reclaim every 250 ms with 0 warm spares. gpu_owned targets (RT/DS/UAV) stay in the sys = false video-memory class in normal operation; they can touch L0 pages only in two edge cases: (1) when a gpu_owned target is placed over an already-live L0 page (existing page-sharing behavior), or (2) if video-memory CreateHeap actually fails with OOM under XCL_VRAM_BUDGET=1, in which case take_tiles_with_fallback falls back to the sys = true pool class (never registering an L0 heap under sys = false) with a 2 s retry backoff (cleared on pool reclaim) and rate-limited warnings so subsequent binds reuse the fallback pool without retrying CreateHeap every bind. Adds unit test gpu_owned_vram_oom_falls_back_to_sys_class_and_backs_off_retries and GPU round-trip test system_memory_pages_have_their_own_heap_and_hold_what_the_gpu_copies (with COPY_DEST -> COPY_SOURCE barrier).
  • crates/xcl/src/hle/d3d12x/sparse.rs: flushes parked sparse tiles at 256 (16 MiB) instead of 4096 (256 MiB) when under pressure.
  • crates/xcl/src/hle/d3d12x/mod.rs: wires vram_budget.

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/in-world runs.
  • cargo test -p xcl --lib -- gpu_owned_vram_oom_falls_back_to_sys_class_and_backs_off_retries system_memory_pages_have_their_own_heap_and_hold_what_the_gpu_copies: 2 passed, 0 failed.
  • cargo test --workspace --no-fail-fast -- --test-threads=4 (on head 2ddf8227): 2,965 passed, 13 pre-existing failed, 49 ignored (identical pre-existing failures to clean origin/amd-dev 41aa60ce: 3 RDNA2 f32/NaN tests, 6 parallel sparse/title_textures contention tests, 2 e2e tests, 2 two_pass_driver_cache tests).
  • Retail title (1778c2d9, lockhart): verified VRAM containment and steady in-world frame rate (2.19 fps / 456 ms under budget vs 1.59 → 1.12 fps over budget on RX 6650 XT; independently retested by @throny on RTX 4080 16 GB at 2.57–2.71 vs 2.67 presents/s with -0.7 to -0.9 GB peak VRAM).

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 (2ddf8227, XCL_VRAM_BUDGET unset):

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

Not tested

  • NVIDIA and Intel GPUs, single-segment/integrated GPUs (relies on uma_segment(non_local)), and Wine.

AI use

  • Antigravity (Gemini 4 Neon High) implemented the review fixes (IDXGIAdapter3 caching, uma_segment(non_local), strict sys = true pool-class separation for VRAM-OOM fallback, missing copy barrier in the GPU test), ran the test suite and 60 s smoke, and updated this description.
<!-- greyfinch-sync:ivall/xcl:issue:5590517425 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587). Originally posted by [iggyvilla](https://github.com/iggyvilla) on 2026-12-01T17:03:58Z. --- Adds opt-in `XCL_VRAM_BUDGET=1` (off by default: zero behavior change) to keep XCL's paged texture pools and sparse tiles under the adapter's DXGI local video-memory budget on 8 GB cards (#1337, #1585). Supersedes #3335 (now closed). ### TL;DR — Before vs After (RX 6650 XT 8 GB, `lockhart`) | Metric | Before (`XCL_VRAM_BUDGET=0`) | After (`XCL_VRAM_BUDGET=1`) | Delta | |---|---:|---:|---:| | **60 s smoke (`41aa60ce` vs `2ddf8227`, off)** | `1,654` frames / `15,902 MB` | `1,659` frames / `16,495 MB` | Parity (`0` crashes) | | **In-world peak local VRAM (vs `6,808 MB` budget)** | `7,688 MB` (`+880 MB` over, `85` warns) | `6,024–6,534 MB` (`-257` to `-783 MB` under, `0` warns; `MARGIN=2500`) | **−1,154 to −1,664 MB** | | **In-world steady frame rate / frame time** | `1.59 → 1.12 fps` (WDDM paging) | `2.19 fps` (`456 ms/frame`, `6.58 GB < 6.8 GB`) | **+38% to +95% FPS** | | **Default margin (`2048 MiB`) loading commit (`41aa60ce`)** | `23,819 MB` commit (`5,746 MB` local) | `20,737 MB` commit (`5,629 MB` local, `256 MB` L0) | **−3,082 MB commit** | **What is in it** (~400 runtime lines + ~215 test lines across 5 files; cohesive budget sampler + pool placement + reporting) - `crates/xcl/src/hle/d3d12x/vram_budget.rs`: opt-in `XCL_VRAM_BUDGET=1` pressure tracker (`Room` / `Near` / `Over` with 256 MiB hysteresis), sampling DXGI local budget every 250 ms (`XCL_VRAM_BUDGET_MARGIN_MB`, default `2048`; `XCL_VRAM_BUDGET_MB` fixed target) + unit tests. - `crates/xcl/src/hle/d3d12x/memory_report.rs`: caches `IDXGIAdapter3` per adapter LUID (no factory creation on 250 ms samples), adds `local_segment()`, and reports `"target pools in system memory"` via `uma_segment(non_local)` (non-local on discrete GPUs, local on single-segment/UMA adapters). - `crates/xcl/src/hle/d3d12x/vram.rs`: per-device `PoolHeaps` L0 tracking (`is_sys`, `sys_live`) and `page_bytes_split_for`; under pressure, sampled textures spill new tiles to 64 MiB L0 heaps (`CUSTOM`, `CPU_PAGE_PROPERTY_NOT_AVAILABLE`, `MEMORY_POOL_L0`) only after free VRAM pool tiles are exhausted, and empty pools reclaim every 250 ms with 0 warm spares. `gpu_owned` targets (RT/DS/UAV) stay in the `sys = false` video-memory class in normal operation; they can touch L0 pages only in two edge cases: (1) when a `gpu_owned` target is placed over an already-live L0 page (existing page-sharing behavior), or (2) if video-memory `CreateHeap` actually fails with OOM under `XCL_VRAM_BUDGET=1`, in which case `take_tiles_with_fallback` falls back to the `sys = true` pool class (never registering an L0 heap under `sys = false`) with a 2 s retry backoff (cleared on pool reclaim) and rate-limited warnings so subsequent binds reuse the fallback pool without retrying `CreateHeap` every bind. Adds unit test `gpu_owned_vram_oom_falls_back_to_sys_class_and_backs_off_retries` and GPU round-trip test `system_memory_pages_have_their_own_heap_and_hold_what_the_gpu_copies` (with `COPY_DEST -> COPY_SOURCE` barrier). - `crates/xcl/src/hle/d3d12x/sparse.rs`: flushes parked sparse tiles at `256` (16 MiB) instead of `4096` (256 MiB) when under pressure. - `crates/xcl/src/hle/d3d12x/mod.rs`: wires `vram_budget`. **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/in-world runs. - `cargo test -p xcl --lib -- gpu_owned_vram_oom_falls_back_to_sys_class_and_backs_off_retries system_memory_pages_have_their_own_heap_and_hold_what_the_gpu_copies`: **2 passed, 0 failed**. - `cargo test --workspace --no-fail-fast -- --test-threads=4` (on head `2ddf8227`): **2,965 passed, 13 pre-existing failed, 49 ignored** (identical pre-existing failures to clean `origin/amd-dev` `41aa60ce`: 3 RDNA2 f32/NaN tests, 6 parallel `sparse`/`title_textures` contention tests, 2 `e2e` tests, 2 `two_pass_driver_cache` tests). - Retail title (`1778c2d9`, `lockhart`): verified VRAM containment and steady in-world frame rate (`2.19 fps` / `456 ms` under budget vs `1.59 → 1.12 fps` over budget on RX 6650 XT; independently retested by `@throny` on RTX 4080 16 GB at `2.57–2.71` vs `2.67` presents/s with `-0.7` to `-0.9 GB` peak VRAM). **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 (`2ddf8227`, `XCL_VRAM_BUDGET` unset): ``` xcl-smoke v1 commit: 2ddf82273c40a2f02340bfa196084e62e8a6749e gpu: AMD Radeon RX 6650 XT title: 1778c2d9 seconds: 60 exit: 0x0 frames shown: 1659 (PresentX 1659) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 16495 MB ``` **Not tested** - NVIDIA and Intel GPUs, single-segment/integrated GPUs (relies on `uma_segment(non_local)`), and Wine. **AI use** - Antigravity (Gemini 4 Neon High) implemented the review fixes (`IDXGIAdapter3` caching, `uma_segment(non_local)`, strict `sys = true` pool-class separation for VRAM-OOM fallback, missing copy barrier in the GPU test), ran the test suite and 60 s smoke, and updated this description.
Foniass commented 2026-12-01 20:28:28 +00:00 (Migrated from github.com)

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


Review (head 08f61a9a, diff read, not a merge-check):

  • Render targets can still get system-memory pages. The description says only sampled textures go to L0, never render targets, depth buffers or UAVs. But when CreateHeap fails for a video-memory heap, alloc_pool_heap (vram.rs ~1724-1731) returns an L0 heap that bind_range (~2521-2524) registers in the sys = false class of the TilePool, against the invariant in bind_range's doc comment (~2488). Later gpu_owned targets then take tiles from that L0 heap by best fit. A target placed over a page created under pressure also shares that L0 page (the "shared as it is" case at ~2489).
  • Each budget sample creates a DXGI factory. memory_report.rs ~93-94 creates a factory and calls EnumAdapterByLuid per sample, every 250 ms, from before_execute and place_on_pages (vram.rs ~3195, ~2798). Caching the IDXGIAdapter3 avoids that. The enabled runs in the description give local MB and warning counts but no frame time, so the cost of XCL_VRAM_BUDGET=1 (including sampling over the bus) is not shown.
  • System-memory pools always counted as non-local. memory_report.rs ~147 hard-codes Kind::NonLocal for "target pools in system memory". On a single-segment adapter DXGI counts L0 heaps in the local segment (what uma_segment() ~121 handles), so the report puts these bytes on the wrong side and local "other" grows by the same amount.

Fine: off by default; with XCL_VRAM_BUDGET unset, pressure stays Room and placement, reclaim and parked-tile limits behave as on the base; PoolHeaps tracks L0 heaps per slot and clears the flag on reclaim; the hysteresis and the L0 round-trip have tests. The description says this supersedes #3335, which is still open.

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

<!-- greyfinch-sync:ivall/xcl:comment:7324746279 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7324746279). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T20:28:28Z. --- Review (head 08f61a9a, diff read, not a merge-check): - **Render targets can still get system-memory pages.** The description says only sampled textures go to L0, never render targets, depth buffers or UAVs. But when `CreateHeap` fails for a video-memory heap, `alloc_pool_heap` (`vram.rs` ~1724-1731) returns an L0 heap that `bind_range` (~2521-2524) registers in the `sys = false` class of the `TilePool`, against the invariant in `bind_range`'s doc comment (~2488). Later `gpu_owned` targets then take tiles from that L0 heap by best fit. A target placed over a page created under pressure also shares that L0 page (the "shared as it is" case at ~2489). - **Each budget sample creates a DXGI factory.** `memory_report.rs` ~93-94 creates a factory and calls `EnumAdapterByLuid` per sample, every 250 ms, from `before_execute` and `place_on_pages` (`vram.rs` ~3195, ~2798). Caching the `IDXGIAdapter3` avoids that. The enabled runs in the description give local MB and warning counts but no frame time, so the cost of `XCL_VRAM_BUDGET=1` (including sampling over the bus) is not shown. - **System-memory pools always counted as non-local.** `memory_report.rs` ~147 hard-codes `Kind::NonLocal` for "target pools in system memory". On a single-segment adapter DXGI counts L0 heaps in the local segment (what `uma_segment()` ~121 handles), so the report puts these bytes on the wrong side and local "other" grows by the same amount. Fine: off by default; with `XCL_VRAM_BUDGET` unset, pressure stays `Room` and placement, reclaim and parked-tile limits behave as on the base; `PoolHeaps` tracks L0 heaps per slot and clears the flag on reclaim; the hysteresis and the L0 round-trip have tests. The description says this supersedes #3335, which is still open. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
throny commented 2026-12-02 02:13:33 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by throny on 2026-12-02T02:13:33Z.


Queued an in-world A/B of this on an RTX 4080 16 GB: current main + this head, same build with XCL_VRAM_BUDGET unset vs =1, 900 s each, XCL_RESIDENCY_PRIORITY=1 and XCL_GPU_PROFILE=1. The retail title runs 3–4 GB over the card's budget in our runs, so this is exactly its case; numbers here when done.

AI use: Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:ivall/xcl:comment:7332606618 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7332606618). Originally posted by [throny](https://github.com/throny) on 2026-12-02T02:13:33Z. --- Queued an in-world A/B of this on an RTX 4080 16 GB: current `main` + this head, same build with `XCL_VRAM_BUDGET` unset vs `=1`, 900 s each, `XCL_RESIDENCY_PRIORITY=1` and `XCL_GPU_PROFILE=1`. The retail title runs 3–4 GB over the card's budget in our runs, so this is exactly its case; numbers here when done. AI use: Claude Code (Claude Opus 5.5).
throny commented 2026-12-02 04:05:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by throny on 2026-12-02T04:05:10Z.


In-world result, RTX 4080 16 GB (621.40). Since this targets amd-dev, the build is this PR's own head (on amd-dev 41aa60ce) plus our local input-timing patch; same build, same save and inputs, 900 s each, XCL_RESIDENCY_PRIORITY=1, no draws skipped:

run XCL_VRAM_BUDGET presents/s after 240 s video memory peak / budget
417 unset 2.67 16.4 / 15.1 GB
416 1 2.05 14.4 / 15.1 GB

So it does keep the process under the budget on this card (the first run we have seen under it in Series X mode), but costs about 23 % presents/s here. No device removal or crash. (A third run without the switch compiled cold for an hour and is left out.) One pair only; if you want a particular margin (XCL_VRAM_BUDGET_MARGIN_MB) or pool tried, say so and we'll run it.

AI use: Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:ivall/xcl:comment:7334540475 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7334540475). Originally posted by [throny](https://github.com/throny) on 2026-12-02T04:05:10Z. --- In-world result, RTX 4080 16 GB (621.40). Since this targets `amd-dev`, the build is this PR's own head (on `amd-dev` `41aa60ce`) plus our local input-timing patch; same build, same save and inputs, 900 s each, `XCL_RESIDENCY_PRIORITY=1`, no draws skipped: | run | `XCL_VRAM_BUDGET` | presents/s after 240 s | video memory peak / budget | |---|---|---|---| | 417 | unset | 2.67 | 16.4 / 15.1 GB | | 416 | 1 | 2.05 | **14.4 / 15.1 GB** | So it does keep the process under the budget on this card (the first run we have seen under it in Series X mode), but costs about 23 % presents/s here. No device removal or crash. (A third run without the switch compiled cold for an hour and is left out.) One pair only; if you want a particular margin (`XCL_VRAM_BUDGET_MARGIN_MB`) or pool tried, say so and we'll run it. AI use: Claude Code (Claude Opus 5.5).
iggyvilla commented 2026-12-02 04:20:47 +00:00 (Migrated from github.com)

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


Updated to b401f608 addressing @Foniass's review:\n- alloc_pool_heap / bind_range: VRAM-OOM L0 fallback now allocates and registers strictly under TilePool's sys = true class so later gpu_owned targets never draw from it by best fit (and documented the shared-alias case explicitly).\n- memory_report.rs: cached IDXGIAdapter3 per adapter LUID instead of creating a DXGI factory every 250 ms, and changed "target pools in system memory" to use uma_segment(non_local).\n- Added the missing COPY_DEST -> COPY_SOURCE barrier in system_memory_pages_have_their_own_heap_and_hold_what_the_gpu_copies, added whole-workspace GPU test counts + 41aa60ce merge-base smoke + in-world FPS numbers, and closed superseded #3335.

<!-- greyfinch-sync:ivall/xcl:comment:7334813535 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7334813535). Originally posted by [iggyvilla](https://github.com/iggyvilla) on 2026-12-02T04:20:47Z. --- Updated to `b401f608` addressing @Foniass's review:\n- `alloc_pool_heap` / `bind_range`: VRAM-OOM L0 fallback now allocates and registers strictly under `TilePool`'s `sys = true` class so later `gpu_owned` targets never draw from it by best fit (and documented the shared-alias case explicitly).\n- `memory_report.rs`: cached `IDXGIAdapter3` per adapter LUID instead of creating a DXGI factory every 250 ms, and changed `"target pools in system memory"` to use `uma_segment(non_local)`.\n- Added the missing `COPY_DEST -> COPY_SOURCE` barrier in `system_memory_pages_have_their_own_heap_and_hold_what_the_gpu_copies`, added whole-workspace GPU test counts + `41aa60ce` merge-base smoke + in-world FPS numbers, and closed superseded #3335.
Foniass commented 2026-12-02 04:23:01 +00:00 (Migrated from github.com)

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


Follow-up review (head b401f608, since 08f61a9a, diff read, not a merge-check):

  • Render targets can still get system-memory pages: partly fixed. Later targets no longer take tiles from a fallback heap: bind_range (vram.rs ~2510-2519) registers it with push_heap(.., true) and pick_heap (~1569, ~1578) filters by class. Two cases remain: the target whose video-memory CreateHeap failed still gets all its tiles from the sys = true class (~2512-2516), and a target placed over a live L0 page still shares it (~2488-2489). The description admits the second, but still says only sampled textures spill.
  • Each budget sample creates a DXGI factory: fixed. cached_adapter (memory_report.rs ~91-109) keeps the IDXGIAdapter3 per LUID; the description now gives frame times for the enabled run.
  • System-memory pools always counted as non-local: fixed (uma_segment(non_local), ~169).

New:

  • Each target bind under video-memory exhaustion retries a failing CreateHeap and logs two warnings. With the fallback heap in the sys = true class, the next gpu_owned bind finds no free tiles in the false class, calls alloc_pool_heap(dev, false) again (fails and warns at ~1717), then warns again at ~2514 before taking the L0 tiles. At 08f61a9a later binds reused the fallback heap without a new CreateHeap. Neither warning is rate-limited, and no test covers the new branch.

Fine: off by default, and with XCL_VRAM_BUDGET unset the !sys branch returns None as on the base; the GPU round-trip test has the COPY_DEST -> COPY_SOURCE barrier it was missing; PoolHeaps takes the class from the caller instead of GetDesc.

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

<!-- greyfinch-sync:ivall/xcl:comment:7334851757 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7334851757). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T04:23:01Z. --- Follow-up review (head b401f608, since 08f61a9a, diff read, not a merge-check): - **Render targets can still get system-memory pages:** partly fixed. Later targets no longer take tiles from a fallback heap: `bind_range` (`vram.rs` ~2510-2519) registers it with `push_heap(.., true)` and `pick_heap` (~1569, ~1578) filters by class. Two cases remain: the target whose video-memory `CreateHeap` failed still gets all its tiles from the `sys = true` class (~2512-2516), and a target placed over a live L0 page still shares it (~2488-2489). The description admits the second, but still says only sampled textures spill. - **Each budget sample creates a DXGI factory:** fixed. `cached_adapter` (`memory_report.rs` ~91-109) keeps the `IDXGIAdapter3` per LUID; the description now gives frame times for the enabled run. - **System-memory pools always counted as non-local:** fixed (`uma_segment(non_local)`, ~169). New: - **Each target bind under video-memory exhaustion retries a failing `CreateHeap` and logs two warnings.** With the fallback heap in the `sys = true` class, the next `gpu_owned` bind finds no free tiles in the `false` class, calls `alloc_pool_heap(dev, false)` again (fails and warns at ~1717), then warns again at ~2514 before taking the L0 tiles. At `08f61a9a` later binds reused the fallback heap without a new `CreateHeap`. Neither warning is rate-limited, and no test covers the new branch. Fine: off by default, and with `XCL_VRAM_BUDGET` unset the `!sys` branch returns `None` as on the base; the GPU round-trip test has the `COPY_DEST -> COPY_SOURCE` barrier it was missing; `PoolHeaps` takes the class from the caller instead of `GetDesc`. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
throny commented 2026-12-02 07:13:26 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by throny on 2026-12-02T07:13:26Z.


Retest of the new head b401f608 (on amd-dev, plus our local input-timing patch), RTX 4080 16 GB, same save and inputs, 900 s, XCL_RESIDENCY_PRIORITY=1, no draws skipped:

run head XCL_VRAM_BUDGET presents/s after 240 s video memory peak / budget
417 08f61a9a unset 2.67 16.4 / 15.1 GB
416 08f61a9a 1 2.05 14.4 / 15.1 GB
424 b401f608 1 2.57 15.5 / 15.1 GB
426 b401f608 1 2.71 15.7 / 15.1 GB

So the new head no longer costs frame rate (2.57–2.71 vs 2.67 without the switch), but it now ends slightly above the budget instead of under it (about 0.7–0.9 GB below the unset run). The unset run on the new head (425) ended with an access violation 82 s into the world before it could be compared, so the "unset" row is from the old head; I'd not read that crash as this PR's (it is the switch-off path), but it's noted.

AI use: Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:ivall/xcl:comment:7337923388 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7337923388). Originally posted by [throny](https://github.com/throny) on 2026-12-02T07:13:26Z. --- Retest of the new head `b401f608` (on `amd-dev`, plus our local input-timing patch), RTX 4080 16 GB, same save and inputs, 900 s, `XCL_RESIDENCY_PRIORITY=1`, no draws skipped: | run | head | `XCL_VRAM_BUDGET` | presents/s after 240 s | video memory peak / budget | |---|---|---|---|---| | 417 | `08f61a9a` | unset | 2.67 | 16.4 / 15.1 GB | | 416 | `08f61a9a` | 1 | 2.05 | 14.4 / 15.1 GB | | 424 | `b401f608` | 1 | 2.57 | 15.5 / 15.1 GB | | 426 | `b401f608` | 1 | 2.71 | 15.7 / 15.1 GB | So the new head no longer costs frame rate (2.57–2.71 vs 2.67 without the switch), but it now ends slightly above the budget instead of under it (about 0.7–0.9 GB below the unset run). The unset run on the new head (425) ended with an access violation 82 s into the world before it could be compared, so the "unset" row is from the old head; I'd not read that crash as this PR's (it is the switch-off path), but it's noted. AI use: Claude Code (Claude Opus 5.5).
throny commented 2026-12-02 07:45:54 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by throny on 2026-12-02T07:45:54Z.


The missing comparison on the new head b401f608, same setup: without XCL_VRAM_BUDGET 2.48 and 2.55 presents/s at 17.2 / 16.9 GB peak (runs 427, 428, both 900 s, no removal); with it 2.57 and 2.71 at 15.5 / 15.7 GB (runs 424, 426). So on this RTX 4080 the switch now saves about 1.3–1.5 GB of video memory and is, if anything, slightly faster. The earlier access violation (run 425) did not repeat.

AI use: Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:ivall/xcl:comment:7338580780 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7338580780). Originally posted by [throny](https://github.com/throny) on 2026-12-02T07:45:54Z. --- The missing comparison on the new head `b401f608`, same setup: without `XCL_VRAM_BUDGET` 2.48 and 2.55 presents/s at 17.2 / 16.9 GB peak (runs 427, 428, both 900 s, no removal); with it 2.57 and 2.71 at 15.5 / 15.7 GB (runs 424, 426). So on this RTX 4080 the switch now saves about 1.3–1.5 GB of video memory and is, if anything, slightly faster. The earlier access violation (run 425) did not repeat. AI use: Claude Code (Claude Opus 5.5).
iggyvilla commented 2026-12-02 07:58:36 +00:00 (Migrated from github.com)

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


Thanks @Foniass for the follow-up audit and @throny for the RTX 4080 retest! Updated #3587 (head 2ddf8227):

  • VRAM-OOM backoff & rate-limited warnings (vram.rs): Extracted take_tiles_with_fallback: when a video-memory CreateHeap fails under XCL_VRAM_BUDGET=1, Pages::vram_oom_until sets a 2 s cooldown (cleared on pool reclaim) so subsequent gpu_owned binds check existing free VRAM tiles and otherwise reuse the sys = true fallback pool directly without hammering failing CreateHeap every bind. Rate-limited both the alloc_pool_heap and fallback warnings (first 8 + powers of two).
  • Unit test: Added vram::tests::gpu_owned_vram_oom_falls_back_to_sys_class_and_backs_off_retries covering VRAM OOM fallback into sys = true, backoff reuse without retrying CreateHeap, VRAM recovery after backoff, and None when XCL_VRAM_BUDGET is unset.
  • Description: Explicitly noted both edge cases where a gpu_owned target can touch L0 pages (placement over an already-live L0 page, or video-memory CreateHeap OOM fallback under XCL_VRAM_BUDGET=1).
<!-- greyfinch-sync:ivall/xcl:comment:7338847801 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7338847801). Originally posted by [iggyvilla](https://github.com/iggyvilla) on 2026-12-02T07:58:36Z. --- Thanks @Foniass for the follow-up audit and @throny for the RTX 4080 retest! Updated #3587 (head `2ddf8227`): - **VRAM-OOM backoff & rate-limited warnings (`vram.rs`):** Extracted `take_tiles_with_fallback`: when a video-memory `CreateHeap` fails under `XCL_VRAM_BUDGET=1`, `Pages::vram_oom_until` sets a 2 s cooldown (cleared on pool reclaim) so subsequent `gpu_owned` binds check existing free VRAM tiles and otherwise reuse the `sys = true` fallback pool directly without hammering failing `CreateHeap` every bind. Rate-limited both the `alloc_pool_heap` and fallback warnings (first 8 + powers of two). - **Unit test:** Added `vram::tests::gpu_owned_vram_oom_falls_back_to_sys_class_and_backs_off_retries` covering VRAM OOM fallback into `sys = true`, backoff reuse without retrying `CreateHeap`, VRAM recovery after backoff, and `None` when `XCL_VRAM_BUDGET` is unset. - **Description:** Explicitly noted both edge cases where a `gpu_owned` target can touch L0 pages (placement over an already-live L0 page, or video-memory `CreateHeap` OOM fallback under `XCL_VRAM_BUDGET=1`).
Foniass commented 2026-12-02 08:01:08 +00:00 (Migrated from github.com)

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


Follow-up review (head 2ddf8227, since b401f608, diff read, not a merge-check):

  • Each target bind under exhaustion retries a failing CreateHeap with two un-rate-limited warnings: fixed. vram_oom_until with VRAM_OOM_BACKOFF (vram.rs ~1986-1991, ~2012-2017) skips the video-memory retry for 2 s, both warnings are rate-limited (~1716-1720, ~2025-2029), and gpu_owned_vram_oom_falls_back_to_sys_class_and_backs_off_retries (~6468) covers the fallback, the reuse within the backoff, recovery and the disabled path.
  • Render targets can still get system-memory pages: partly fixed. The description now names both cases (a target over a live L0 page, ~2490, and a target bound after a video-memory CreateHeap failure, through take_tiles_with_fallback, ~2012-2030, ~2556); the code is unchanged, and the commit message, which is what lands, still says "a sampled texture's pages (not render targets, depth, or UAVs)".

New:

  • The backoff ends when any empty pool heap is reclaimed, including an L0 one. sweep_and_reclaim (~2307-2308) clears vram_oom_until whenever dropped is non-empty, whatever the class, though dropping a system-memory heap returns no video memory. Under pressure reclaim runs every 250 ms with no spare kept, so when sampled-texture L0 heaps keep emptying, the next target bind retries the CreateHeap that just failed. The new test does not cover the reclaim path.

Fine: the default path is unchanged (with vram_budget::enabled() false the helper returns None without touching the backoff); a failed partial take in either class is rolled back before the other is tried, so one bind never mixes video-memory and L0 tiles; the helper takes the allocator as a closure, so the unit test exercises the real tile selection.

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

<!-- greyfinch-sync:ivall/xcl:comment:7338900254 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7338900254). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T08:01:08Z. --- Follow-up review (head 2ddf8227, since b401f608, diff read, not a merge-check): - **Each target bind under exhaustion retries a failing `CreateHeap` with two un-rate-limited warnings:** fixed. `vram_oom_until` with `VRAM_OOM_BACKOFF` (`vram.rs` ~1986-1991, ~2012-2017) skips the video-memory retry for 2 s, both warnings are rate-limited (~1716-1720, ~2025-2029), and `gpu_owned_vram_oom_falls_back_to_sys_class_and_backs_off_retries` (~6468) covers the fallback, the reuse within the backoff, recovery and the disabled path. - **Render targets can still get system-memory pages:** partly fixed. The description now names both cases (a target over a live L0 page, ~2490, and a target bound after a video-memory `CreateHeap` failure, through `take_tiles_with_fallback`, ~2012-2030, ~2556); the code is unchanged, and the commit message, which is what lands, still says "a sampled texture's pages (not render targets, depth, or UAVs)". New: - **The backoff ends when any empty pool heap is reclaimed, including an L0 one.** `sweep_and_reclaim` (~2307-2308) clears `vram_oom_until` whenever `dropped` is non-empty, whatever the class, though dropping a system-memory heap returns no video memory. Under pressure reclaim runs every 250 ms with no spare kept, so when sampled-texture L0 heaps keep emptying, the next target bind retries the `CreateHeap` that just failed. The new test does not cover the reclaim path. Fine: the default path is unchanged (with `vram_budget::enabled()` false the helper returns `None` without touching the backoff); a failed partial take in either class is rolled back before the other is tried, so one bind never mixes video-memory and L0 tiles; the helper takes the allocator as a closure, so the unit test exercises the real tile selection. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
throny commented 2026-12-02 10:07:53 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by throny on 2026-12-02T10:07:53Z.


Newest head 2ddf8227 (on amd-dev), same setup: with XCL_VRAM_BUDGET=1 2.68 and 2.50 presents/s at 15.7 / 16.0 GB (runs 434, 436), without it 2.26 at 17.2 GB (run 435); all 900 s, no removal. Consistent with the previous head: ~1.3–1.5 GB less video memory and no frame-rate cost.

AI use: Claude Code (Claude Opus 5.5).

<!-- greyfinch-sync:ivall/xcl:comment:7342008560 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7342008560). Originally posted by [throny](https://github.com/throny) on 2026-12-02T10:07:53Z. --- Newest head `2ddf8227` (on `amd-dev`), same setup: with `XCL_VRAM_BUDGET=1` 2.68 and 2.50 presents/s at 15.7 / 16.0 GB (runs 434, 436), without it 2.26 at 17.2 GB (run 435); all 900 s, no removal. Consistent with the previous head: ~1.3–1.5 GB less video memory and no frame-rate cost. AI use: Claude Code (Claude Opus 5.5).
thehollowedone commented 2026-12-02 12:10:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by thehollowedone on 2026-12-02T12:10:25Z.


Follow-up to Foniass's backoff finding on current head 2ddf8227: filtering reclaimed heaps by PoolHeaps::is_sys would avoid clearing the cooldown for an L0 heap, but it would still clear too early for a video-memory heap.

sweep_and_reclaim removes an empty heap from the pool and returns its COM reference; it does not release that allocation. before_execute hands it to retire_heaps_and_sweep, which holds heaps behind queue and unmap fence marks, then passes completed ones through late_release::hold_heap. Thus an immediate retry after either class is reclaimed can hit the same video-memory failure while the old heap is still live.

The small correction is to retain vram_oom_until through reclamation and let the existing retry interval expire. If earlier recovery is wanted, clear it only after confirmed video-heap destruction, with an epoch check so an older retirement cannot erase a newer OOM. Please add a regression that reclaims an L0 heap and a video heap during active cooldown and verifies neither causes an immediate CreateHeap retry; the current fallback test never calls reclaim. The reclaim log should also say heaps are scheduled for retirement rather than claiming VRAM has already returned.

Minimal candidate diff
diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs
@@ -2302,8 +2302,7 @@ impl Pages {
             }
         }
         if !dropped.is_empty() {
-            self.vram_oom_until = None;
             let mb = (dropped.len() * POOL_PAGES as usize * PAGE) >> 20;

This is a source review and an untested candidate, not a merge-check or GPU measurement. AI use: OpenAI Codex (GPT-6 Sol) traced the reclamation and retirement lifecycle.

<!-- greyfinch-sync:ivall/xcl:comment:7344944797 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7344944797). Originally posted by [thehollowedone](https://github.com/thehollowedone) on 2026-12-02T12:10:25Z. --- Follow-up to [Foniass's backoff finding](https://github.com/xcl-dev/xcl/pull/3587) on current head [`2ddf8227`](https://github.com/xcl-dev/xcl/commit/2ddf82273c40a2f02340bfa196084e62e8a6749e): filtering reclaimed heaps by `PoolHeaps::is_sys` would avoid clearing the cooldown for an L0 heap, but it would still clear too early for a video-memory heap. [`sweep_and_reclaim`](https://github.com/xcl-dev/xcl/blob/2ddf82273c40a2f02340bfa196084e62e8a6749e/crates/xcl/src/hle/d3d12x/vram.rs#L2297-L2316) removes an empty heap from the pool and returns its COM reference; it does not release that allocation. [`before_execute`](https://github.com/xcl-dev/xcl/blob/2ddf82273c40a2f02340bfa196084e62e8a6749e/crates/xcl/src/hle/d3d12x/vram.rs#L3250-L3295) hands it to `retire_heaps_and_sweep`, which holds heaps behind queue and unmap fence marks, then passes completed ones through `late_release::hold_heap`. Thus an immediate retry after *either* class is reclaimed can hit the same video-memory failure while the old heap is still live. The small correction is to retain `vram_oom_until` through reclamation and let the existing retry interval expire. If earlier recovery is wanted, clear it only after confirmed video-heap destruction, with an epoch check so an older retirement cannot erase a newer OOM. Please add a regression that reclaims an L0 heap and a video heap during active cooldown and verifies neither causes an immediate `CreateHeap` retry; the current fallback test never calls reclaim. The reclaim log should also say heaps are scheduled for retirement rather than claiming VRAM has already returned. <details> <summary>Minimal candidate diff</summary> ```diff diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs @@ -2302,8 +2302,7 @@ impl Pages { } } if !dropped.is_empty() { - self.vram_oom_until = None; let mb = (dropped.len() * POOL_PAGES as usize * PAGE) >> 20; ``` </details> This is a source review and an untested candidate, not a merge-check or GPU measurement. AI use: OpenAI Codex (GPT-6 Sol) traced the reclamation and retirement lifecycle.
Foniass commented 2026-12-02 13:11:29 +00:00 (Migrated from github.com)

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


merge-check
base: 41aa60ce84
head: 2ddf82273c
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2968 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/3587#issuecomment-7338900254 and its findings stand. Most serious: on the opt-in XCL_VRAM_BUDGET path, sweep_and_reclaim (vram.rs ~2307) ends the backoff when any empty heap is reclaimed, system-memory ones included, so the failing CreateHeap is retried; the commit message's "not render targets" doesn't hold.
performance: 60 s smoke of a retail title, amd-dev 41aa60ce vs this merge (2ddf8227): 1671 -> 1684 frames shown (100 %; last presents per 2 s: 60 60 60), peak commit 16722 -> 16818 MB, 0 device removals, 0 crashes.
verdict: safe to merge: no blocking finding in the review (the points there are minor), the suite passes and the smoke run is clean
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:7346489076 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7346489076). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T13:11:29Z. --- merge-check base: 41aa60ce842060a597b7e8724896f7bf6a031af5 head: 2ddf82273c40a2f02340bfa196084e62e8a6749e merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2968 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/3587#issuecomment-7338900254 and its findings stand. Most serious: on the opt-in `XCL_VRAM_BUDGET` path, `sweep_and_reclaim` (`vram.rs` ~2307) ends the backoff when any empty heap is reclaimed, system-memory ones included, so the failing `CreateHeap` is retried; the commit message's "not render targets" doesn't hold. performance: 60 s smoke of a retail title, amd-dev 41aa60ce vs this merge (2ddf8227): 1671 -> 1684 frames shown (100 %; last presents per 2 s: 60 60 60), peak commit 16722 -> 16818 MB, 0 device removals, 0 crashes. verdict: safe to merge: no blocking finding in the review (the points there are minor), the suite passes and the smoke run is clean 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:18:54 +00:00 (Migrated from github.com)

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

Code review location: crates/xcl/src/hle/d3d12x/vram_budget.rs; line 125

@@ -0,0 +1,188 @@
+//! Video memory budget tracking (`XCL_VRAM_BUDGET`).
+//!
+//! On an 8 GB adapter, world load can push local video memory far past DXGI's local `Budget`,
+//! forcing WDDM to page allocations across PCIe. When `XCL_VRAM_BUDGET=1` (off by default),
+//! XCL samples DXGI's local segment every 250 ms and shifts new sampled-texture pool heaps to
+//! system memory (L0), returns empty pool heaps sooner without a warm spare, and flushes parked
+//! sparse tiles sooner once usage reaches `Budget - margin` (or `XCL_VRAM_BUDGET_MB`).
+
+use std::sync::atomic::{AtomicU8, Ordering};
+use std::sync::{Mutex, OnceLock};
+use std::time::Duration;
+
+const MB: u64 = 1 << 20;
+/// Default headroom kept below DXGI's local `Budget` (2 GiB): large enough to start spilling
+/// streaming sampled textures before a ~2 GiB world-entry burst of render targets, two-pass
+/// buffers, and driver pipelines hits an 8 GB card, while staying dormant on 16 GB+ adapters
+/// under typical 8-10 GB loads. Override with `XCL_VRAM_BUDGET_MARGIN_MB`.
+const DEFAULT_MARGIN_MB: u64 = 2048;
+/// Usage must drop this far below the target before pressure returns to `Room` (avoids flapping).
+const HYSTERESIS: u64 = 256 * MB;
+/// Minimum interval between DXGI `QueryVideoMemoryInfo` samples.
+const SAMPLE_EVERY: Duration = Duration::from_millis(250);
+
+/// Whether `XCL_VRAM_BUDGET=1` is enabled (off by default).
+pub fn enabled() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        std::env::var("XCL_VRAM_BUDGET").ok().is_some_and(|v| {
+            let v = v.trim();
+            v == "1" || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("yes")
+        })
+    })
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct Settings {
+    pub margin: u64,
+    pub fixed: Option<u64>,
+}
+
+impl Settings {
+    fn from_env(margin: Option<&str>, fixed: Option<&str>) -> Self {
+        let margin_mb = margin
+            .and_then(|s| s.trim().parse::<u64>().ok())
+            .unwrap_or(DEFAULT_MARGIN_MB);
+        let fixed_mb = fixed
+            .and_then(|s| s.trim().parse::<u64>().ok())
+            .filter(|&mb| mb > 0);
+        Self {
+            margin: margin_mb.saturating_mul(MB),
+            fixed: fixed_mb.map(|mb| mb.saturating_mul(MB)),
+        }
+    }
+
+    pub(crate) fn target(&self, budget: u64) -> Option<u64> {
+        if let Some(fixed) = self.fixed {
+            return Some(fixed);
+        }
+        (budget > 0).then(|| budget.saturating_sub(self.margin))
+    }
+
+    pub(crate) fn pressure(&self, usage: u64, budget: u64, prev: Pressure) -> Pressure {
+        let Some(target) = self.target(budget) else {
+            return Pressure::Room;
+        };
+        if budget > 0 && usage >= budget {
+            return Pressure::Over;
+        }
+        if usage >= target {
+            return Pressure::Near;
+        }
+        if prev != Pressure::Room && usage >= target.saturating_sub(HYSTERESIS) {
+            return Pressure::Near;
+        }
+        Pressure::Room
+    }
+}
+
+fn settings() -> Settings {
+    static SETTINGS: OnceLock<Settings> = OnceLock::new();
+    *SETTINGS.get_or_init(|| {
+        let margin = std::env::var("XCL_VRAM_BUDGET_MARGIN_MB").ok();
+        let fixed = std::env::var("XCL_VRAM_BUDGET_MB").ok();
+        Settings::from_env(margin.as_deref(), fixed.as_deref())
+    })
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(u8)]
+pub enum Pressure {
+    Room = 0,
+    Near = 1,
+    Over = 2,
+}
+
+static PRESSURE: AtomicU8 = AtomicU8::new(Pressure::Room as u8);
+
+/// The pressure of the last sample (`Room` when off).
+pub fn pressure() -> Pressure {
+    match PRESSURE.load(Ordering::Relaxed) {
+        2 => Pressure::Over,
+        1 => Pressure::Near,
+        _ => Pressure::Room,
+    }
+}
+
+/// At or past the target: new sampled-texture pools in system memory, empty pools given back.
+pub fn tight() -> bool {
+    pressure() != Pressure::Room
+}
+
+/// Sample DXGI again when the last sample is older than `SAMPLE_EVERY` (one caller at a time;
+/// the others go on with the last one). Call it without XCL's memory locks held.
+pub fn refresh() {
+    static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None);
+    if !enabled() {
+        return;
+    }
+    let Ok(mut last) = LAST.try_lock() else { return };
+    let now = std::time::Instant::now();
+    if last.is_some_and(|at| now.saturating_duration_since(at) < SAMPLE_EVERY) {
+        return;
+    }
+    *last = Some(now);
+    let Some(local) = super::memory_report::local_segment() else { return };

High: When local_segment() returns None, refresh() returns without touching PRESSURE, so a Near/Over state can never go back to Room, and the cached IDXGIAdapter3 in memory_report is never dropped after a failed query. Suppose pressure reaches Near during world load and QueryVideoMemoryInfo then starts failing (the cached adapter is stale after a TDR or driver reset with the same LUID, or device_raw() is null during teardown or recreation). Every later refresh() bails out early and tight() stays true for the rest of the session: every new sampled texture goes to L0 system memory, there are no warm spare pools, reclaim runs every 250 ms, and sparse tiles flush at 256. CACHE (memory_report.rs:100) keeps returning the same broken adapter, so it never recovers. Decaying to Room (and dropping the cached adapter) after a failed query would avoid it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771820086 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#discussion_r4771820086). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:18:54Z. **Code review location:** `crates/xcl/src/hle/d3d12x/vram_budget.rs`; line 125 ~~~~diff @@ -0,0 +1,188 @@ +//! Video memory budget tracking (`XCL_VRAM_BUDGET`). +//! +//! On an 8 GB adapter, world load can push local video memory far past DXGI's local `Budget`, +//! forcing WDDM to page allocations across PCIe. When `XCL_VRAM_BUDGET=1` (off by default), +//! XCL samples DXGI's local segment every 250 ms and shifts new sampled-texture pool heaps to +//! system memory (L0), returns empty pool heaps sooner without a warm spare, and flushes parked +//! sparse tiles sooner once usage reaches `Budget - margin` (or `XCL_VRAM_BUDGET_MB`). + +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +const MB: u64 = 1 << 20; +/// Default headroom kept below DXGI's local `Budget` (2 GiB): large enough to start spilling +/// streaming sampled textures before a ~2 GiB world-entry burst of render targets, two-pass +/// buffers, and driver pipelines hits an 8 GB card, while staying dormant on 16 GB+ adapters +/// under typical 8-10 GB loads. Override with `XCL_VRAM_BUDGET_MARGIN_MB`. +const DEFAULT_MARGIN_MB: u64 = 2048; +/// Usage must drop this far below the target before pressure returns to `Room` (avoids flapping). +const HYSTERESIS: u64 = 256 * MB; +/// Minimum interval between DXGI `QueryVideoMemoryInfo` samples. +const SAMPLE_EVERY: Duration = Duration::from_millis(250); + +/// Whether `XCL_VRAM_BUDGET=1` is enabled (off by default). +pub fn enabled() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("XCL_VRAM_BUDGET").ok().is_some_and(|v| { + let v = v.trim(); + v == "1" || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("yes") + }) + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Settings { + pub margin: u64, + pub fixed: Option<u64>, +} + +impl Settings { + fn from_env(margin: Option<&str>, fixed: Option<&str>) -> Self { + let margin_mb = margin + .and_then(|s| s.trim().parse::<u64>().ok()) + .unwrap_or(DEFAULT_MARGIN_MB); + let fixed_mb = fixed + .and_then(|s| s.trim().parse::<u64>().ok()) + .filter(|&mb| mb > 0); + Self { + margin: margin_mb.saturating_mul(MB), + fixed: fixed_mb.map(|mb| mb.saturating_mul(MB)), + } + } + + pub(crate) fn target(&self, budget: u64) -> Option<u64> { + if let Some(fixed) = self.fixed { + return Some(fixed); + } + (budget > 0).then(|| budget.saturating_sub(self.margin)) + } + + pub(crate) fn pressure(&self, usage: u64, budget: u64, prev: Pressure) -> Pressure { + let Some(target) = self.target(budget) else { + return Pressure::Room; + }; + if budget > 0 && usage >= budget { + return Pressure::Over; + } + if usage >= target { + return Pressure::Near; + } + if prev != Pressure::Room && usage >= target.saturating_sub(HYSTERESIS) { + return Pressure::Near; + } + Pressure::Room + } +} + +fn settings() -> Settings { + static SETTINGS: OnceLock<Settings> = OnceLock::new(); + *SETTINGS.get_or_init(|| { + let margin = std::env::var("XCL_VRAM_BUDGET_MARGIN_MB").ok(); + let fixed = std::env::var("XCL_VRAM_BUDGET_MB").ok(); + Settings::from_env(margin.as_deref(), fixed.as_deref()) + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[repr(u8)] +pub enum Pressure { + Room = 0, + Near = 1, + Over = 2, +} + +static PRESSURE: AtomicU8 = AtomicU8::new(Pressure::Room as u8); + +/// The pressure of the last sample (`Room` when off). +pub fn pressure() -> Pressure { + match PRESSURE.load(Ordering::Relaxed) { + 2 => Pressure::Over, + 1 => Pressure::Near, + _ => Pressure::Room, + } +} + +/// At or past the target: new sampled-texture pools in system memory, empty pools given back. +pub fn tight() -> bool { + pressure() != Pressure::Room +} + +/// Sample DXGI again when the last sample is older than `SAMPLE_EVERY` (one caller at a time; +/// the others go on with the last one). Call it without XCL's memory locks held. +pub fn refresh() { + static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None); + if !enabled() { + return; + } + let Ok(mut last) = LAST.try_lock() else { return }; + let now = std::time::Instant::now(); + if last.is_some_and(|at| now.saturating_duration_since(at) < SAMPLE_EVERY) { + return; + } + *last = Some(now); + let Some(local) = super::memory_report::local_segment() else { return }; ~~~~ --- **High**: When `local_segment()` returns None, `refresh()` returns without touching PRESSURE, so a Near/Over state can never go back to Room, and the cached IDXGIAdapter3 in memory_report is never dropped after a failed query. Suppose pressure reaches Near during world load and QueryVideoMemoryInfo then starts failing (the cached adapter is stale after a TDR or driver reset with the same LUID, or `device_raw()` is null during teardown or recreation). Every later `refresh()` bails out early and `tight()` stays true for the rest of the session: every new sampled texture goes to L0 system memory, there are no warm spare pools, reclaim runs every 250 ms, and sparse tiles flush at 256. CACHE (memory_report.rs:100) keeps returning the same broken adapter, so it never recovers. Decaying to Room (and dropping the cached adapter) after a failed query would avoid it.
bmjask commented 2026-12-02 15:18:54 +00:00 (Migrated from github.com)

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

Code review location: crates/xcl/src/hle/d3d12x/vram_budget.rs; line 72

@@ -0,0 +1,188 @@
+//! Video memory budget tracking (`XCL_VRAM_BUDGET`).
+//!
+//! On an 8 GB adapter, world load can push local video memory far past DXGI's local `Budget`,
+//! forcing WDDM to page allocations across PCIe. When `XCL_VRAM_BUDGET=1` (off by default),
+//! XCL samples DXGI's local segment every 250 ms and shifts new sampled-texture pool heaps to
+//! system memory (L0), returns empty pool heaps sooner without a warm spare, and flushes parked
+//! sparse tiles sooner once usage reaches `Budget - margin` (or `XCL_VRAM_BUDGET_MB`).
+
+use std::sync::atomic::{AtomicU8, Ordering};
+use std::sync::{Mutex, OnceLock};
+use std::time::Duration;
+
+const MB: u64 = 1 << 20;
+/// Default headroom kept below DXGI's local `Budget` (2 GiB): large enough to start spilling
+/// streaming sampled textures before a ~2 GiB world-entry burst of render targets, two-pass
+/// buffers, and driver pipelines hits an 8 GB card, while staying dormant on 16 GB+ adapters
+/// under typical 8-10 GB loads. Override with `XCL_VRAM_BUDGET_MARGIN_MB`.
+const DEFAULT_MARGIN_MB: u64 = 2048;
+/// Usage must drop this far below the target before pressure returns to `Room` (avoids flapping).
+const HYSTERESIS: u64 = 256 * MB;
+/// Minimum interval between DXGI `QueryVideoMemoryInfo` samples.
+const SAMPLE_EVERY: Duration = Duration::from_millis(250);
+
+/// Whether `XCL_VRAM_BUDGET=1` is enabled (off by default).
+pub fn enabled() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| {
+        std::env::var("XCL_VRAM_BUDGET").ok().is_some_and(|v| {
+            let v = v.trim();
+            v == "1" || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("yes")
+        })
+    })
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct Settings {
+    pub margin: u64,
+    pub fixed: Option<u64>,
+}
+
+impl Settings {
+    fn from_env(margin: Option<&str>, fixed: Option<&str>) -> Self {
+        let margin_mb = margin
+            .and_then(|s| s.trim().parse::<u64>().ok())
+            .unwrap_or(DEFAULT_MARGIN_MB);
+        let fixed_mb = fixed
+            .and_then(|s| s.trim().parse::<u64>().ok())
+            .filter(|&mb| mb > 0);
+        Self {
+            margin: margin_mb.saturating_mul(MB),
+            fixed: fixed_mb.map(|mb| mb.saturating_mul(MB)),
+        }
+    }
+
+    pub(crate) fn target(&self, budget: u64) -> Option<u64> {
+        if let Some(fixed) = self.fixed {
+            return Some(fixed);
+        }
+        (budget > 0).then(|| budget.saturating_sub(self.margin))
+    }
+
+    pub(crate) fn pressure(&self, usage: u64, budget: u64, prev: Pressure) -> Pressure {
+        let Some(target) = self.target(budget) else {
+            return Pressure::Room;
+        };
+        if budget > 0 && usage >= budget {
+            return Pressure::Over;
+        }
+        if usage >= target {
+            return Pressure::Near;
+        }
+        if prev != Pressure::Room && usage >= target.saturating_sub(HYSTERESIS) {

High: The hysteresis uses target.saturating_sub(HYSTERESIS), so when target < 256 MiB, or the margin is at least the budget (target = Some(0)), pressure can never return to Room. The fixed 2048 MiB default margin also makes small cards tight from the start: on a 4 GB card (DXGI budget ~3.5 GB) the target is ~1.5 GB, so nearly every session is tight from launch. With XCL_VRAM_BUDGET_MARGIN_MB at or above budget - 256 MiB, or on a small-budget adapter, target - 256 MiB is 0, usage >= 0 always holds once Near, and every sampled texture goes to L0 for the whole run. A margin proportional to the budget, and a floor on the hysteresis target, would fix both.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771820096 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#discussion_r4771820096). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:18:54Z. **Code review location:** `crates/xcl/src/hle/d3d12x/vram_budget.rs`; line 72 ~~~~diff @@ -0,0 +1,188 @@ +//! Video memory budget tracking (`XCL_VRAM_BUDGET`). +//! +//! On an 8 GB adapter, world load can push local video memory far past DXGI's local `Budget`, +//! forcing WDDM to page allocations across PCIe. When `XCL_VRAM_BUDGET=1` (off by default), +//! XCL samples DXGI's local segment every 250 ms and shifts new sampled-texture pool heaps to +//! system memory (L0), returns empty pool heaps sooner without a warm spare, and flushes parked +//! sparse tiles sooner once usage reaches `Budget - margin` (or `XCL_VRAM_BUDGET_MB`). + +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +const MB: u64 = 1 << 20; +/// Default headroom kept below DXGI's local `Budget` (2 GiB): large enough to start spilling +/// streaming sampled textures before a ~2 GiB world-entry burst of render targets, two-pass +/// buffers, and driver pipelines hits an 8 GB card, while staying dormant on 16 GB+ adapters +/// under typical 8-10 GB loads. Override with `XCL_VRAM_BUDGET_MARGIN_MB`. +const DEFAULT_MARGIN_MB: u64 = 2048; +/// Usage must drop this far below the target before pressure returns to `Room` (avoids flapping). +const HYSTERESIS: u64 = 256 * MB; +/// Minimum interval between DXGI `QueryVideoMemoryInfo` samples. +const SAMPLE_EVERY: Duration = Duration::from_millis(250); + +/// Whether `XCL_VRAM_BUDGET=1` is enabled (off by default). +pub fn enabled() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + std::env::var("XCL_VRAM_BUDGET").ok().is_some_and(|v| { + let v = v.trim(); + v == "1" || v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("yes") + }) + }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Settings { + pub margin: u64, + pub fixed: Option<u64>, +} + +impl Settings { + fn from_env(margin: Option<&str>, fixed: Option<&str>) -> Self { + let margin_mb = margin + .and_then(|s| s.trim().parse::<u64>().ok()) + .unwrap_or(DEFAULT_MARGIN_MB); + let fixed_mb = fixed + .and_then(|s| s.trim().parse::<u64>().ok()) + .filter(|&mb| mb > 0); + Self { + margin: margin_mb.saturating_mul(MB), + fixed: fixed_mb.map(|mb| mb.saturating_mul(MB)), + } + } + + pub(crate) fn target(&self, budget: u64) -> Option<u64> { + if let Some(fixed) = self.fixed { + return Some(fixed); + } + (budget > 0).then(|| budget.saturating_sub(self.margin)) + } + + pub(crate) fn pressure(&self, usage: u64, budget: u64, prev: Pressure) -> Pressure { + let Some(target) = self.target(budget) else { + return Pressure::Room; + }; + if budget > 0 && usage >= budget { + return Pressure::Over; + } + if usage >= target { + return Pressure::Near; + } + if prev != Pressure::Room && usage >= target.saturating_sub(HYSTERESIS) { ~~~~ --- **High**: The hysteresis uses `target.saturating_sub(HYSTERESIS)`, so when target < 256 MiB, or the margin is at least the budget (target = Some(0)), pressure can never return to Room. The fixed 2048 MiB default margin also makes small cards tight from the start: on a 4 GB card (DXGI budget ~3.5 GB) the target is ~1.5 GB, so nearly every session is tight from launch. With XCL_VRAM_BUDGET_MARGIN_MB at or above budget - 256 MiB, or on a small-budget adapter, `target - 256 MiB` is 0, `usage >= 0` always holds once Near, and every sampled texture goes to L0 for the whole run. A margin proportional to the budget, and a floor on the hysteresis target, would fix both.
bmjask commented 2026-12-02 15:18:54 +00:00 (Migrated from github.com)

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

Code review location: crates/xcl/src/hle/d3d12x/vram.rs; line 2006

@@ -1922,6 +1983,54 @@ struct Pages {
     zero_ring: Option<ZeroRing>,
     /// true once `ZeroRing::new` failed so we don't retry every submit
     zero_ring_failed: bool,
+    /// cooldown after a video-memory `CreateHeap` failure under `XCL_VRAM_BUDGET` so subsequent
+    /// `gpu_owned` binds reuse the `sys = true` fallback class instead of retrying every bind
+    vram_oom_until: Option<std::time::Instant>,
+}
+
+const VRAM_OOM_BACKOFF: std::time::Duration = std::time::Duration::from_secs(2);
+
+#[allow(clippy::too_many_arguments)]
+fn take_tiles_with_fallback(
+    pool: &mut TilePool,
+    missing: usize,
+    preferred: Option<u32>,
+    sys: bool,
+    allow_sys_fallback: bool,
+    now: std::time::Instant,
+    pool_pages: u32,
+    pending_zero: &mut Vec<Tile>,
+    vram_oom_until: &mut Option<std::time::Instant>,
+    mut alloc: impl FnMut(bool) -> Option<u32>,
+) -> Option<Vec<Tile>> {
+    if sys {

High: The sys path in take_tiles_with_fallback never falls back to a video-memory heap, so if the L0 CreateHeap fails the whole bind fails, where a DEFAULT heap would have worked before this PR. Under pressure the process commit is high (the PR reports 16-23 GB), so CreateHeap(CUSTOM/L0) fails with E_OUTOFMEMORY, or the driver rejects CUSTOM L0 heaps for tiled mappings. A sampled texture with missing pages then gets None from bind(), place_on_pages frees the reserved resource and drops off the paged path, or remap_if_unmapped / map_levels leave it unmapped. Trying the VRAM path when L0 creation fails would keep the old behaviour as the floor.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771820104 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#discussion_r4771820104). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:18:54Z. **Code review location:** `crates/xcl/src/hle/d3d12x/vram.rs`; line 2006 ~~~~diff @@ -1922,6 +1983,54 @@ struct Pages { zero_ring: Option<ZeroRing>, /// true once `ZeroRing::new` failed so we don't retry every submit zero_ring_failed: bool, + /// cooldown after a video-memory `CreateHeap` failure under `XCL_VRAM_BUDGET` so subsequent + /// `gpu_owned` binds reuse the `sys = true` fallback class instead of retrying every bind + vram_oom_until: Option<std::time::Instant>, +} + +const VRAM_OOM_BACKOFF: std::time::Duration = std::time::Duration::from_secs(2); + +#[allow(clippy::too_many_arguments)] +fn take_tiles_with_fallback( + pool: &mut TilePool, + missing: usize, + preferred: Option<u32>, + sys: bool, + allow_sys_fallback: bool, + now: std::time::Instant, + pool_pages: u32, + pending_zero: &mut Vec<Tile>, + vram_oom_until: &mut Option<std::time::Instant>, + mut alloc: impl FnMut(bool) -> Option<u32>, +) -> Option<Vec<Tile>> { + if sys { ~~~~ --- **High**: The sys path in `take_tiles_with_fallback` never falls back to a video-memory heap, so if the L0 CreateHeap fails the whole bind fails, where a DEFAULT heap would have worked before this PR. Under pressure the process commit is high (the PR reports 16-23 GB), so CreateHeap(CUSTOM/L0) fails with E_OUTOFMEMORY, or the driver rejects CUSTOM L0 heaps for tiled mappings. A sampled texture with missing pages then gets None from `bind()`, `place_on_pages` frees the reserved resource and drops off the paged path, or `remap_if_unmapped` / `map_levels` leave it unmapped. Trying the VRAM path when L0 creation fails would keep the old behaviour as the floor.
bmjask commented 2026-12-02 15:18:54 +00:00 (Migrated from github.com)

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

Code review location: crates/xcl/src/hle/d3d12x/vram.rs; line 2944

@@ -2787,6 +2941,8 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool {
         return false;
     }
     let Some(dev) = dev else { return false };
+    super::vram_budget::refresh();

Medium: Not certain about this one: remap_if_unmapped now calls vram_budget::refresh(), whose own doc says to call it without XCL's memory locks held, but placements::map_again calls remap_if_unmapped while holding REGISTRY.lock() (from placed(), settle() and the reuse path). When the 250 ms sample is due, refresh() runs QueryVideoMemoryInfo, and on the first call also CreateDXGIFactory1 + EnumAdapterByLuid, all inside REGISTRY. Every streaming thread placing textures waits on that kernel call, and anything in DXGI factory creation that reaches XCL hooks taking REGISTRY would deadlock. Refreshing after the lock is released would avoid it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771820112 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#discussion_r4771820112). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:18:54Z. **Code review location:** `crates/xcl/src/hle/d3d12x/vram.rs`; line 2944 ~~~~diff @@ -2787,6 +2941,8 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { return false; } let Some(dev) = dev else { return false }; + super::vram_budget::refresh(); ~~~~ --- **Medium**: Not certain about this one: `remap_if_unmapped` now calls `vram_budget::refresh()`, whose own doc says to call it without XCL's memory locks held, but `placements::map_again` calls `remap_if_unmapped` while holding REGISTRY.lock() (from placed(), settle() and the reuse path). When the 250 ms sample is due, `refresh()` runs QueryVideoMemoryInfo, and on the first call also CreateDXGIFactory1 + EnumAdapterByLuid, all inside REGISTRY. Every streaming thread placing textures waits on that kernel call, and anything in DXGI factory creation that reaches XCL hooks taking REGISTRY would deadlock. Refreshing after the lock is released would avoid it.
bmjask commented 2026-12-02 15:18:54 +00:00 (Migrated from github.com)

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

Code review location: crates/xcl/src/hle/d3d12x/vram.rs; line 2308

@@ -2187,14 +2297,15 @@ impl Pages {
     fn sweep_and_reclaim(&mut self, now: std::time::Instant) -> Vec<ID3D12Heap> {
         self.sweep(now);
         self.pool.drain_cooling(now);
-        let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare_pools(), POOL_PAGES);
+        let reclaimed_ids = self.pool.reclaim_empty_heaps(spare_pools_for(keep_spare_pools(), super::vram_budget::tight()), POOL_PAGES);
         let mut dropped = Vec::with_capacity(reclaimed_ids.len());
         for idx in reclaimed_ids {
             if let Some(h) = self.pools.take_heap(idx) {
                 dropped.push(h);
             }
         }
         if !dropped.is_empty() {
+            self.vram_oom_until = None;

Medium: sweep_and_reclaim clears vram_oom_until whenever any heap is reclaimed, including L0 heaps that free no video memory, and logs every reclaim as a VRAM heap returned to the GPU. Under XCL_VRAM_BUDGET=1, a failed video-memory CreateHeap sets a 2 s backoff, but while tight reclaim runs every 250 ms with 0 spares, so an emptied sys heap is reclaimed almost at once and the backoff is cleared. The next gpu_owned bind retries the failing CreateHeap and logs another failure, so the 2 s backoff lasts at most ~250 ms. Only clearing it when a VRAM-class heap is reclaimed would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771820122 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#discussion_r4771820122). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:18:54Z. **Code review location:** `crates/xcl/src/hle/d3d12x/vram.rs`; line 2308 ~~~~diff @@ -2187,14 +2297,15 @@ impl Pages { fn sweep_and_reclaim(&mut self, now: std::time::Instant) -> Vec<ID3D12Heap> { self.sweep(now); self.pool.drain_cooling(now); - let reclaimed_ids = self.pool.reclaim_empty_heaps(keep_spare_pools(), POOL_PAGES); + let reclaimed_ids = self.pool.reclaim_empty_heaps(spare_pools_for(keep_spare_pools(), super::vram_budget::tight()), POOL_PAGES); let mut dropped = Vec::with_capacity(reclaimed_ids.len()); for idx in reclaimed_ids { if let Some(h) = self.pools.take_heap(idx) { dropped.push(h); } } if !dropped.is_empty() { + self.vram_oom_until = None; ~~~~ --- **Medium**: `sweep_and_reclaim` clears `vram_oom_until` whenever any heap is reclaimed, including L0 heaps that free no video memory, and logs every reclaim as a VRAM heap returned to the GPU. Under XCL_VRAM_BUDGET=1, a failed video-memory CreateHeap sets a 2 s backoff, but while tight reclaim runs every 250 ms with 0 spares, so an emptied sys heap is reclaimed almost at once and the backoff is cleared. The next gpu_owned bind retries the failing CreateHeap and logs another failure, so the 2 s backoff lasts at most ~250 ms. Only clearing it when a VRAM-class heap is reclaimed would fix it.
bmjask commented 2026-12-02 15:18:54 +00:00 (Migrated from github.com)

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

Review: COMMENTED


Review of 2ddf8227: 5 finding(s) (3 high, 2 medium), most severe first.

  1. High crates/xcl/src/hle/d3d12x/vram_budget.rs:125: When local_segment() returns None, refresh() returns without touching PRESSURE, so a Near/Over state can never go back to Room, and the cached IDXGIAdapter3 in memory_report is never dropped after a failed query. (inline)
  2. High crates/xcl/src/hle/d3d12x/vram_budget.rs:72: The hysteresis uses target.saturating_sub(HYSTERESIS), so when target < 256 MiB, or the margin is at least the budget (target = Some(0)), pressure can never return to Room. (inline)
  3. High crates/xcl/src/hle/d3d12x/vram.rs:2006: The sys path in take_tiles_with_fallback never falls back to a video-memory heap, so if the L0 CreateHeap fails the whole bind fails, where a DEFAULT heap would have worked before this PR. (inline)
  4. Medium crates/xcl/src/hle/d3d12x/vram.rs:2944: Not certain about this one: remap_if_unmapped now calls vram_budget::refresh(), whose own doc says to call it without XCL's memory locks held, but placements::map_again calls remap_if_unmapped while holding REGISTRY.lock() (from .... (inline)
  5. Medium crates/xcl/src/hle/d3d12x/vram.rs:2308: sweep_and_reclaim clears vram_oom_until whenever any heap is reclaimed, including L0 heaps that free no video memory, and logs every reclaim as a VRAM heap returned to the GPU. (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:6153701987 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#pullrequestreview-6153701987). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:18:54Z. **Review:** COMMENTED --- Review of `2ddf8227`: 5 finding(s) (3 high, 2 medium), most severe first. 1. **High** `crates/xcl/src/hle/d3d12x/vram_budget.rs:125`: When `local_segment()` returns None, `refresh()` returns without touching PRESSURE, so a Near/Over state can never go back to Room, and the cached IDXGIAdapter3 in memory_report is never dropped after a failed query. (inline) 2. **High** `crates/xcl/src/hle/d3d12x/vram_budget.rs:72`: The hysteresis uses `target.saturating_sub(HYSTERESIS)`, so when target < 256 MiB, or the margin is at least the budget (target = Some(0)), pressure can never return to Room. (inline) 3. **High** `crates/xcl/src/hle/d3d12x/vram.rs:2006`: The sys path in `take_tiles_with_fallback` never falls back to a video-memory heap, so if the L0 CreateHeap fails the whole bind fails, where a DEFAULT heap would have worked before this PR. (inline) 4. **Medium** `crates/xcl/src/hle/d3d12x/vram.rs:2944`: Not certain about this one: `remap_if_unmapped` now calls `vram_budget::refresh()`, whose own doc says to call it without XCL's memory locks held, but `placements::map_again` calls `remap_if_unmapped` while holding REGISTRY.lock() (from .... (inline) 5. **Medium** `crates/xcl/src/hle/d3d12x/vram.rs:2308`: `sweep_and_reclaim` clears `vram_oom_until` whenever any heap is reclaimed, including L0 heaps that free no video memory, and logs every reclaim as a VRAM heap returned to the GPU. (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:19:03 +00:00 (Migrated from github.com)

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


@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:7350117498 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7350117498). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:19:03Z. --- @Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
stijn-boer commented 2026-12-02 18:50:01 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by stijn-boer on 2026-12-02T18:50:01Z.


merge-check
base: 41aa60ce84
head: 2ddf82273c
verdict: not yet: the focused tests passed, but the workspace runs aborted at different points and retail budget behavior remains unverified.

Windows / AMD RDNA4 — VRAM budget and fallback checks on 2ddf822

The current amd-dev base fast-forwarded cleanly to the PR head. git diff --check was clean.

Setup

AMD Radeon RX 9060 XT (32.0.32029.2010), Ryzen 7 5700X, Windows 10 21H2 build 19044.6332, Rust 1.100.0 debug, Agility 1.620.2 with matching debug layer, DXC 1.9.2609.5.

Tested

cargo build --workspace passed on both builds. cargo test --workspace --no-fail-fast -- --test-threads=4 --show-output exited 101 on both.

Build Passed Failed Ignored SKIPPED notices
amd-dev 178 2 20 1
Merged PR 2144 3 44 8

These are partial counts. Both had two failures of two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs. The library exited 0xc0000005 on base and 0x80004005 on the PR, where fuzz_validate_and_gpu_1 also failed. Base did not supply a result for that test. The base logged one heap-windows skip. The merge logged that skip plus one additional heap-windows skip and six unsupported f16/f32 instruction cases. Both debug-layer E2E tests and the texture-state check passed on both builds.

The seven new focused tests passed with --test-threads=1 --show-output --nocapture, with 0 failures, 0 ignored, and 0 skip notices. This includes AMD readback from a system-memory pool, simulated VRAM allocation failure and retry backoff, reclamation policy, and target hysteresis.

Retail smoke

Ran scripts/smoke.ps1 -Game <local folder> -Seconds 60 -Xcl <debug binary> with XCL_UMA_DRIVER=mixed for title hash 2c508222, with the budget feature unset. Both builds hit the 180-second outer timeout. The smoke script did not receive a log path from either process. The local logs had no final frame summary or device-removal notice. I stopped both leftover test children after their launchers timed out.

Not tested

Comparable full-suite results, retail frame or memory behavior, and live budget-enabled retail use. The focused tests exercised the allocation policy independently.

AI use

Codex (GPT-6) merged and built the PR, ran the tests and smoke checks, compared the results with amd-dev, and drafted this report.

<!-- greyfinch-sync:ivall/xcl:comment:7355221750 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3587#issuecomment-7355221750). Originally posted by [stijn-boer](https://github.com/stijn-boer) on 2026-12-02T18:50:01Z. --- merge-check base: 41aa60ce842060a597b7e8724896f7bf6a031af5 head: 2ddf82273c40a2f02340bfa196084e62e8a6749e verdict: not yet: the focused tests passed, but the workspace runs aborted at different points and retail budget behavior remains unverified. **Windows / AMD RDNA4 — VRAM budget and fallback checks on `2ddf822`** The current `amd-dev` base fast-forwarded cleanly to the PR head. `git diff --check` was clean. **Setup** AMD Radeon RX 9060 XT (32.0.32029.2010), Ryzen 7 5700X, Windows 10 21H2 build 19044.6332, Rust 1.100.0 debug, Agility 1.620.2 with matching debug layer, DXC 1.9.2609.5. **Tested** `cargo build --workspace` passed on both builds. `cargo test --workspace --no-fail-fast -- --test-threads=4 --show-output` exited 101 on both. | Build | Passed | Failed | Ignored | `SKIPPED` notices | |---|---:|---:|---:|---:| | `amd-dev` | 178 | 2 | 20 | 1 | | Merged PR | 2144 | 3 | 44 | 8 | These are partial counts. Both had two failures of `two_pass_driver_cache_reuses_both_passes_and_recovers_corrupt_blobs`. The library exited `0xc0000005` on base and `0x80004005` on the PR, where `fuzz_validate_and_gpu_1` also failed. Base did not supply a result for that test. The base logged one heap-windows skip. The merge logged that skip plus one additional heap-windows skip and six unsupported f16/f32 instruction cases. Both debug-layer E2E tests and the texture-state check passed on both builds. The seven new focused tests passed with `--test-threads=1 --show-output --nocapture`, with 0 failures, 0 ignored, and 0 skip notices. This includes AMD readback from a system-memory pool, simulated VRAM allocation failure and retry backoff, reclamation policy, and target hysteresis. **Retail smoke** Ran `scripts/smoke.ps1 -Game <local folder> -Seconds 60 -Xcl <debug binary>` with `XCL_UMA_DRIVER=mixed` for title hash `2c508222`, with the budget feature unset. Both builds hit the 180-second outer timeout. The smoke script did not receive a log path from either process. The local logs had no final frame summary or device-removal notice. I stopped both leftover test children after their launchers timed out. **Not tested** Comparable full-suite results, retail frame or memory behavior, and live budget-enabled retail use. The focused tests exercised the allocation policy independently. **AI use** Codex (GPT-6) merged and built the PR, ran the tests and smoke checks, compared the results with `amd-dev`, and drafted this report.
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/3587:upstream-pr/3587'
git switch 'upstream-pr/3587'

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