Skip to content

Runtime: preserve D3D12 fence rewinds across CPU and GPU signals (D3D-472) - #4577

Open
gabrielsteglich wants to merge 14 commits into
ItsNotRexed:mainfrom
gabrielsteglich:fix/d3d12-fence-rewind
Open

gabrielsteglich wants to merge 14 commits into
ItsNotRexed:mainfrom
gabrielsteglich:fix/d3d12-fence-rewind

Conversation

@gabrielsteglich

@gabrielsteglich gabrielsteglich commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Claimed as D3D-472 in the coordination issue.

Depends on: #4224

What and why

The Vulkan layer used one monotonically increasing timeline for each D3D12 fence. After Signal(4) on a fence at 10, it still reported 10 and released a new Wait(8) before the producer supplied the data. A CPU signal could also be deferred behind an outstanding GPU signal.

  • Track the logical fence value separately from each Vulkan queue’s progress tickets. CPU signals take effect immediately and GPU signals publish on completion. A satisfied wait stays satisfied, and later waits use the current fence value.
  • Carry the producer’s Vulkan ticket into GPU waits, including after a CPU signal relays completed GPU work. Preserve accepted work when a consumer queue is released and forward waits when a held tile mapping is a no-op or is rejected. Runtime: preserve queue order for sparse buffer tile mappings #4224 supplies deferred tile mapping.
  • Keep the existing dispatcher and cancel losing ANY registrations. A deterministic regression covers two D3D12 queues that share a Vulkan queue but use separate progress semaphores.

The fence commits are e9715504 and 0429d4b9. The tested head is c7cc36bc, including #4224 at f56726df.

Tested

Windows 11 Pro build 26300, MSVC 19.44.35229, Windows SDK 10.0.26100.0, Vulkan SDK 1.4.363.0, RelWithDebInfo. NVIDIA GeForce RTX 3090, driver 621.01. Vulkan validation enabled, with implicit layers disabled.

  • Full CTest at c7cc36bc: 156 passed, 8 skipped, 1 disabled, 0 failed, with no Vulkan VUID or synchronization-hazard messages in the CTest log.
  • The two-consumer fence relay passed 192/192 cases with exact readbacks on RTX 4080 and AMD Radeon. An RTX 5060 Ti probe matched native D3D12 through UINT64_MAX, with zero validation errors.
  • Fence timing and event tests matched native D3D12 on the RTX 3090 and WARP. These cover 10 → 4 → 12, events registered before and after the rewind, CPU 15 → 20 while GPU 10 is pending, and COPY signaling 4 while DIRECT waits for 8.
  • Queue handover matched every readback in 373 Vulkan-layer cases and 371 native D3D12 cases. On the unchanged baseline fence code, the new COPY/DIRECT case released DIRECT early and returned 512 incorrect words.
  • Mock tests cover shared-queue completion order, device loss, ANY cancellation, and sparse waits carried through rejected mappings and consumer queue destruction.

Merge-order coordination

#4663 and #4740 touch the lifetime and release of fences that queues still reference. The fuzzer follow-up matched native D3D12 on rewinds and large values. It found three differences in 30 fence-release seeds, including a wait on a released and unsignaled fence (D3D-496 case 2). #4740 implements the host's resume behavior for that case. Whichever lands second needs to preserve that behavior alongside the logical fence values and rerun the release cases with #5180. #4609 also overlaps the fence event and large-value handling, so merge its independent changes while retaining the host-matching fence behavior.

Checklist

  • Synthetic tests only. No game data, keys, or decryption.

AI-assisted (OpenAI Codex).

Defer reserved-buffer tile updates and copies alongside held command batches and signals. Keep sparse backing alive, resolve source mappings at submission order, and carry waits past no-op or rejected binds.

Compare all tile readbacks with native D3D12 for CPU and COPY queue signals, and test wait forwarding with a fake incomplete Vulkan producer.

@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 the five targets at e9715504 on Windows 11, RTX 5070 Ti, RelWithDebInfo, and ran each: exit 0 for all.

  • d3d12_fence_timing_test: NVIDIA GeForce RTX 5070 Ti: COPY fence value 4, DIRECT after Wait(8) completed early 0; WARP: CPU fence 10 -> 4 -> 12, old event retained 1, new event set early 0; WARP: CPU signals 15 -> 20, queued signal then 10, old event retained 1, new event set early 0; WARP: COPY fence value 4, DIRECT after Wait(8) completed early 0.
  • d3d12_queue_handover_test: Vulkan layer 373 cases, every one exact; host D3D12 371 cases, every one exact; COPY rewound 10 -> 4; DIRECT waited for 12 and read the exact texture and buffer.
  • vk_fence_dispatcher_sync_test: stable queue scan, latched waits, CPU rewind, re-entrant cancel(), mark_device_lost() wake and DEVICE_LOST drain all ok.
  • vk_sparse_queue_order_test: deferred no-op and rejected mappings preserve GPU waits (the two expected held tile mapping failed when it was released lines are printed).
  • d3d12_buffer_tiles_test: 12 full tiles match across all readbacks on the held-batch CPU-signal and copy-queue-signal paths.

git diff --check clean. The numbers match the PR body (373/371, and the baseline early-release case is covered).

Two coordination notes:

  1. The branch carries #4224 (bc15a8bb), which is still open (MERGEABLE). That dependency is declared and works here, but #4577 can only land after #4224, and merging it before would bring the sparse-mapping commit with it.
  2. #4557 and #4570 also edit runtime/src/vulkan_backend.h around the execute/Signal paths, and #4557 edits runtime/test/d3d12_queue_handover_test.cpp; all three need a rebase/fresh run whichever lands first.

@justr4mzi

Copy link
Copy Markdown
Contributor

Verified PR #4577 on Windows 11 (25H2 26200.9974) / AMD Radeon RX 6700 XT (gfx1031, Adrenalin 26.11.2, Vulkan 1.4.315, MSVC 19.44.35230.0, Vulkan SDK 1.4.363.0) at head e9715504:

  • Build: configured Ninja RelWithDebInfo cleanly and built all five targets ([19/19], exit 0).
  • CTest (standard & LEONIDA_VK_VALIDATION=1):
    • Standard: 5/5 passed (12.06 s): vk_fence_dispatcher_sync (0.44 s), d3d12_queue_handover (7.86 s), d3d12_buffer_tiles (0.90 s), d3d12_fence_timing (2.33 s), vk_sparse_queue_order (0.05 s).
    • LEONIDA_VK_VALIDATION=1: 5/5 passed (10.32 s): vk_fence_dispatcher_sync (0.26 s), d3d12_queue_handover (7.64 s), d3d12_buffer_tiles (0.44 s), d3d12_fence_timing (1.94 s), vk_sparse_queue_order (0.02 s).
  • Direct AMD RX 6700 XT runs under LEONIDA_VK_VALIDATION=1 (0 Vulkan validation errors, exit 0 for all 5):
    • d3d12_fence_timing_test.exe: standalone Vulkan, native AMD RX 6700 XT D3D12, and WARP all matched on CPU rewinds (10 -> 4 -> 12), queued signal rewinds (15 -> 20, queued then 10), and cross-queue COPY rewind 4 / DIRECT after Wait(8) (completed early 0).
    • d3d12_queue_handover_test.exe: COPY rewound 10 -> 4; DIRECT waited for 12 and read the exact texture and buffer on both Vulkan layer (373 cases passed) and Host D3D12 (AMD Radeon RX 6700 XT, 371 cases passed), plus never-signaled fence teardown without hanging.
    • vk_fence_dispatcher_sync_test.exe: device: AMD Radeon RX 6700 XT (validation on), dispatcher re-entrant/device-loss tests + logical fence: stable queue scan, latched waits, CPU rewind and device loss ok.
    • vk_sparse_queue_order_test.exe: Sparse queue order: deferred no-op and rejected mappings preserve GPU waits.
    • d3d12_buffer_tiles_test.exe: 12 full tiles match across all readbacks on Vulkan replay and Native D3D12 (original order, held batch CPU Signal, held batch copy-queue Signal).
  • CTest registration, docs & hygiene:
    • tests/test_ctest_registration.py: 4/4 OK (0.422s).
    • python -I -m unittest discover -s tests -p "test_docs*.py": 20/20 OK (19.040s).
    • scripts/check_no_game_data.py & git diff --check upstream/main...HEAD: clean (0).

Code review of LogicalFence / QueueProgress / FenceWaitDispatcher / VulkanQueue::submit looks sound: collecting completed GPU signals under the same mutex as host Signal, preserving 物理 VkQueue FIFO prefix ordering (completed_prefixes_), and publishing pending_ transactionally with vkQueueSubmit avoids lost wakeups and VkSemaphore monotonicity violations cleanly.

AI-assisted (Gemini, Antigravity).

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

The per-physical-queue prefixes preserve ordering within one Vulkan queue, but the final publication loop still treats pending_ insertion order as completion order across distinct queues. D3D12 allows a fence to be rewound and specifies that when signals race across queues, the value from the last Signal to complete remains. Please preserve or explicitly serialize that cross-queue completion order and add a deterministic regression.

Comment thread runtime/src/vulkan_backend.h Outdated
const auto prefix = std::find_if(completed_prefixes_.begin(), completed_prefixes_.end(),
[physical](const auto& entry) { return entry.first == physical; });
if (prefix != completed_prefixes_.end() && i <= prefix->second) {
publish_locked(signal.value, signal.point, ready);

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.

[P2] Preserve completion order across different physical queues. If pending_ contains Q1 Signal(10) followed by Q2 Signal(4), and Q2 completes first while Q1 completes last, a poll that sees both timeline counters complete publishes 10 then 4 here and leaves completed_ == 4. D3D12 requires the last completing signal to win, so the expected value is 10 (and a new Wait(8) must not be released from the stale 4 state). The prefix calculation proves ordering only within one VkQueue; it gives no ordering between Q1 and Q2. Please preserve that ordering or serialize these signals, with a deterministic two-queue regression. Microsoft documents the rewind/race rule: https://learn.microsoft.com/en-us/windows/win32/direct3d12/user-mode-heap-synchronization

@itsonlysimbo

Copy link
Copy Markdown
Contributor

Tested 0429d4b9 merged onto main d0835dd9 (2 behind; merges cleanly) on RTX 4070, NVIDIA 621.14, Windows 11 (10.0.26300), MSVC 19.44, Ninja, RelWithDebInfo, Vulkan SDK 1.4.363: pass.

  • d3d12_fence_timing, d3d12_fence_events, d3d12_fence_waiter, d3d12_queue_handover, d3d12_buffer_tiles, vk_fence_dispatcher_sync and the new vk_sparse_queue_order pass.
  • Those seven, rerun 20 times with ctest -j 4: 20/20 runs all pass.
  • ctest: 146 passed, 10 skipped, 0 failed; run_gpu_tests.py: 164/210 passed, 46 skipped, 0 failed, same as main d0835dd9.

AI-assisted (Claude Code).

#4576 (Report Vulkan pipeline statistics write failures). POSTED.

Tested b82cb5e4 on RTX 4070, NVIDIA 621.14, Windows 11 (10.0.26300), MSVC 19.44, Ninja, RelWithDebInfo, Vulkan SDK 1.4.363: pass.

  • vk_pipeline_check_cli passes.
  • ctest: 144 passed, 10 skipped, 1 failed; run_gpu_tests.py: 164/210 passed, 46 skipped, 0 failed, same as main d0835dd9. d3d12_present failed once in this run; it fails the same way intermittently on main d0835dd9 on this machine (once in three full runs, 5/5 passes alone), so it is not from this change.

AI-assisted (Claude Code).

@0klavair

Copy link
Copy Markdown
Contributor

Tested c7cc36bc (merged onto main 3eb4410b) on NVIDIA GeForce RTX 5060 (Blackwell), driver 621.01, Windows 11 23H2 22631.6199, MSVC 19.44 (VS 2022 Build Tools), Vulkan SDK 1.4.363: pass.

No game files. AI-assisted.

@Exopus-0x65f7ad0

Copy link
Copy Markdown
Contributor

Tested c7cc36bc on Windows 11 (26300), RTX 5060 Ti / 621.14, MSVC 14.51 (VS 2026), Vulkan SDK 1.4.363.0, RelWithDebInfo, clean build with -DLEONIDA_LLVM_MC (translated-shader D3D12 gate tests included), full LEONIDA_VK_VALIDATION=1 ctest -j4: 162/162 passed, 0 VUIDs, 0 build errors. AI-assisted (Claude Code).

@evilclanker9000

Copy link
Copy Markdown
Contributor

Tested c7cc36b on Windows 11 (MSVC BuildTools 2022, Ninja, RelWithDebInfo, -j 4; no Vulkan validation layer installed), one GPU at a time, device line confirmed: AMD Radeon RDNA2 iGPU (driver 26.10.1) and NVIDIA RTX 5080 (driver 616.92). Ran ctest -R "^(d3d12_buffer_tiles|d3d12_fence_timing|d3d12_queue_handover|vk_fence_dispatcher_sync|vk_sparse_queue_order)$" (the tests this PR changes): pass on both GPUs, 5/5 each. No game files.

AI-assisted.

@throny throny 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 c7cc36b on NVIDIA RTX 4080, driver 610.88, Windows 11: pass

This head also fixes the D3D-514 hang. On main, Fence::claim records a queue Signal's value when Signal is called, not when it is submitted. So a relay queue's held Signal(F, 98), which waits behind its own Wait(F, 97), claims 98 first, and the producer's Signal(F, 97) that comes after it is dropped with S_OK (fence signal 97 is not above 98; Vulkan timelines cannot go back). Nothing ever reaches 97, so the relay and every reader of 97 wait forever. Host D3D12 runs the same calls and passes. In this PR the signals go through LogicalFence, there is no call-time claim, and the case completes with exact readbacks.

Scenario (one fence F, b = 2·i): P uploads a texture and a buffer, then Signal(F, b+1). R does Wait(F, b+1), a copy, then Signal(F, b+2). C2 does Wait(F, b+2) and reads back. C1 does Wait(F, b+1) and reads back. The queues are COPY and DIRECT, one per role. All 24 call orders × 8 type assignments make 192 iterations, and both readbacks are compared byte for byte with the CPU's data. Builds: MSVC 19.44 (VS 2022 BuildTools), Vulkan SDK 1.4.363.0, Ninja RelWithDebInfo, standalone device. Runs alternated main → PR, one process on the GPU at a time.

Build Runs Result
host D3D12 (RTX 4080) 1 192/192 exact
main 3faac557 5 5 hang at iteration 48 (iterations 0–47 exact), each run printing fence signal 97 is not above 98 once
this PR c7cc36bc 5 5 pass: 192/192 iterations exact, 0 differing bytes, C2-held probe 96/96, no is not above note
this PR, LEONIDA_VK_VALIDATION=1 (with sync validation) 1 pass, 0 VUID-
main, LEONIDA_VK_VALIDATION=1 1 hang at iteration 48, 0 VUID- before it

Iteration 48 is the first order in which R's calls (Wait(F, 97), ExecuteCommandLists, Signal(F, 98)) come before P's Signal(F, 97).

Not covered: COMPUTE queues, the caller-owned device modes, and any GPU other than the RTX 4080. I did not rerun the rest of ctest on this head; this review covers only the scenario above.

Reproduction (rt196_same_fence_test.cpp; put it in runtime/test, link gta6rt_d3d12_com d3d12 dxgi like the other d3d12_* tests; usage: rt196_same_fence_test [iterations=192] [--p-first] [--host], exit 0 pass, 1 readback failure, 3 hang)
// RT-196: two waits on DIFFERENT values of ONE fence across COPY and DIRECT queues, with a texture and a buffer handed
// over (docs/d3d12_vulkan.md section 4.4). Not part of the repository; reviewers' scratch check for PR #2951.
//
// Per iteration i, one fence F (shared by all iterations, b = 2 * i):
//   P  (producer)   upload -> stage0 texture + buffer                 Signal(F, b + 1)
//   R  (relay)      Wait(F, b + 1)  stage0 -> stage1                  Signal(F, b + 2)
//   C2 (late read)  Wait(F, b + 2)  stage1 -> readback B              Signal(D2, i + 1)
//   C1 (early read) Wait(F, b + 1)  stage0 -> readback A              Signal(D1, i + 1)
// P and R are on different queue types (COPY/DIRECT); C1 and C2 are COPY or DIRECT; every role has its own queue.
// The four submissions reach their queues in one of the 24 orders, so consumers are often submitted before their
// producers. A layer that treated Wait(F, b + 2) as satisfied by the Signal of b + 1 would record C2 before R, against
// the layouts from before R ran. Both readbacks are compared byte for byte with what the CPU wrote.
// No game data.
#include "../shims/d3d12_com.h"

#include <dxgi1_4.h>
#include <wrl/client.h>

#include <algorithm>
#include <array>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <thread>
#include <vector>

using Microsoft::WRL::ComPtr;

namespace {

constexpr UINT dim = 16;  // 16 x 16 RGBA8
constexpr UINT pitch = D3D12_TEXTURE_DATA_PITCH_ALIGNMENT;
constexpr UINT64 buffer_bytes = 1024;
constexpr UINT64 texture_offset = 1024;
constexpr UINT64 staging_bytes = texture_offset + UINT64(dim) * pitch;

std::atomic<ULONGLONG> deadline{0};
std::atomic<int> current_iter{-1};

std::uint32_t pattern(std::uint32_t seed, std::uint32_t i) {
    std::uint32_t x = seed * 0x9e3779b1u + i * 0x85ebca6bu + 0x1234567u;
    x ^= x >> 15; x *= 0x2c1b3c6du; x ^= x >> 12; x *= 0x297a2d39u; x ^= x >> 15;
    return x | 0x01000000u;  // never zero
}

enum Type { copy_q = 0, direct_q = 1 };
constexpr const char* type_name[] = {"COPY", "DIRECT"};
constexpr D3D12_COMMAND_LIST_TYPE list_type[] = {D3D12_COMMAND_LIST_TYPE_COPY, D3D12_COMMAND_LIST_TYPE_DIRECT};

D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) {
    D3D12_RESOURCE_DESC d{};
    d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
    d.Width = bytes;
    d.Height = d.DepthOrArraySize = d.MipLevels = 1;
    d.SampleDesc.Count = 1;
    d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
    return d;
}
D3D12_RESOURCE_DESC texture_desc() {
    D3D12_RESOURCE_DESC d{};
    d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
    d.Width = d.Height = dim;
    d.DepthOrArraySize = d.MipLevels = 1;
    d.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    d.SampleDesc.Count = 1;
    return d;
}
D3D12_RESOURCE_BARRIER transition(ID3D12Resource* r, D3D12_RESOURCE_STATES a, D3D12_RESOURCE_STATES b) {
    D3D12_RESOURCE_BARRIER x{};
    x.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
    x.Transition = {r, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, a, b};
    return x;
}
D3D12_TEXTURE_COPY_LOCATION footprint(ID3D12Resource* r) {
    D3D12_TEXTURE_COPY_LOCATION l{};
    l.pResource = r;
    l.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
    l.PlacedFootprint = {texture_offset, {DXGI_FORMAT_R8G8B8A8_UNORM, dim, dim, 1, pitch}};
    return l;
}
D3D12_TEXTURE_COPY_LOCATION subresource(ID3D12Resource* r) {
    D3D12_TEXTURE_COPY_LOCATION l{};
    l.pResource = r;
    l.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
    return l;
}

struct Set {
    ComPtr<ID3D12Resource> texture, buffer;
};

struct Totals {
    int iterations = 0, passed = 0, failed = 0;
    unsigned long long bad_bytes = 0;
};

struct Iteration {
    ID3D12Device* device;
    int seed;
    ComPtr<ID3D12Resource> upload, readback[2];  // [0] A (from stage0), [1] B (from stage1)
    Set stage[2];
    std::vector<ComPtr<ID3D12CommandAllocator>> allocators;
    std::vector<ComPtr<ID3D12GraphicsCommandList>> lists;

    bool make() {
        D3D12_HEAP_PROPERTIES def{D3D12_HEAP_TYPE_DEFAULT}, up{D3D12_HEAP_TYPE_UPLOAD}, rb{D3D12_HEAP_TYPE_READBACK};
        const auto staging = buffer_desc(staging_bytes);
        const auto buf = buffer_desc(buffer_bytes);
        const auto tex = texture_desc();
        if (FAILED(device->CreateCommittedResource(&up, D3D12_HEAP_FLAG_NONE, &staging,
                                                   D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&upload))))
            return false;
        for (auto& r : readback)
            if (FAILED(device->CreateCommittedResource(&rb, D3D12_HEAP_FLAG_NONE, &staging,
                                                       D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&r))))
                return false;
        for (auto& s : stage)
            if (FAILED(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_COMMON,
                                                       nullptr, IID_PPV_ARGS(&s.texture))) ||
                FAILED(device->CreateCommittedResource(&def, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COMMON,
                                                       nullptr, IID_PPV_ARGS(&s.buffer))))
                return false;
        std::uint8_t* m = nullptr;
        const D3D12_RANGE none{0, 0};
        if (FAILED(upload->Map(0, &none, reinterpret_cast<void**>(&m)))) return false;
        for (UINT64 i = 0; i < buffer_bytes / 4; ++i)
            reinterpret_cast<std::uint32_t*>(m)[i] = pattern(seed, std::uint32_t(i));
        for (UINT y = 0; y < dim; ++y)
            for (UINT x = 0; x < dim; ++x)
                reinterpret_cast<std::uint32_t*>(m + texture_offset + y * pitch)[x] = pattern(seed + 7919, y * dim + x);
        upload->Unmap(0, nullptr);
        // Readbacks start filled with 0xCD, so a copy that never landed shows up as differing bytes.
        for (auto& r : readback) {
            if (FAILED(r->Map(0, nullptr, reinterpret_cast<void**>(&m)))) return false;
            std::memset(m, 0xcd, size_t(staging_bytes));
            const D3D12_RANGE all{0, size_t(staging_bytes)};
            r->Unmap(0, &all);
        }
        return true;
    }

    // src null: upload buffer; dst null: readback[rb].
    ID3D12GraphicsCommandList* list(Type type, const Set* src, const Set* dst, int rb) {
        ComPtr<ID3D12CommandAllocator> a;
        ComPtr<ID3D12GraphicsCommandList> l;
        if (FAILED(device->CreateCommandAllocator(list_type[type], IID_PPV_ARGS(&a))) ||
            FAILED(device->CreateCommandList(0, list_type[type], a.Get(), nullptr, IID_PPV_ARGS(&l))))
            return nullptr;
        std::vector<D3D12_RESOURCE_BARRIER> before, after;
        const auto track = [&](ID3D12Resource* r, D3D12_RESOURCE_STATES s) {
            before.push_back(transition(r, D3D12_RESOURCE_STATE_COMMON, s));
            after.push_back(transition(r, s, D3D12_RESOURCE_STATE_COMMON));
        };
        if (src) {
            track(src->texture.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE);
            track(src->buffer.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE);
        }
        if (dst) {
            track(dst->texture.Get(), D3D12_RESOURCE_STATE_COPY_DEST);
            track(dst->buffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST);
        }
        l->ResourceBarrier(UINT(before.size()), before.data());
        ID3D12Resource* rbr = readback[rb].Get();
        l->CopyBufferRegion(dst ? dst->buffer.Get() : rbr, 0, src ? src->buffer.Get() : upload.Get(), 0, buffer_bytes);
        const auto to = dst ? subresource(dst->texture.Get()) : footprint(rbr);
        const auto from = src ? subresource(src->texture.Get()) : footprint(upload.Get());
        l->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr);
        l->ResourceBarrier(UINT(after.size()), after.data());
        if (FAILED(l->Close())) return nullptr;
        allocators.push_back(a);
        lists.push_back(l);
        return l.Get();
    }

    // Byte comparison of readback[rb] with the CPU's data: buffer bytes [0, 1024), texture rows at texture_offset.
    unsigned long long verify(int rb, const char* label, int iter) {
        std::uint8_t* m = nullptr;
        if (FAILED(readback[rb]->Map(0, nullptr, reinterpret_cast<void**>(&m)))) return ~0ull;
        unsigned long long bad_buf = 0, bad_tex = 0;
        long long first_buf = -1, first_tex = -1;
        for (UINT64 i = 0; i < buffer_bytes; ++i) {
            const std::uint32_t w = pattern(seed, std::uint32_t(i / 4));
            const std::uint8_t want = std::uint8_t(w >> (8 * (i % 4)));
            if (m[i] != want) { if (first_buf < 0) first_buf = (long long)i; ++bad_buf; }
        }
        for (UINT y = 0; y < dim; ++y)
            for (UINT b = 0; b < dim * 4; ++b) {
                const UINT64 off = texture_offset + UINT64(y) * pitch + b;
                const std::uint32_t w = pattern(seed + 7919, y * dim + b / 4);
                const std::uint8_t want = std::uint8_t(w >> (8 * (b % 4)));
                if (m[off] != want) { if (first_tex < 0) first_tex = (long long)off; ++bad_tex; }
            }
        if (bad_buf)
            std::printf("  iter %d readback %s buffer: %llu of %llu bytes differ, first at offset %lld (got %02x)\n",
                        iter, label, bad_buf, buffer_bytes, first_buf, m[first_buf]);
        if (bad_tex)
            std::printf("  iter %d readback %s texture: %llu of %u bytes differ, first at readback offset %lld (got %02x)\n",
                        iter, label, bad_tex, dim * dim * 4, first_tex, m[first_tex]);
        readback[rb]->Unmap(0, nullptr);
        return bad_buf + bad_tex;
    }
};

bool wait_value(ID3D12Fence* f, UINT64 v, const char* what, int iter) {
    if (f->GetCompletedValue() >= v) return true;
    HANDLE e = CreateEventW(nullptr, FALSE, FALSE, nullptr);
    if (!e || FAILED(f->SetEventOnCompletion(v, e))) return false;
    const bool ok = WaitForSingleObject(e, 15000) == WAIT_OBJECT_0;
    CloseHandle(e);
    if (!ok) {
        std::printf("HANG: iter %d: fence %s never reached %llu (completed %llu)\n", iter, what,
                    (unsigned long long)v, (unsigned long long)f->GetCompletedValue());
        std::fflush(stdout);
        std::_Exit(3);
    }
    return true;
}

}  // namespace

int main(int argc, char** argv) {
    const int iterations = argc > 1 ? std::atoi(argv[1]) : 192;
    std::thread([] {
        for (;;) {
            Sleep(100);
            const ULONGLONG limit = deadline.load();
            if (limit && GetTickCount64() > limit) {
                std::printf("HANG (watchdog) in iteration %d\n", current_iter.load());
                std::fflush(stdout);
                std::_Exit(3);
            }
        }
    }).detach();

    // --host: the same scenario on the host D3D12 runtime (first hardware adapter), to show it is valid D3D12.
    // --p-first: only the 12 orders in which P's Signal(F, b + 1) is called before R's Signal(F, b + 2). The other
    // 12 call the higher Signal first (it executes second on the GPU, since R waits for b + 1).
    bool host = false, p_first = false;
    for (int a = 2; a < argc; ++a) {
        host |= std::strcmp(argv[a], "--host") == 0;
        p_first |= std::strcmp(argv[a], "--p-first") == 0;
    }
    ComPtr<ID3D12Device> device;
    if (host) {
        ComPtr<IDXGIFactory4> factory;
        if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)))) return 77;
        for (UINT i = 0; !device; ++i) {
            ComPtr<IDXGIAdapter1> adapter;
            if (factory->EnumAdapters1(i, &adapter) != S_OK) break;
            DXGI_ADAPTER_DESC1 desc{};
            if (FAILED(adapter->GetDesc1(&desc)) || (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)) continue;
            if (SUCCEEDED(D3D12CreateDevice(adapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device))))
                std::printf("host D3D12 adapter: %ls\n", desc.Description);
        }
        if (!device) { std::puts("no host D3D12 adapter"); return 77; }
    } else if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device)))) {
        std::puts("Vulkan standalone device unavailable");
        return 77;
    }
    // Two queues of each type: P, R, C1, C2 use distinct queues (the n-th role of a type takes the n-th queue).
    constexpr int max_slots = 3;
    ComPtr<ID3D12CommandQueue> queues[2][max_slots];
    int available[2] = {0, 0};
    for (int i = 0; i < max_slots; ++i)
        for (int t = 0; t < 2; ++t) {
            D3D12_COMMAND_QUEUE_DESC d{};
            d.Type = list_type[t];
            if (available[t] == i && SUCCEEDED(device->CreateCommandQueue(&d, IID_PPV_ARGS(&queues[t][i]))))
                ++available[t];
        }
    std::printf("queues (COPY/DIRECT): %d/%d\n", available[0], available[1]);

    ComPtr<ID3D12Fence> F, D[2];
    if (FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&F))) ||
        FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&D[0]))) ||
        FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&D[1]))))
        return 1;

    Totals total;
    int skipped = 0, held_ok = 0, held_checked = 0;
    for (int it = 0; it < iterations; ++it) {
        current_iter = it;
        deadline = GetTickCount64() + 30000;
        // Combination: 8 type assignments x 24 orders, walked deterministically.
        const int types = it % 8;
        const int order_index = (it / 8) % 24;
        const Type pt = (types & 1) ? direct_q : copy_q;
        const Type rt_ = pt == copy_q ? direct_q : copy_q;
        const Type c1t = (types & 2) ? direct_q : copy_q;
        const Type c2t = (types & 4) ? direct_q : copy_q;
        const Type role_type[4] = {pt, rt_, c2t, c1t};  // P, R, C2, C1
        int role_slot[4];
        for (int r = 0; r < 4; ++r) {
            role_slot[r] = 0;
            for (int p = 0; p < r; ++p) role_slot[r] += role_type[p] == role_type[r];
        }
        bool fits = true;
        for (int r = 0; r < 4; ++r) fits &= role_slot[r] < available[role_type[r]];
        if (!fits) { ++skipped; continue; }
        std::array<int, 4> order{0, 1, 2, 3};
        if (!p_first) {
            for (int k = 0; k < order_index; ++k) std::next_permutation(order.begin(), order.end());
        } else {
            for (int k = 0, seen = -1;; std::next_permutation(order.begin(), order.end()), ++k) {
                const bool ok = std::find(order.begin(), order.end(), 0) < std::find(order.begin(), order.end(), 1);
                if (ok && ++seen == order_index % 12) break;
            }
        }

        const UINT64 b = 2ull * UINT64(it);
        Iteration c{device.Get(), 1000 + it};
        if (!c.make()) { std::puts("resource creation failed"); return 1; }
        ID3D12GraphicsCommandList* l[4] = {
            c.list(role_type[0], nullptr, &c.stage[0], 0),     // P: upload -> stage0
            c.list(role_type[1], &c.stage[0], &c.stage[1], 0),  // R: stage0 -> stage1
            c.list(role_type[2], &c.stage[1], nullptr, 1),     // C2: stage1 -> readback B
            c.list(role_type[3], &c.stage[0], nullptr, 0),     // C1: stage0 -> readback A
        };
        for (auto* x : l)
            if (!x) { std::puts("list creation failed"); return 1; }
        bool calls_ok = true;
        for (int r : order) {
            ID3D12CommandQueue* q = queues[role_type[r]][role_slot[r]].Get();
            ID3D12CommandList* batch[] = {l[r]};
            switch (r) {
            case 0:  // P
                q->ExecuteCommandLists(1, batch);
                calls_ok &= SUCCEEDED(q->Signal(F.Get(), b + 1));
                break;
            case 1:  // R
                calls_ok &= SUCCEEDED(q->Wait(F.Get(), b + 1));
                q->ExecuteCommandLists(1, batch);
                calls_ok &= SUCCEEDED(q->Signal(F.Get(), b + 2));
                break;
            case 2:  // C2
                calls_ok &= SUCCEEDED(q->Wait(F.Get(), b + 2));
                q->ExecuteCommandLists(1, batch);
                calls_ok &= SUCCEEDED(q->Signal(D[1].Get(), UINT64(it) + 1));
                break;
            case 3:  // C1
                calls_ok &= SUCCEEDED(q->Wait(F.Get(), b + 1));
                q->ExecuteCommandLists(1, batch);
                calls_ok &= SUCCEEDED(q->Signal(D[0].Get(), UINT64(it) + 1));
                break;
            }
            // Probe: P is submitted and R is not yet. Once P's work is done, F must be at b + 1 exactly and C2 (which
            // waits for b + 2) must not have run.
            if (r == 0 && std::find(order.begin(), order.end(), 1) > std::find(order.begin(), order.end(), 0)) {
                wait_value(F.Get(), b + 1, "F (P)", it);
                Sleep(1);
                ++held_checked;
                if (D[1]->GetCompletedValue() < UINT64(it) + 1 && F->GetCompletedValue() == b + 1) ++held_ok;
                else std::printf("  iter %d: C2 completed (or F passed b+1) before R was submitted\n", it);
            }
        }
        if (!calls_ok) { std::printf("iter %d: a queue call failed\n", it); return 1; }
        wait_value(D[0].Get(), UINT64(it) + 1, "D1 (C1)", it);
        wait_value(D[1].Get(), UINT64(it) + 1, "D2 (C2)", it);
        wait_value(F.Get(), b + 2, "F (R)", it);
        const auto bad = c.verify(0, "A(C1, waits b+1)", it) + c.verify(1, "B(C2, waits b+2)", it);
        ++total.iterations;
        if (bad) {
            ++total.failed;
            total.bad_bytes += bad;
            std::printf("FAIL iter %d: P=%s R=%s C1=%s C2=%s order=%c%c%c%c (P R C2 C1 = A B C D)\n", it,
                        type_name[pt], type_name[rt_], type_name[c1t], type_name[c2t], 'A' + order[0],
                        'A' + order[1], 'A' + order[2], 'A' + order[3]);
        } else {
            ++total.passed;
        }
    }
    deadline = 0;
    std::printf("iterations %d, passed %d, failed %d, differing bytes %llu, skipped (queues) %d, "
                "C2-held probe %d/%d\n",
                total.iterations, total.passed, total.failed, total.bad_bytes, skipped, held_ok, held_checked);
    std::fflush(stdout);
    return total.failed || held_ok != held_checked ? 1 : 0;
}

D3D-514. AI-assisted.

@emirduran707

Copy link
Copy Markdown
Contributor

A second GPU for the D3D-514 scenario in @throny's review: the same result on AMD.

AMD Radeon RX 9060 XT, driver 26.10.44, Windows 11, MSVC 14.44 (Visual Studio 2022), Ninja, RelWithDebInfo. I built @throny's rt196_same_fence_test.cpp unchanged in a worktree of each commit and ran it with its defaults (192 iterations), alternating main and this PR.

Build Runs Result
host D3D12 (--host, the AMD driver) 1 192/192 passed, 0 differing bytes
main 3faac557 3 3 hang at iteration 48 (fence D1 (C1) never reached 49), each printing is not above once
this PR c7cc36bc 3 3 pass: 192/192, 0 differing bytes, C2-held probe 96/96, no is not above line

Not covered: validation runs, COMPUTE queues, and the rest of ctest on this head. Synthetic data, no game files. AI-assisted (Claude Code).

@milas6669

Copy link
Copy Markdown

Tested c7cc36bc on NVIDIA GeForce RTX 3070 (driver 32.0.16.2124), Windows 11, MSVC 19.44, Vulkan SDK 1.4.363: pass.

Ran ctest -R fence (vk_fence_dispatcher_sync, d3d12_fence_timing, d3d12_fence_events, d3d12_fence_waiter: 4/4) and d3d12_fence_timing_test.exe directly (exit 0). The held-producer case (check_held_producer_rewind: COPY holds Signal(fence, 10), DIRECT signals 4) reads 4 then 10, the same on the standalone Vulkan device, the Xbox-ABI proxy, native D3D12 and WARP.

This is related to D3D-514 (#4933): the existing test is the nearest covered case, not the finding's two-consumer relay with readback, so that exact scenario remains untested here.

AI-assisted. Synthetic tests only; no game data.

@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested c7cc36b on AMD Radeon(TM) Graphics (integrated), driver 32.0.21043.5001, Windows 11: pass. This adds an integrated AMD result to the RX 9060 XT result.

I built the unchanged rt196_same_fence_test.cpp from throny's review with MSVC 14.51 in RelWithDebInfo. I set LEONIDA_VK_DEVICE=Radeon. Both executables identified the AMD adapter. I ran each executable once with argument 192.

Revision Result
Main 3faac55 Exit 3. At iteration 48 the runtime rejected signal 97 after signal 98. C1's completion fence stayed at 48 instead of reaching 49.
PR c7cc36b Exit 0. All 192 iterations passed. Both readbacks matched, with zero differing bytes. All 96 held-consumer checks passed. No queue assignment skipped.

The fixture covers 24 call orders and eight COPY/DIRECT queue assignments. This run used the standalone Vulkan device without validation layers. AI-assisted.

@Exopus-0x65f7ad0

Copy link
Copy Markdown
Contributor

A data point for this PR from #4609: there, the layer's Fence::Signal(UINT64_MAX) hit VUID-VkSemaphoreSignalInfo-value-03260 on NVIDIA, whose maxTimelineSemaphoreValueDifference is 2^31-1. #4609's fix clamps the jump, but then events, blocking waits and queue waits for values above the limit diverge from the host (measurements).

I ran the same local probe on c7cc36bc (RTX 5060 Ti / 621.14, LEONIDA_VK_VALIDATION=1, probe added to d3d12_fence_timing_test and not pushed). All four cases match the host, with 0 validation errors:

  • A postponed Signal(UINT64_MAX) behind a queue Signal(f, 1) reads back 1. On the host the CPU signal is immediate and the queue's 1 lands afterwards; this PR's rewinds give the same value.
  • An event for UINT64_MAX registered before Signal(UINT64_MAX) is set.
  • A blocking wait for 2^32 returns at 1200 ms with 2^32. Another thread signals 2^31-1 at 200 ms and 2^32 at 1200 ms, so this is not an early return.
  • A queue Wait(f, UINT64_MAX) after Signal(UINT64_MAX) is released.

So the LogicalFence design also covers fence values beyond the timeline limit, which is worth a line in the description. I've noted the conflict with #4609 in d3d12_com.cpp there.

AI-assisted (Claude Code). Synthetic fences only.

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

Independent AMD synchronization-validation follow-up at exact head c7cc36b.

Hardware: AMD Radeon(TM) Graphics, device 0x164e, Windows driver 32.0.21043.5001 / Vulkan driver 26.3.1, Vulkan 1.4.315. Windows 11, MSVC 19.44, Windows SDK 10.0.26100, Vulkan SDK/validation layer 1.4.363.0.

Ran the unchanged 381-line rt196_same_fence_test.cpp fixture from review #6017875760, SHA-256 db46c9233efb000694ec1a69cb27c46c32075a9605a6a4b21d8d1719d335e828, through this PR's runtime. With synchronization validation enabled: 192 iterations, 192 passed, 0 failed, 0 differing bytes, 0 queue skips, C2-held probe 96/96, exit 0 (2.029 s). Captured stdout/stderr contains 0 validation errors, 0 warnings, 0 VUID IDs, and 0 SYNC-HAZARD IDs.

I verified that this runtime path actually exposes diagnostics: a separate synthetic control uses create_vulkan_device_standalone without a debug messenger and records two fills of one buffer. The no-barrier control emits one SYNC-HAZARD-WRITE-AFTER-WRITE message to the captured stdout; the same control with a transfer barrier emits zero. The relay fixture was then rerun under the identical settings:

LEONIDA_VK_DEVICE=radeon
LEONIDA_VK_VALIDATION=1
VK_KHRONOS_VALIDATION_VALIDATE_SYNC=1
VK_KHRONOS_VALIDATION_DEBUG_ACTION=VK_DBG_LAYER_ACTION_LOG_MSG
VK_KHRONOS_VALIDATION_LOG_FILENAME=stdout
VK_KHRONOS_VALIDATION_REPORT_FLAGS=error,warn
VK_LOADER_LAYERS_DISABLE=~implicit~
DISABLE_RTSS_LAYER=1
DISABLE_VULKAN_OBS_CAPTURE=1

Scope: the same-fence C0/C1/C2 relay fixture on this commit and driver. No production changes; only temporary local test targets. All inputs are synthetic, with no game files. AI-assisted: yes.

@Exopus-0x65f7ad0

Copy link
Copy Markdown
Contributor

The differential fence fuzzer I'm writing (claimed in #5032) ran on c7cc36bc: seeded random programs of queue Signal/Wait, CPU Signal, events and submissions, replayed on the layer and on the host D3D12 and compared once settled. RTX 5060 Ti / 621.14, LEONIDA_VK_VALIDATION=1.

Mode (30 seeds) main 3faac557 this PR c7cc36bc
default (monotonic, no release) identical identical
--rewinds (D3D-472) differs identical
--big (steps above 2^31-1, the #4609 case) VUID-03260 identical, 0 VUIDs
--release (fences released while in use) segfault 3 of 30 differ, no crash

So the LogicalFence design covers both rewinds and large values, and it fixes the main crash I described on #4740 (a satisfied queue Wait, the fence released, then the next submission).

The --release difference: a queue blocked on a fence that is then released stays blocked. On the host it goes on. Seed 24, reproduced 4 of 4 times:

DIRECT Wait(f3, 2)          // f3 is a CPU fence nobody signals yet: DIRECT blocks
...
release f3                  // the application releases it
...
DIRECT Signal(f3', 1)       // a new fence in that slot, signalled by DIRECT
-- settle
host  values: 5 0 3 1  events: 1100011
layer values: 5 0 3 0  events: 1100000

DIRECT never gets past the wait on the released fence, so the new fence stays at 0 and the three events on it are never set. The host behaviour matches what I measured with a plain host probe on #4282: a queue waiting on a released fence continues.

This is D3D-496 case 2, which #4740 fixes for the current Fence (on #4740's head all 30 --release seeds match the host). Since this PR replaces that code, whichever of the two lands second needs to carry the other's behaviour. The fuzzer can check it: d3d12_fence_fuzz_test --release --seeds 30. I'll link its PR here once it's up.

AI-assisted (Claude Code). Synthetic fences only, no game files.

@memorypressure

Copy link
Copy Markdown

Merges cleanly into 3faac55 and all docs/Python guards pass on the merged tree, but note the stack, verified on the graph: this branch contains #4224's head f56726d, which is not on main while #4224 is still open — so part of your diff against main is #4224's sparse-queue ordering, not the fence work. Land #4224 first or expect a re-merge. The runtime core (fence rewinds across CPU/GPU signals, new dispatcher-sync test) needs cmake and a GPU, so the C++ tests were not exercised here; the four checks are pending. AI-assisted: yes. Tested on Linux (RTX 5080 host, CPU-only run).

@DeSunShine

Copy link
Copy Markdown

Tested 2ae764b0a merged into main 1cc6e3c12 on NVIDIA GeForce RTX 4090 (driver 621.24), Windows 11 Pro 26200, MSVC (VS Build Tools 18) + Ninja, Vulkan SDK 1.4.363: pass.

  • ctest -R "buffer_tiles|fence|queue_handover|queue_share|vulkan_device|sparse_queue_order" --output-on-failure: 18/18 passed (includes d3d12_fence_timing, d3d12_fence_events, d3d12_fence_device_lost_counter, vk_fence_dispatcher_sync, the three d3d12_queue_handover*, d3d12_queue_share*, d3d12_vulkan_device, d3d12_buffer_tiles, vk_sparse_queue_order).

AI-assisted (Claude Code).

@SlopTart

Copy link
Copy Markdown

Linux AMD companion row to @DeSunShine's Windows 18/18 — head 2ae764b0 built fresh on RX 7900 XT (RADV NAVI31), Mesa 26.2.5, Arch/Omarchy:

No game files - repo tests only, bare hardware. Posted by Hermes (agent) on my machine (also the boxb/GTX 1070 reporter in #6296).

@SlopTart

Copy link
Copy Markdown

Pascal companion to our RDNA3 row — GTX 1070 (GP104), driver 550.163.01, Debian 13, head 2ae764b0 built fresh: the Linux-buildable subset of the ctest regex (vulkan_device_filter, vk_fence_dispatcher_sync, vk_sparse_queue_order) is 3/3 pass, same as on the RX 7900 XT / Mesa 26.2.5.

No game files — repo tests only, bare hardware. Posted by Hermes (agent) from the second machine (boxb, GTX 1070).

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.