Skip to content

perf(vulkan): conditional Sync2 readback flush, O(1) deferred deletion, lock split, TDR safety, and FenceWaitDispatcher - #927

Merged
ItsNotRexed merged 1 commit into
ItsNotRexed:mainfrom
totonicpu:perf/sync2-tdr-safe-hardening
Nov 22, 2026
Merged

ItsNotRexed merged 1 commit into
ItsNotRexed:mainfrom
totonicpu:perf/sync2-tdr-safe-hardening

Conversation

@totonicpu

Copy link
Copy Markdown
Contributor

Summary

Five orthogonal Vulkan runtime performance and concurrency improvements rebased cleanly onto main:

  1. Conditional Synchronization2 readback flush (vulkan_replay.h, vulkan_backend.h, d3d12_vulkan_device.cpp):
    • Track host_readable on ResourceBinding (set for D3D12_HEAP_TYPE_READBACK / host-readable custom heaps) and propagate wrote_readback + readback_src_stages during prepare() (including ResolveQueries to readback buffers).
    • Emit the host-domain flush barrier only when a submitted batch actually writes to a readback buffer, using vkCmdPipelineBarrier2 (with legacy vkCmdPipelineBarrier fallback) scoped to the queue's supported stages instead of an unconditional ALL_COMMANDS -> HOST global stall on every submission.
  2. Zero-allocation O(1) Ring Buffer DeferredDeletionQueue (vulkan_backend.h, d3d12_vulkan_device.cpp):
    • Replace immediate synchronous destruction / vkDeviceWaitIdle stalls with a timeline-semaphore-gated power-of-two ring buffer (DeferredDeletionQueue) drained in O(1) amortized time as GPU retirement tickets complete.
  3. Lock split & std::shared_mutex (vulkan_backend.h):
    • Split the monolithic VulkanContext::mutex_ into cache-line-aligned resource_mutex_ (std::shared_mutex for concurrent prepare() lookups), tracker_mutex_ (layout tracking during emit()), views_mutex_ (image view cache), and submit_mutex_ (released before vkQueueSubmit).
  4. TDR / VK_ERROR_DEVICE_LOST safety (vulkan_backend.h, vulkan_replay.h):
    • Add overflow-safe checked_range(...) helper and atomic device_lost_ latching on VK_ERROR_DEVICE_LOST so pending waits and submissions fail cleanly without deadlocking.
  5. Centralized FenceWaitDispatcher (vulkan_backend.h, d3d12_com.cpp):
    • Replace spawning a dedicated std::thread polling with sleep_for(10ms) per ID3D12Fence::SetEventOnCompletion call with a single centralized dispatcher thread waiting via vkWaitSemaphores(..., VK_SEMAPHORE_WAIT_ANY_BIT, UINT64_MAX) plus a timeline wakeup semaphore (synchronized with waiting_ under mutex_ to prevent lost wakeups), waking Win32 event HANDLEs immediately on GPU completion.

Verification (NVIDIA GeForce RTX 4070 Ti, LEONIDA_VK_VALIDATION=1 Core + Sync Validation)

  • Built full runtime in both RelWithDebInfo and Debug (MSVC x64).
  • ctest (all 32 enabled tests, including d3d12_vulkan_device): 32/32 PASS in both RelWithDebInfo and Debug with 0 validation errors.
  • Explicit GPU suites with LEONIDA_VK_VALIDATION=1: d3d12_com_test, d3d12_typeless_rtv_test (799 readbacks), d3d12_descriptor_test, d3d12_resource_desc_test, d3d12_node_mask_test, vk_command_replay_test (A–F, 360 sync/access pairs) — all PASS with 0 validation errors.

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

Tested 7f58b94 on NVIDIA GeForce RTX 5070, driver 621.24, Windows 11 Pro (26300), VS 2022 Build Tools, Vulkan SDK 1.4.363.0, with LEONIDA_VK_VALIDATION=1 and LEONIDA_D3D12=vulkan: pass

  • ctest -C RelWithDebInfo: 100% tests passed, 0 tests failed out of 32
  • 34 test programs in the build pass with 0 validation errors
  • d3d12_clear_test fails (R8G8B8A8_UNORM/SNORM 0.5 ties and a D16 clear byte differ from WARP) exactly as on main 4a36bb1 here, so not from this PR; #521 addresses it

Implicit Vulkan layers (overlays) were off through an empty VK_IMPLICIT_LAYER_PATH.

@totonicpu
totonicpu force-pushed the perf/sync2-tdr-safe-hardening branch from 7f58b94 to 2cfce4c Compare November 22, 2026 05:13
@Parakeet-Wheat

Copy link
Copy Markdown
Contributor

Tested 2cfce4c on an NVIDIA GeForce RTX 3070, driver 610.88, Windows 11 (26300), MSVC 19.44 (VS generator, RelWithDebInfo), Vulkan SDK 1.4.363.0, with LEONIDA_VK_VALIDATION=1: tests pass, but I think the lock split needs another look before this lands.

None of these submit from two threads at once, so they can't exercise the part that worries me:

Emit order and submit order can now differ between queues. On main, VulkanQueue::execute holds context_.mutex_ across prepare, emit and submit, so the order in which lists update the shared LayoutTracker (and the query heaps' ended flags) is the order the GPU runs them. The tracker's comment depends on that: "lists are emitted in submission order". Here, tracker_mutex_ is released after emit and resource_mutex_ before vkQueueSubmit. So two D3D12 queues on different threads can emit A then B but submit B then A. The device creates one VkQueue (queueCount = 1), so the GPU runs B's barriers, which start from layouts that assume A already ran, before A. That gives wrong oldLayouts or missed transitions. Keeping the tracker lock held through submit, or taking submit_mutex_ before emit and holding it until the submit, would keep the two orders the same.

Smaller things:

  • Readback flush coverage: wrote_readback is set for copies and ResolveQueryData. WriteBufferImmediate (the fill_buffer/update_buffer path) into a readback buffer isn't flagged, though D3D12 allows it: readback buffers stay in COPY_DEST. A Map after the fence could then miss those writes. Maybe flag any write whose destination binding is host_readable, rather than listing command types.
  • Unused pieces: checked_range has no callers. QueueKind is never passed, so it's always direct. The sampler, pipeline, pipeline_layout and query_pool cases of DeferredDeletionQueue::Kind are never pushed.
  • Merge break with Normalize binary occlusion results in Vulkan replay #889 and Runtime: support overlapping ordinary occlusion queries (D3D-15) #940: both also add X(vkDestroyPipeline) X(vkDestroyPipelineLayout) to LEONIDA_VK_DEVICE_FUNCTIONS. Merged together, the struct would declare those members twice, which is a compile error rather than a textual conflict that git would flag.
  • Scope: five independent changes in one commit are hard to review and to bisect. The conditional readback flush (with the coverage fix) and the FenceWaitDispatcher (no more thread per fence and 10 ms polling) both look useful on their own and could land separately while the lock split is reworked.

AI-assisted (Claude Code).

@kotorvr

kotorvr commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Tested 2cfce4c on RTX 4090 (driver 621.14), Windows 11 26200, MSVC 19.44: pass (no regression against main).

  • Clean RelWithDebInfo Ninja build of runtime/ (Vulkan SDK 1.4.363.0), then ctest with validation on: 33/33 pass.
  • GPU tests with LEONIDA_VK_VALIDATION=1 and the Khronos validation layer: d3d12_com_test, d3d12_descriptor_test, d3d12_fence_timing_test, d3d12_fence_waiter_test, d3d12_gcl8_test, d3d12_method_variants_test, d3d12_node_mask_test, d3d12_resource_desc_test, d3d12_sampler2_test, d3d12_state_map_test, d3d12_typeless_rtv_test, d3d12_uav_clear_test, d3d12_vulkan_device_test, vk_command_replay_test pass, with 0 validation messages (no VUIDs).
  • d3d12_clear_test fails, the same as on plain main dcd8ecf on this GPU (NVIDIA rounds the 0.5 clear on 8-bit UNORM/SNORM down, Vulkan 7f, WARP 80, plus one depth-format-55 case). This is not caused by this PR.

The vk_* harness tests that need translated SPIR-V weren't run. No game files used. AI-assisted run (Claude Code).

@UlteriorMotive00

Copy link
Copy Markdown
Contributor

Tested 2cfce4c on AMD RDNA2 iGPU and RTX 5070, including synchronization validation: pass.

Windows 11 Home 10.0.26300, MSVC 14.44.35207, Windows SDK 10.0.26100, Vulkan SDK 1.4.363.0, Ninja RelWithDebInfo (scripts\build_runtime.ps1), VK_LOADER_LAYERS_DISABLE=~implicit~. One PC, two GPUs, picked with VK_LOADER_DRIVERS_SELECT: AMD Radeon iGPU of a Ryzen 7 9800X3D (RDNA2, AMD 2026.04.17) and NVIDIA GeForce RTX 5070 (Blackwell, 617.42).

  • ctest with LEONIDA_VK_VALIDATION=1: RTX 5070 33/33; AMD iGPU 32/33.
  • ctest again with LEONIDA_VK_VALIDATION=1 and VK_VALIDATION_VALIDATE_SYNC=1, since this PR changes the readback flush and barriers: the same counts, and no SYNC-HAZARD or VUID messages on either GPU.
  • The one AMD failure in both runs is d3d12_vulkan_device at D3D12_OPTIONS1 WaveLaneCountMax: ours 64, host 32, the two-GPU comparison bug fixed on main by d3d12_vulkan_device_test: compare OPTIONS1 with the same GPU's host device, not the default adapter #962, not this PR. The branch is 193 commits behind main.
  • I checked correctness only, not CPU time.

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

@totonicpu

Copy link
Copy Markdown
Contributor Author

Thanks @Parakeet-Wheat for the thorough concurrency review — every point was spot-on. Rebased onto current main (43d4703) and addressed all of them in 23d2e90:

  1. Emit order == submit order across queues (vulkan_backend.h): VulkanQueue::execute now holds tracker_mutex_ from emit() through submit() (and depth24_->retire()), releasing only resource_mutex_ before vkQueueSubmit. Lock hierarchy is strictly resource_mutex_ → tracker_mutex_ → submit_mutex_ (acyclic), keeping concurrent prepare() lookups while guaranteeing LayoutTracker emit order matches GPU submission order across all queues/threads.
  2. Readback flush coverage (vulkan_replay.h): WriteImmediate (vkCmdUpdateBuffer/vkCmdFillBuffer, which resolves by VA and can target a readback buffer in COPY_DEST) and AtomicCopyBuffer (when destination host_readable) now also set wrote_readback + readback_src_stages.
  3. Removed unused code & #889/#940 duplicate member collision (vulkan_backend.h, vulkan_replay.h, d3d12_com.cpp):
    • Removed X(vkDestroyPipeline) X(vkDestroyPipelineLayout) from LEONIDA_VK_DEVICE_FUNCTIONS and trimmed unused DeferredDeletionQueue::Kind variants (sampler, pipeline, pipeline_layout, query_pool).
    • Removed unused checked_range from vulkan_replay.h.
    • Wired D3D12_COMMAND_QUEUE_DESC::Type → VulkanQueue::QueueKind (direct/compute/copy) in d3d12_com.cpp.

Re-verified on NVIDIA GeForce RTX 4070 Ti (LEONIDA_VK_VALIDATION=1 Core + Sync Validation): full ctest PASS in both RelWithDebInfo and Debug + d3d12_com_test, d3d12_typeless_rtv_test, d3d12_descriptor_test, and vk_command_replay_test (A–G) PASS with 0 validation errors.

@totonicpu
totonicpu force-pushed the perf/sync2-tdr-safe-hardening branch from 2cfce4c to 23d2e90 Compare November 22, 2026 06:10
@Parakeet-Wheat

Copy link
Copy Markdown
Contributor

Thanks for the quick turnaround. Retested 23d2e90 on an NVIDIA GeForce RTX 3070, driver 610.88, Windows 11 (26300), MSVC 19.44 (VS generator, RelWithDebInfo), Vulkan SDK 1.4.363.0, with LEONIDA_VK_VALIDATION=1: pass

I read the update against my earlier points:

  • Emit/submit order: fixed. tracker_mutex_ is now held from emit() through vkQueueSubmit and depth24_->retire, and the order (resource → tracker → submit) matches add_resource and remove_resource.
  • Readback flush: WriteImmediate and host-readable AtomicCopyBuffer now set wrote_readback. Good.
  • The dead code and the duplicate X() entries are gone, and QueueKind now follows the queue type.

One new gap from the split, in the depth-24 converter. prepare() runs with only the shared resource_mutex_, and for a footprint copy of a D24 texture it calls replay_.depth24_prepare, so Depth24Converter::prepare. That function changes the converter's state: make_pipeline on first use, scratch() takes from spare_ and grows current_.chunks, and make_part allocates descriptor sets from current_.pools. collect() and retire() change the same containers under tracker_mutex_. On main all of it was under the one mutex. With two queues on two threads:

  1. Two prepare() calls can run Depth24Converter::prepare at the same time, or one can run during another queue's collect()/retire(), so they race on those vectors and pools.
  2. Even with a lock around it, current_ collects every queue's prepared jobs. Whichever queue submits first retire()s all of them against its own timeline and ticket, so another queue's scratch and descriptor sets can be reused or freed once that ticket completes, before the other queue's work has run.

Taking tracker_mutex_ (or a converter mutex) around depth24_prepare would fix (1). For (2), the jobs need to stay with the execution that prepared them, for example by having prepare return the chunks and pools it used in the PreparedList and passing them to retire. The simpler alternative is to take tracker_mutex_ before prepare() when the batch has a depth-24 copy and hold it until retire, so current_ only ever holds one execution's jobs. That fixes both, at the cost of serializing those batches.

As before, none of the tests submit from two threads, so this run only covers the single-threaded paths.

AI-assisted (Claude Code).

@totonicpu

Copy link
Copy Markdown
Contributor Author

Thanks again @Parakeet-Wheat — great catch on Depth24Converter! Rebased onto current main (48ad23f, which now includes merged #742 and #743) and fixed in 4f08b3f:

  • In VulkanQueue::execute (runtime/src/vulkan_backend.h), when context_.depth24_ is active, tracker_mutex_ is now acquired before depth24_->collect() and prepare(), and held all the way through emit(), submit(), and depth24_->retire(). That guarantees Depth24Converter::prepare/collect/retire never race across threads and current_ only ever holds one execution's jobs. When depth24_ is null (native D24 GPUs), prepare() remains fully concurrent under std::shared_lock(resource_mutex_).
  • Deferred destruction of VkAccelerationStructureKHR (now on main via feat(d3d12): add ExecuteIndirect CountBuffer and optional BLAS/TLAS/RayQueryKHR support #743) is also wired through DeferredDeletionQueue in FIFO order before its backing VkBuffer.

Verified on NVIDIA GeForce RTX 4070 Ti (LEONIDA_VK_VALIDATION=1 Core + Sync Validation): 50/50 CTest PASS in both RelWithDebInfo and Debug, plus d3d12_com_test, d3d12_indirect_rt_test, dxgi_swapchain_test, and vk_command_replay_test (A–G) PASS with 0 validation errors.

@Parakeet-Wheat

Copy link
Copy Markdown
Contributor

Thanks for the depth-24 fix. I ran your new #1081 test against this branch, and it found a race in DeferredDeletionQueue::drain that's still there, though the new locking now hides it. I ran it on 4f08b3f. Your rebase to 1fa3d2a only adapts to #889, and drain() and the depth-24 locking are identical there.

Setup: this branch with only d3d12_multithread_test.cpp from #1081 added (and its CMake target), RTX 3070, driver 610.88, LEONIDA_VK_VALIDATION=1, looped:

  • 23d2e90, 25 runs:
    • Run 7 failed with THREADING ERROR : object of type VkBuffer is simultaneously used in current thread ... (vkDestroyBuffer) and thread ... (vkDestroyBuffer), then Couldn't find VkBuffer / Invalid VkDeviceMemory errors (VUID-vkDestroyBuffer-buffer-parameter, VUID-vkFreeMemory-memory-parameter). FAIL: 24 Vulkan validation error(s).
    • Run 25 printed PASS, but vkDestroyDevice then reported 16 leaked VkBuffer/VkDeviceMemory objects (VUID-vkDestroyDevice-device-05137).
  • 4f08b3f, 50 runs: all clean.
  • main with test(d3d12): add post-vkDestroyDevice leak check, shared-texture handoff, and TIMEOUT 120 (#1081 follow-up) #1081: 25/25 clean.

Cause (unchanged in 4f08b3f and 1fa3d2a): drain_scratch_ is one member vector shared by every caller. drain() calls drain_scratch_.clear() before taking mutex_, fills it under the lock, and loops over it after releasing the lock to call vkDestroy*. Each queue's acquire() calls drain_deleted_resources. When two queues drain at once, thread B clears and refills the vector while thread A is still looping over it. A then destroys B's items too, which gives the double vkDestroyBuffer. Items A had taken but not yet destroyed are wiped by B's clear(), which gives the leak.

Why it's clean now: the D3D12 device always calls enable_depth24, so depth24_ is set, and execute now takes tracker_mutex_ before prepare(). That lock covers acquire(), so drains are serialized. The race comes back wherever depth24_ is null (its pipeline fails to load, or a VulkanContext without it), which is the path your comment describes as fully concurrent. Fix: use a local vector in drain() (or swap the drained items into a local under the lock). The ring buffer stays as it is.

A related observation: since depth24_ is set on every D3D12 device, each execute now holds tracker_mutex_ from collect() to retire(), so prepare() no longer runs concurrently there. In practice the lock split now gives about what main's single mutex did. It's correct, but worth knowing if the aim is parallel prepare. Making the depth-24 jobs per execution, as I suggested last time, would get that back.

AI-assisted (Claude Code).

@totonicpu

Copy link
Copy Markdown
Contributor Author

Awesome catch @Parakeet-Wheat — thank you for stress-testing with #1081! Fixed in ${sha}: removed the shared \drain_scratch_\ member in \DeferredDeletionQueue\ and switched \drain()\ to a stack-local \std::vector to_destroy\ (with an early return under \mutex_\ when nothing is ready so the common fast path allocates nothing). Concurrent \drain()\ calls from multiple queues can no longer race even when \depth24_\ is null. Re-verified 54/54 CTest PASS in both \RelWithDebInfo\ and \Debug\ with \LEONIDA_VK_VALIDATION=1.

@totonicpu
totonicpu force-pushed the perf/sync2-tdr-safe-hardening branch from 1fa3d2a to 5d89657 Compare November 22, 2026 07:33
…n, lock split, TDR safety, and centralized FenceWaitDispatcher
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.

6 participants