Skip to content

runtime: notify QueueHolds when a held CPU Fence::Signal fires - #4282

Open
cixotdev wants to merge 1 commit into
ItsNotRexed:mainfrom
cixotdev:fix/fence-held-cpu-signal-queue-holds
Open

cixotdev wants to merge 1 commit into
ItsNotRexed:mainfrom
cixotdev:fix/fence-held-cpu-signal-queue-holds

Conversation

@cixotdev

Copy link
Copy Markdown
Contributor

Summary

Fixes a cross-queue Wait-before-Signal deadlock in runtime/shims/d3d12_com.cpp where a deferred CPU ID3D12Fence::Signal(value) callback advanced the Vulkan timeline semaphore without notifying QueueHolds.

Root Cause

When Fence::Signal(value) is called while a GPU queue->Signal(fence, queued) is still pending (held_->load() != 0 || fence_.completed() < queued), it defers the signal through FenceWaitDispatcher. Once queued completes:

  • Immediate CPU signals go through VulkanFence::signal() (runtime/src/vulkan_backend.h), which calls vkSignalSemaphore, context_.holds().signaled(semaphore_, value), and context_.holds().pump_ready().
  • Deferred CPU signals in Fence::Signal() called raw vkSignalSemaphore and decremented held_, but never called context->holds().signaled(semaphore, value) or context->holds().pump_ready().

As a result, any batch held in QueueHolds waiting for fence >= value remained stalled indefinitely—even after fence->GetCompletedValue() had already reached value—until queue teardown discarded it.

Changes

  • runtime/shims/d3d12_com.cpp:
    • In Fence::Signal()'s deferred callback, capture whether vkGetSemaphoreCounterValue(...) == VK_SUCCESS, now >= queued && now < value, and vkSignalSemaphore(...) == VK_SUCCESS.
    • Decrement held->fetch_sub(1) before pumping ready holds (so concurrent Fence::Signal callers see the updated count), then call context->holds().signaled(semaphore, value) and context->holds().pump_ready() if the semaphore was signaled.
    • Lock safety: FenceWaitDispatcher unlocks mutex_ prior to invoking callbacks, and QueueHolds::signaled() / pump_ready() require no queue lock held.
  • runtime/test/d3d12_fence_timing_test.cpp:
    • Extend check_held_cpu_signal() with two cross-queue regression scenarios (exercised on both the wrapped device proxy and the standalone Vulkan device):
      1. Queue B Wait(f, 70) + Signal(done, 1) queued before held CPU f->Signal(70) behind Queue A Wait(gate, 3) + Signal(f, 60).
      2. Queue B Wait(f, 90) + Signal(done, 2) queued while CPU f->Signal(90) is already held behind Queue A Wait(gate, 4) + Signal(f, 80).

Verification (No Game Files)

  • Negative control (new tests against unpatched d3d12_com.cpp on origin/main aa2988cc):
    • LEONIDA_VK_VALIDATION=1 d3d12_fence_timing_test.exe failed with exit code 1:
      • held CPU signal did not wake QueueHolds: f=70 done=0
      • [rt] d3d12: queue destroyed with 1 held operation(s) never submitted: waits for a fence value (70) that no Signal reached; the fence was never signaled
  • After fix (Windows 11 10.0.26200, NVIDIA GeForce RTX 4060 8 GB, Vulkan SDK 1.4.363.0, MSVC 19.44.35230.0, CMake 4.4.4, Ninja 1.13.2):
    • LEONIDA_VK_VALIDATION=1 d3d12_fence_timing_test.exe: PASS, 0 validation errors, wrapped + standalone devices both verified.
    • LEONIDA_VK_VALIDATION=1 ctest --output-on-failure -R "^(d3d12_fence_timing|d3d12_queue_wait|d3d12_queue_wait_timeout|d3d12_fence_events|d3d12_fence_waiter|vk_fence_dispatcher_sync)$": 6/6 passed (100% tests passed) in 6.79 sec.
    • Clean /W4 compilation, git diff --check clean, LF line endings preserved (CRLF=0).

Coordination & Related PRs

AI-assisted with Neon (Antigravity).

When ID3D12Fence::Signal is deferred behind a pending GPU queue signal,
Fence::Signal enqueues a FenceWaitDispatcher callback that calls
vkSignalSemaphore directly instead of going through VulkanFence::signal.
That callback previously never notified QueueHolds via
holds().signaled(semaphore, value) and holds().pump_ready(), leaving any
cross-queue Wait-before-Signal batch stalled on that fence value
forever even after GetCompletedValue() reached it.

Record whether vkSignalSemaphore succeeded, decrement held_ first, and
then call holds().signaled(semaphore, value) and holds().pump_ready()
with no dispatcher or queue lock held. Add cross-queue regression cases
to check_held_cpu_signal in d3d12_fence_timing_test.cpp covering both a
Wait queued before the held CPU Signal and a Wait queued while the CPU
Signal is already held.

Claim: ItsNotRexed#4084 (comment)
AI-assisted: yes (Antigravity)

@Kam471 Kam471 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.

Built d3d12_fence_timing_test at 8dfe9bce and ran it on Windows 11, RTX 5070 Ti: exit 0, ctest -R d3d12_fence_timing -> 1/1 passed (1.64 s).

The held CPU-signal cases, multiple-fence waits, adapter LUID, custom heap properties and both clock-calibration paths (submitted-timestamp fallback and the calibrated-timestamps extension) all pass, including the queue-capability gate. No blocking issue.

@dcastell1

Copy link
Copy Markdown
Contributor

Tested 8dfe9bc on RTX 5090, 621.24, Windows 11: pass. Built the runtime from this tree and ran ctest -R d3d12_fence_timing → 1/1 passed (2.00 s).

Notifying QueueHolds when a held CPU fence is signalled is the kind of fix that cannot be proven by the shader suite, so having the timing test is what makes it verifiable at all.

@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 8dfe9bc on Windows 11, MSVC 14.51, with NVIDIA GeForce RTX 4090 (driver 32.0.16.2101) and AMD Radeon(TM) Graphics (driver 32.0.21043.5001): pass. The build has no validation layers.

ctest -C RelWithDebInfo -R "^d3d12_fence_timing$" --repeat until-fail:3 passes three times on each GPU. LEONIDA_VK_DEVICE selects the GPU.

I also made a synthetic probe. Queue A waits behind a gate and has a signal of 100 in its queue. Then the CPU signals 110 and 120. Queues B and C wait on those values.
The completion events of B and C stay unset before the gate opens. They complete after the gate opens. The fence gets to 120. The result is the same on the two GPUs.

Negative control: the new test of this head, linked with the libraries of main aa2988cc, exits with 1 on the RTX 4090. After five seconds it reports f=70 done=0.

The full ctest result will follow if it shows a difference. I found no defect. AI-assisted.

@traeb0n

traeb0n commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 8dfe9bc on NVIDIA GeForce RTX 5070, driver 621.01, Windows 11 Pro 26300, i7-14700K / 64 GB, MSVC 14.44 RelWithDebInfo (scripts/build_runtime.ps1, llvm-mc 23.1.6 so the translated-shader targets build), Vulkan SDK 1.4.363, LEONIDA_VK_VALIDATION=1 for ctest: pass.

  • Build: exit 0, 0 compiler warnings.
  • Full ctest -E loader -j 4: 149/149.
  • Run alone with -V: d3d12_fence_timing (with the new cross-queue regression), d3d12_fence_events, d3d12_fence_waiter, d3d12_queue_wait, d3d12_queue_wait_timeout and d3d12_queue_handover pass, 6/6, with no validation messages.

Baseline on main 03b09a0, same machine and settings: 150/150 ctest, 0 compiler warnings.

No game files. AI-assisted (Claude Code).

@Flyander Flyander 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.

Reviewed the current head 8dfe9bce. The deferred CPU-signal path notifies queue holds after the signal, and the independent Windows timing test covers waits before and after the deferred signal. No blocking issue found.

@byPreaZy

Copy link
Copy Markdown

Tested 8dfe9bc on AMD Radeon RX 9060 XT (RDNA4), Windows 11, driver 26.10.1 (LLPC), Vulkan SDK 1.4.363.0, MSVC RelWithDebInfo.

  • LEONIDA_VK_VALIDATION=1 d3d12_fence_timing_test.exe: PASS, exit 0, "fences and timing: multiple-fence waits, held CPU signals, clock calibration, adapter LUID and custom heap properties all checked", 0 validation errors
  • ctest -R "fence_timing|queue_wait|queue_wait_timeout|fence_events|fence_waiter|vk_fence_dispatcher_sync": 6/6 passed (12.0 s)

Independent check on a second AMD RDNA4 part. AI-assisted (Devin).

@requiemsnkrp

Copy link
Copy Markdown

Review from working on the same path (I had reproduced it as D3D-481, now released as a duplicate of this; code read + a local implementation on RTX 3060, not a run of this PR's head):

  1. cancel path. ~Fence → cancel_fence_waits runs the deferred callback synchronously. With this change the callback then calls holds().signaled() + pump_ready() while the fence is being released, so batches waiting on that fence get submitted (with a Vulkan wait on its semaphore) instead of dropped by remove_fence, and ~VulkanFence destroys the semaphore right after (VUID-vkDestroySemaphore-semaphore-05149 / use after free). The callback shouldn't notify holds when invoked from cancel — e.g. a shared live/releasing/gone state that ~Fence sets before and after cancel.
  2. Pre-existing race, now wider. An entry the dispatcher already moved to its ready list can run after ~Fence returned (cancel() only waits while the dispatcher is inside vkWaitSemaphores, not while it dispatches), so the callback can call vkGetSemaphoreCounterValue / vkSignalSemaphore — and now signaled() / pump_ready() — on a destroyed semaphore. A per-fence mutex the callback holds, with ~Fence marking "gone" under it, closes that.
  3. That same mutex held across signaled() + pump_ready() also keeps the device alive (~Fence and its device reference wait for the pump) while pumping on the dispatcher thread.
  4. The test could also check the consumer batch's data and teardown under validation (gated queue Signal, CPU Signal(2), Wait(F,2) on another queue, layer vs host).

AI-assisted (Claude).

@ruvenesh

Copy link
Copy Markdown

Tested 8dfe9bc (merged onto main 2d3369a, clean merge, only d3d12_com.cpp and d3d12_fence_timing_test.cpp differ) on RTX 3060, driver 580.178.04, Ubuntu 24.04, runtime cross-built with clang-cl 23.1.6 + xwin and run under Wine 9.0. AI-assisted (Claude Code); no game files.

Pass: the fix and its new test do what the PR says.

  • With the fix: the new check_held_cpu_signal cases (a Wait held for a deferred CPU Signal, and a Wait queued while the CPU signal is already held) pass. 15 of 15 runs, no flakes, no did not wake.
  • Fix reverted, test kept (main's d3d12_com.cpp): the test fails with held CPU signal did not wake QueueHolds: f=70 done=0. So the semaphore reaches 70 while the held batch never runs, which is the reported stall, and the test catches it.
  • Neighbours: d3d12_fence_events and d3d12_com pass with the PR.

Not caused by this PR (same result on unmodified main under Wine):

  • d3d12_fence_timing stops at check_custom_heap_properties (the line after check_held_cpu_signal; Wine reports a fake "GTX 470" adapter). So on this setup the second check_held_cpu_signal call (the standalone device, later in main) is not reached; it would need a native Windows run.
  • queue_proxy fails at child runner line 1036 on main too.
  • vk_fence_dispatcher_sync fails at line 126 on main under Wine; I did not re-run it with the PR.

Not covered: no validation layer on this box (LEONIDA_VK_VALIDATION=1 exits), and no native Windows run.

Code read: the callback only pumps after vkSignalSemaphore returns VK_SUCCESS, captures context and semaphore only (no Fence access after release), and held->fetch_sub(1) runs before signaled()/pump_ready(). That order looks right: the callback drops its hold first, then wakes the queues. LGTM from my side.

@Exopus-0x65f7ad0

Copy link
Copy Markdown

Measured @requiemsnkrp's point 1 with a local probe added to d3d12_fence_timing_test (not pushed anywhere). Each iteration uses a fresh fence F: queue A Wait(gate, i) + Signal(F, 1), CPU F->Signal(2) (postponed), queue B Wait(F, 2) + Signal(done, 1), gate->Signal(i), a busy-wait of 0–1.9 ms (i % 20 × 100 µs), then F->Release(). 200 iterations on the test-made device with LEONIDA_VK_VALIDATION=1; RTX 5060 Ti / 621.14, Windows 11, MSVC 14.51.

tree B's batch runs validation runs crashing
main 7b7d73f8 0/200 (D3D-481) 0 0/3
this PR 8dfe9bce 187/200 VUID-vkDestroySemaphore-semaphore-05149 (≥10, the layer's duplicate limit) 2/3 segfault, one also VUID-VkSubmitInfo-pWaitSemaphores-parameter
#4663 0cc958d0 0/200 0 0/3
#4663 + this PR 176–184/200 0 0/5

But the VUID isn't specific to this PR. A control on main with the CPU signal applied at once (B Wait(F, 2), CPU F->Signal(2), release F) gives 200/200 runs and 05149 in 3/3 runs: ~VulkanFence destroys the semaphore while a released batch still waits on it. This PR adds the postponed path to the paths that release such a batch, so it hits the same thing. #4663 (D3D-486) retires the semaphore through the deferred-deletion tickets and clears it on both paths: immediate 200/200 with 0 VUIDs ×5, and the table's last row.

Host reference (same GPU, D3D12 debug layer on): releasing the fence right after the CPU signal is legal. B ran 50/50 both ways (with and without the gate), with 0 debug-layer messages, and a queue Wait/Signal takes no COM reference (refcount stays 1). So "don't notify the holds from cancel, let remove_fence drop them" would move away from the host, while keeping the semaphore alive (#4663) matches it. I'd land #4663 first or with this one (Depends on: #4663).

Gap left vs the host (not this PR's to fix): with #4663 + this PR, 16–24 of 200 batches are still dropped. That happens when F is released before the GPU reaches the queued value: cancel runs the callback with now < queued, the postponed signal is lost and remove_fence drops B. The host ran all 50. Also on the host, an unsatisfied Wait on a released fence lets the queue go on (the Signal after it lands), where the layer drops the held work.

AI-assisted (Claude Code). No game files.

0klavair added a commit to 0klavair/Leonida that referenced this pull request Nov 23, 2026
…l (D3D-496 case 1)

check_released_postponed_signal runs @Exopus-0x65f7ad0's scenario 200 times
on a fresh fence each time: queue A Wait(gate, i) + Signal(F, 1), CPU
F->Signal(2) (held behind A's Signal), queue B Wait(F, 2) + Signal(done, i),
then F->Release(). Even iterations release F before opening the gate, so the
GPU cannot have reached 1 and the postponed Signal is lost; odd ones release
it 0-1.9 ms after. B's batch must run every time, as on the host runtime,
which the test also runs as the reference.

With ItsNotRexed#4663 + ItsNotRexed#4282 alone the layer drops B's batch on every early release
(100/200 here). With D3D-496 case 2 (a released fence's wait counts as
reached) it runs 200/200, on the host too.
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.

10 participants