Skip to content

D3D12.X: drop global FENCES lock across GetCompletedValue and scope CPU-signal refreshes to the signalled fence - #2649

Open
Decodere wants to merge 1 commit into
xcl-dev:mainfrom
Decodere:fix-fence-x-lockfree-refresh-and-scoped-signal
Open

Decodere wants to merge 1 commit into
xcl-dev:mainfrom
Decodere:fix-fence-x-lockfree-refresh-and-scoped-signal

Conversation

@Decodere

Copy link
Copy Markdown
Contributor

What is in it

Part of #1833
Part of #1773

crates/xcl/src/hle/d3d12x/fence_x.rs previously held the global FENCES: Mutex<Option<HashMap<usize, Fence>>> lock across D3D12 COM ID3D12Fence::GetCompletedValue() calls in refresh() and pending_summary(), serializing concurrent note_queue_signal, note_queue_wait, note_cpu_signal, and completed_value_address calls behind driver calls. In addition, note_cpu_signal() locked FENCES twice and invoked full-table refresh() (scanning every tracked fence including non-cell fences), and completed_value_address() refreshed all fences instead of only the newly published fence.

Scoped solely to crates/xcl/src/hle/d3d12x/fence_x.rs (+264/-63 lines; the_cell_follows_the_fence untouched, and does not duplicate #906 rewind polling, #1297 intermediate pre-cell arming, or #1411 Wine WARP fallback):

  • Kept #[repr(C, align(64))] struct Cell(AtomicU64) and wrapped each cell in struct CellMirror { cell: Box<Cell>, refresh_lock: Mutex<bool> } (true = live, false = retired). Keeping Box<Cell> on its own heap cache line preserves permanent *const u64 addresses and prevents refresh_lock traffic from false-sharing title monitorx/mwaitx wakes.
  • Replaced static FENCES with struct FenceTable { inner: Mutex<State> } (State { map: HashMap<usize, Fence>, cells: Vec<(usize, Arc<CellMirror>)> }, singleton table() -> &'static FenceTable) so unit tests can exercise isolated tables without polluting global state.
  • FenceTable::refresh_one(fence, mirror) acquires only mirror.refresh_lock, returns immediately if !*live, calls borrowed(fence, |f| f.GetCompletedValue()), and stores Ordering::Release into mirror.cell.0 — serializing concurrent updates per fence without holding the global table lock.
  • FenceTable::refresh() clones state.cells, drops self.inner, and refreshes only cell-backed fences lock-free (skipping all non-cell fences).
  • FenceTable::note_cpu_signal(fence) locks self.inner once, clones f.cell for only fence, drops self.inner, and calls refresh_one on that single fence.
  • FenceTable::completed_value_address_with(this, arm_fn) returns immediately if a cell already exists; otherwise publishes Arc<CellMirror> to map and cells, drops self.inner, invokes arm_fn when pending > 0, refreshes only this, and returns mirror.cell.0.as_ptr().
  • FenceTable::pending_summary() snapshots (p, signalled, waited, has_cell) under self.inner, drops the lock, then queries GetCompletedValue() lock-free and formats the exact same diagnostic string.
  • FenceTable::forget_fence(fence) (wired to forget_fence_for_test) removes the entry from map and cells, drops self.inner, and sets *mirror.refresh_lock.lock() = false so any concurrent refresh() snapshot either completes before return or bails out on !*live, preventing UAF.
  • Added three deterministic pure-CPU unit tests using thread-safe MockFence COM vtables (AtomicU64 / AtomicUsize + offset_of!(ID3D12Fence_Vtbl, GetCompletedValue)):
    • refresh_and_pending_summary_do_not_block_concurrent_queue_and_cpu_signals
    • note_cpu_signal_and_refresh_avoid_unrelated_and_non_cell_fences
    • per_cell_lock_prevents_stale_refresh_overwrite

Tested

  • Hardware & toolchain: Windows 11 Home (build 26200), Intel Core i5-11400F (6C/12T), 32 GB RAM, NVIDIA GeForce RTX 4060 8 GB (driver 621.14), rustc 1.100.0, DXC 1.9.2609.5 (01b62ad4), release builds.
  • Failing-first reproduction on unmodified b49be183: a temporary pure-CPU mock COM probe against unmodified fence_x.rs failed (unrelated_calls=1, global_lock_held=true), confirming note_cpu_signal queried unrelated fences and refresh() held global FENCES across GetCompletedValue().
  • Pure-CPU / WARP (XCL_ADAPTER=warp, XCL_WARP=1): cargo test --release -p xcl --lib -- hle::d3d12x::fence_x::tests:: --skip the_cell_follows_the_fence --nocapture -> 3 passed; 0 failed; 0 ignored (0 skipped, 0.02s).
  • RTX 4060 targeted: cargo test --release -p xcl --lib -- hle::d3d12x::fence_x::tests:: --nocapture -> 4 passed; 0 failed; 0 ignored (0 skipped, 0.29s, including untouched real-D3D12 the_cell_follows_the_fence).
  • Full release workspace on RTX 4060: cargo test --release --workspace --no-fail-fast -- --test-threads=4 --nocapture: 37 binaries, 1438 passed, 0 failed, 47 ignored (0 warnings in fence_x.rs), 29 pre-existing environment-gated SKIPPED lines (none in fence_x):
    • 21 wave64-only GPU tests (no wave64 on RTX 4060 32-lane waves)
    • 3 per-lane wave32 shader tests (refused)
    • 3 D3D12 debug layer tests (no d3d12SDKLayers.dll / debug layer unavailable)
    • 1 heap-window OOM fallback test (no heap windows)
    • 1 PSO driver-cache measurement test (cannot disable the driver cache)

Regression run

Paired 60 s retail smoke (scripts/smoke.ps1, RTX 4060): both base and HEAD sustained 60 60 60 presents per 2 s with 0 device removals and 0 crashes (1319 vs 1549 total frames, 13957 MB vs 13968 MB peak commit).

Base (origin/main):

xcl-smoke v1
commit: b49be1836844fe0b0cdb3211dce3cb7fb4e21ac7
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1549 (PresentX 1549)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 13968 MB

HEAD (fix-fence-x-lockfree-refresh-and-scoped-signal):

xcl-smoke v1
commit: 6530439984ad79923fcb7698af76aa0c2d0b9fb2
gpu: NVIDIA GeForce RTX 4060
title: 29640639
seconds: 60
exit: 0x0
frames shown: 1319 (PresentX 1320)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 13957 MB

Not tested

  • Real-D3D12 the_cell_follows_the_fence on a hardware-free WARP-only host (that existing test calls D3D12CreateDevice(None, ...) first before falling back to WARP, so on this RTX 4060 host it ran on RTX 4060; the three new mock COM concurrency/scoping tests are pure CPU with zero D3D12 device dependency).
  • The 29 hardware/environment-skipped workspace tests listed above (native wave64 GPUs, D3D12 debug layer SDK, heap windows, driver-cache-disabled PSO measurement) and non-Windows hosts.

AI use

Google Antigravity (Gemini 4 Neon) authored the FenceTable/CellMirror refactoring, mock COM concurrency/scoping tests, and verification runs; verified via failing-first probe, pure-CPU and RTX 4060 fence_x tests, full RTX 4060 release workspace tests, and paired 60 s retail smoke runs.

…PU-signal refreshes to the signalled fence

Encapsulate fence_x tracking in `FenceTable` (`State { map, cells }`)
backed by `Arc<CellMirror>` (`Box<Cell>` on its own 64-byte cache line
for `monitorx`/`mwaitx` plus a per-fence `refresh_lock: Mutex<bool>`
live guard). `refresh()`, `note_cpu_signal()`, `pending_summary()`, and
`completed_value_address()` now drop the global mutex before any
`ID3D12Fence::GetCompletedValue()` COM call; `note_cpu_signal()` and
`completed_value_address()` refresh only the target fence rather than
scanning all tracked fences; `refresh()` visits only cell-backed fences;
and `refresh_lock` serializes concurrent per-fence updates and guards
test fence teardown against UAF.

Part of xcl-dev#1833
Part of xcl-dev#1773

Assisted-by: Google Antigravity (Gemini 4 Neon)

@luckyteagirl luckyteagirl left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could this snapshot keep test-owned fences live until GetCompletedValue returns? queue_slot_18_before_the_layout_is_known_writes_8_bytes registers a stack-backed fence and removes it in Cleanup::drop. A concurrent wait-watchdog summary can copy that raw address, release the table lock, then query it after cleanup and the test return. forget_fence only waits for cell refreshes, and this fixture never creates a cell. Main's diagnostic kept the same table lock as forget_fence_for_test, which serialized the query and cleanup. A test-build lifetime guard covering all entries, or a test-only locked diagnostic traversal, would preserve that ordering. Source review only at head 65304399; no crash reproduced. AI-assisted with Codex (GPT-6.2 Sol).

@SlopTart

Copy link
Copy Markdown

Tested: current PR head merged onto current origin/main (clean), Linux (Arch, kernel 7.2.15), Mesa 26.2.5 RADV, Radeon RX 7900 XT (NAVI31), cargo target x86_64-pc-windows-gnu run under wine-11.0 (Proton), rustc 1.94.0, vkd3d-proton 3.1 with the XCL patch, official MS DXC (binaries 2026-09-29).

gpu_ suite (cold cache): 165 passed / 3 failed, no crashes. The three are the known baseline on this lane (seed-1003 fuzz, mad/mac contraction, promoted-UAV-clear driver gap, PR #2490); none caused by this PR. This PR does not change the mad/mac red on RADV.
Targeted run of note_cpu_signal_and_refresh_avoid_unrelated_and_non_cell_fences, per_cell_lock_prevents_stale_refresh_overwrite, refresh_and_pending_summary_do_not_block_concurrent_queue_and_cpu_signals: 3 passed. Lock-scoping behavior is timing-sensitive under Wine too, so the concurrency tests here do exercise the interesting part on this lane.

Not tested: retail titles (no title data on this lane, counts only).

AI use: Hermes agent (local Qwen-class) ran both machines and drafted this; I checked it before posting.

@Aniseto

Aniseto commented Nov 26, 2026

Copy link
Copy Markdown

Ran the fence refresh tests at 65304399:

Environment: Windows 11 Pro build 26200 x64, NVIDIA GeForce RTX 5070 Ti (Blackwell, 32-lane waves only, 16 GB) driver 32.0.16.2124, Intel Core i5-12400F, 64 GB RAM, rustc 1.100.0 (0ef1bc386 2026-11-09) MSVC 14.44.35207, DXC 1.9.2609.5, debug build.

XCL_ADAPTER=nvidia cargo test -p xcl --lib hle::d3d12x::fence_x::tests:: -- --test-threads=1 --nocapture
4 passed; 0 failed; 0 ignored; 1335 filtered out      (exit 0)

All four pass here, including the three new mock-COM concurrency/scoping tests and the existing real-D3D12 the_cell_follows_the_fence test on the RTX 5070 Ti.

What this adds: the author measured on an RTX 4060 (Ada) and WARP; this is a second NVIDIA host (Blackwell, different driver) running the same real-D3D12 fence test. The thread has no report from another machine.

Not tested: the full workspace suite, a paired 60 s smoke run, AMD and Intel GPUs, native wave64, Wine, release profile, title data.

AI-assisted (OpenCode), model: DeepSeek V4.1 Flash Free - checked out the PR's head commit in a detached worktree, built it, ran the tests, wrote this report; the worktree was not modified; no game data was used.

@pickles976

Copy link
Copy Markdown

Wine/NVIDIA verification of exact head 6530439984ad79923fcb7698af76aa0c2d0b9fb2 (Linux 6.17, Wine 11.0, RTX 4060 Laptop, NVIDIA 590.48.1, DXVK 3.1.1, Rust 1.98.1 x86_64-pc-windows-msvc). Caveat: locally built diagnostic-relaxed vkd3d-proton 3.2.0 2576c0b4adfae4a+ (assertions disabled, allocator/list from_iface vtable identity checks removed, null checks kept) — not stock-runtime certification. Unchanged owner code; fresh Compiling xcl .../xcl-pr2649/... (26.58 s); one test thread; 9 GiB/512 MiB cgroup scope.

hle::d3d12x::fence_x::tests 4/4 pass, 0.71 s:

  • the_cell_follows_the_fence on the real adapter: queue Signal(6)/Signal(7) observed through completed_value_address cells, CPU fence.Signal(9) through note_cpu_signal — including the queued-before-address-asked ordering.
  • refresh_and_pending_summary_do_not_block_concurrent_queue_and_cpu_signals, note_cpu_signal_and_refresh_avoid_unrelated_and_non_cell_fences, per_cell_lock_prevents_stale_refresh_overwrite — all pass under --test-threads=1 with their internal concurrency harnesses (no deadlocks, no stale overwrite).

Log kept locally as verify-pr2649-fences.log.

One scoping note from reading the code alongside the GTA VI Game Init stall I reported at #850 (comment): the title-crash symptom (1 CPU-write submissions using legacy fallback after 10000 ms (fence at 0, wanted 1; 2 queued writes)) comes from hle/d3d12x/cpu_writes.rs, which has its own FENCES: Mutex<Option<HashMap<usize, QueueFence>>> distinct from this PR's fence_x map, and its worker already waits off-lock (fence::wait in the xcl-cpu-writes thread; the lock is taken only for map insert/remove/lookup). So this PR is a latency/correctness improvement for the fence_x cell path, but it does not plausibly change that crash. No title run, no perf claim.

AI use: omp, harness model openai-codex/gpt-6-astra, ran the checks and drafted this report. No upstream code changes or assets attached.

bmjask pushed a commit to bmjask/xcl that referenced this pull request Nov 26, 2026
Fence refresh and diagnostics held the global fence table lock across driver GetCompletedValue calls, while CPU signals scanned unrelated fences. Snapshot stable cell mirrors, serialize refreshes per fence, and keep raw diagnostic fixtures alive through teardown without blocking ordinary signal/wait bookkeeping.

Adapted from xcl-dev/xcl PR xcl-dev#2649 commit 6530439 by Decodere, with the non-cell diagnostic lifetime race fixed.

Cross-target cargo check for library and tests passed; Windows execution was unavailable.

Assisted-by: Codex (GPT-5.6-sol)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants