From f8007dda67f9c45757b63df5c5fd8377647da4ae Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:02:33 +0100 Subject: Queue holds: review fixes (Present ordering, pins, timeline monotonicity, fence lifetime, teardown, docs) - Present is queued behind held work (QueueHolds::after_held) and submitted in order by the releasing thread. - Held batches keep the pipeline states and root signatures of their lists; fences a queue waits on or signals are kept until the submission has completed on the GPU (a D3D12 queue holds them). - A held Signal released below an unheld one on the same fence leaves the Vulkan signal out (claimed under the submit lock). - A queue destroyed with held Signals completes the CPU waits on their fences and reports it. - A failed held batch is reported (take_held_failure, last_execute_result), its waits stay for the next submission, and the Signal behind it still signals. - d3d12_queue_handover_test: pairs, two-thread signalling stress, held Signal of a released fence, shared fence, teardown with a CPU waiter; --two-queues and --shared-queue modes on a caller-owned device. - Tests for each fix in vk_presenter_sync_test, vk_queue_query_sync_test and d3d12_m4_compute_test; docs section 4.4. Co-Authored-By: Claude Opus 5.5 --- runtime/test/d3d12_queue_handover_test.cpp | 247 +++++++++++++++++++++++++++-- 1 file changed, 237 insertions(+), 10 deletions(-) (limited to 'runtime/test/d3d12_queue_handover_test.cpp') diff --git a/runtime/test/d3d12_queue_handover_test.cpp b/runtime/test/d3d12_queue_handover_test.cpp index c445fdfe6..d3ed188f6 100644 --- a/runtime/test/d3d12_queue_handover_test.cpp +++ b/runtime/test/d3d12_queue_handover_test.cpp @@ -17,6 +17,7 @@ // compared byte for byte with the data written by the CPU: a consumer replayed against the layout from before its // producer ran reads a zero-filled texture and fails here (and with LEONIDA_VK_VALIDATION=1 under sync validation). // No game data. +#include "vk_test_device.h" #include "../shims/d3d12_com.h" #include @@ -364,6 +365,7 @@ bool cpu_released_chain(Rig& rig, const Roles& roles, int seed) { // A CPU Signal that comes before the Wait (nothing is held), and one that comes after the batch was submitted. bool cpu_gate(Rig& rig, Type producer, Type consumer, bool signal_first, int seed) { + if (!rig.available[producer] || !rig.available[consumer]) return true; if (producer == consumer && rig.available[producer] < 2) return true; const int cslot = producer == consumer ? 1 : 0; std::string name = std::string("CPU Signal ") + (signal_first ? "before" : "after") + " the consumer's Wait, " + @@ -413,6 +415,7 @@ std::string capture_stderr(const std::function& body) { // A batch waits for a fence nobody signals. The other queues keep working, the batch never runs, destroying the queue // does not hang and the layer says why. Layer only: the host runtime has nothing to report. bool never_signaled(Rig& rig, int seed) { + if (!rig.available[copy_q] || !rig.available[direct_q]) return true; arm("fence nobody signals"); Case c(rig, seed); if (!c.make_resources()) return false; @@ -463,31 +466,210 @@ bool fence_released(Rig& rig, int seed) { ID3D12CommandList* batch[] = {held}; if (FAILED(victim->Wait(doomed.Get(), 9))) return c.fail("Wait", __LINE__); victim->ExecuteCommandLists(1, batch); - const std::string log = capture_stderr([&] { doomed.Reset(); victim.Reset(); }); - if (log.find("fence was released while a queue still held work") == std::string::npos) { + // The queue holds the fence it waits on, as D3D12 does: the application's release does not free it under the held + // batch. The batch stays held (nothing ran) and is reported when the queue goes. + doomed.Reset(); + Sleep(50); + const std::string log = capture_stderr([&] { victim.Reset(); }); + if (log.find("queue destroyed with") == std::string::npos) { + std::fprintf(stderr, "stderr was: \"%s\"\n", log.c_str()); + return c.fail("no report for the held batch", __LINE__); + } + ++cases_run; + return true; +} + +// Review item 4: a held Signal names a fence the application has released. The fence lives until the Signal has been +// submitted (a queue behind it that waits for the fence proves it was signaled), with nothing used after free. +bool held_signal_survives_release(Rig& rig, int seed) { + if (!rig.available[direct_q] || !rig.available[compute_q]) return true; + arm("held Signal of a released fence"); + Case c(rig, seed); + if (!c.make_resources()) return false; + ComPtr gate, target; + if (FAILED(rig.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate))) || + FAILED(rig.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&target)))) + return false; + ID3D12CommandQueue* a = rig.queues[direct_q][0].Get(); + ID3D12CommandQueue* b = rig.queues[compute_q][0].Get(); + // a: Wait(gate), copy upload -> stage[0], Signal(target) (held until the CPU signals the gate) + ID3D12GraphicsCommandList* produce = c.make_list(direct_q, nullptr, &c.stage[0], 3); + ID3D12GraphicsCommandList* consume = c.make_list(compute_q, &c.stage[0], nullptr, 3); + if (!produce || !consume) return c.fail("setup", __LINE__); + if (FAILED(a->Wait(gate.Get(), 1))) return c.fail("Wait", __LINE__); + ID3D12CommandList* pb[] = {produce}; + a->ExecuteCommandLists(1, pb); + if (FAILED(a->Signal(target.Get(), 1))) return c.fail("Signal", __LINE__); + if (FAILED(b->Wait(target.Get(), 1))) return c.fail("Wait", __LINE__); + ID3D12CommandList* cb[] = {consume}; + b->ExecuteCommandLists(1, cb); + if (FAILED(b->Signal(c.fence(2), 1))) return c.fail("Signal", __LINE__); + target.Reset(); // the application is done with it; both queues still name it + Sleep(20); + if (FAILED(gate->Signal(1))) return c.fail("CPU Signal", __LINE__); + ++cases_run; + return c.wait_fence(2, 1) && c.verify(); +} + +// Review item 3: Signal(F, 2) is held, Signal(F, 3) on another queue is not. When the held one is released the +// timeline is already at 3 and must not be signaled lower; a wait for 2 passes and F reads 3. Layer only (D3D12 sets +// the fence to the lower value). +bool monotonic_shared_fence(Rig& rig, int seed) { + if (!rig.available[direct_q] || !rig.available[copy_q] || !rig.available[compute_q]) return true; + arm("held Signal below an unheld one"); + Case c(rig, seed); + if (!c.make_resources()) return false; + ID3D12CommandQueue* a = rig.queues[direct_q][0].Get(); + ID3D12CommandQueue* b = rig.queues[copy_q][0].Get(); + ID3D12CommandQueue* w = rig.queues[compute_q][0].Get(); + ID3D12Fence *gate = c.fence(0), *shared = c.fence(1); + ID3D12GraphicsCommandList* produce = c.make_list(copy_q, nullptr, &c.stage[0], 3); + ID3D12GraphicsCommandList* consume = c.make_list(compute_q, &c.stage[0], nullptr, 3); + if (!gate || !shared || !produce || !consume) return c.fail("setup", __LINE__); + if (FAILED(a->Wait(gate, 1)) || FAILED(a->Signal(shared, 2))) return c.fail("held Signal", __LINE__); // held + ID3D12CommandList* pb[] = {produce}; + b->ExecuteCommandLists(1, pb); + if (FAILED(b->Signal(shared, 3))) return c.fail("Signal", __LINE__); // not held + if (c.wait_fence(1, 3) == false) return false; + if (FAILED(gate->Signal(1))) return c.fail("CPU Signal", __LINE__); // releases a + // A queue that waits for 2 now: satisfied, and the data the copy queue wrote is what it reads. + if (FAILED(w->Wait(shared, 2))) return c.fail("Wait", __LINE__); + ID3D12CommandList* cb[] = {consume}; + w->ExecuteCommandLists(1, cb); + if (FAILED(w->Signal(c.fence(2), 1))) return c.fail("Signal", __LINE__); + if (!c.wait_fence(2, 1) || !c.verify()) return false; + Sleep(50); + if (shared->GetCompletedValue() != 3) return c.fail("the fence went below 3", __LINE__); + ++cases_run; + return true; +} + +// Review item 5: a queue destroyed with a held Signal wakes the CPU wait on that fence (with a report) instead of +// leaving it hanging. +bool teardown_wakes_cpu_waiters(Rig& rig, int seed) { + arm("teardown with a held Signal"); + Case c(rig, seed); + if (!c.make_resources()) return false; + ComPtr victim; + const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + if (FAILED(rig.device->CreateCommandQueue(&desc, IID_PPV_ARGS(&victim)))) return true; + ID3D12Fence *never = c.fence(0), *target = c.fence(1); + if (FAILED(victim->Wait(never, 1)) || FAILED(victim->Signal(target, 1))) return c.fail("setup", __LINE__); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (FAILED(target->SetEventOnCompletion(1, event))) return c.fail("SetEventOnCompletion", __LINE__); + const std::string log = capture_stderr([&] { victim.Reset(); }); + const bool woke = WaitForSingleObject(event, 5000) == WAIT_OBJECT_0; + CloseHandle(event); + if (!woke) return c.fail("the CPU wait on the held Signal's fence was never woken", __LINE__); + if (log.find("CPU waits on the fences of its held Signals are completed") == std::string::npos) { std::fprintf(stderr, "stderr was: \"%s\"\n", log.c_str()); - return c.fail("no report for the dropped batch", __LINE__); + return c.fail("no report", __LINE__); } ++cases_run; return true; } +// Two threads: one submits a consumer and a relay (both held, waiting for fences that are signaled by queues it does +// not own), the other submits the producer and signals a CPU gate the producer waits on, at the same moment, many +// times over. Everything is built up front; the threads only make queue calls. +bool concurrent_signalling(Rig& rig, int iterations, int seed) { + if (!Roles::make(copy_q, compute_q, direct_q).fits(rig)) return true; // needs one queue of each type + arm("two threads signalling and releasing", 120000); + struct Round { + std::unique_ptr c; + Case::Job jobs[3]; + ID3D12GraphicsCommandList* lists[3]; + }; + std::vector rounds(iterations); + const Roles roles = Roles::make(copy_q, compute_q, direct_q); + for (int i = 0; i < iterations; ++i) { + Round& r = rounds[i]; + r.c = std::make_unique(rig, seed + i); + Case& c = *r.c; + if (!c.make_resources()) return false; + const bool gated = i % 2 == 0; + r.jobs[0] = {roles.type[0], roles.slot[0], nullptr, &c.stage[0], 3, gated ? std::vector>{{3, 1}} : std::vector>{}, 0}; + r.jobs[1] = {roles.type[1], roles.slot[1], &c.stage[0], &c.stage[1], 3, {{0, 1}}, 1}; + r.jobs[2] = {roles.type[2], roles.slot[2], &c.stage[1], nullptr, 3, {{1, 1}}, 2}; + for (int j = 0; j < 3; ++j) { + r.lists[j] = c.make_list(r.jobs[j].type, r.jobs[j].src, r.jobs[j].dst, r.jobs[j].mask); + if (!r.lists[j]) return false; + } + if (!c.fence(3)) return false; + } + std::atomic turn{-1}, ready{0}, failed{0}; + const auto fire = [&](Case& c, const Case::Job& job, ID3D12GraphicsCommandList* list) { + ID3D12CommandQueue* queue = rig.queues[job.type][job.slot].Get(); + for (const auto& [f, v] : job.waits) + if (FAILED(queue->Wait(c.fences[f].Get(), v))) failed++; + ID3D12CommandList* batch[] = {list}; + queue->ExecuteCommandLists(1, batch); + if (job.signal >= 0 && FAILED(queue->Signal(c.fences[job.signal].Get(), 1))) failed++; + }; + std::thread consumer_side([&] { + for (int i = 0; i < iterations; ++i) { + ready++; + while (turn.load() < i) std::this_thread::yield(); + fire(*rounds[i].c, rounds[i].jobs[2], rounds[i].lists[2]); + fire(*rounds[i].c, rounds[i].jobs[1], rounds[i].lists[1]); + } + }); + std::thread producer_side([&] { + for (int i = 0; i < iterations; ++i) { + while (ready.load() <= i) std::this_thread::yield(); + turn = i; + fire(*rounds[i].c, rounds[i].jobs[0], rounds[i].lists[0]); + if (i % 2 == 0 && FAILED(rounds[i].c->fences[3]->Signal(1))) failed++; + } + }); + producer_side.join(); + consumer_side.join(); + if (failed) return rounds[0].c->fail("a queue call failed", __LINE__); + bool ok = true; + for (int i = 0; i < iterations; ++i) { + arm("two threads signalling and releasing", 20000); + ok &= rounds[i].c->wait_fence(2, 1) && rounds[i].c->verify(); + } + cases_run += iterations; + return ok; +} + +// Producer and consumer on two queues, in both submission orders: what fits when the device hands over only two +// VkQueues (the D3D12 queues share them) and what M4's copy -> compute -> copy path does. +bool pair_case(Rig& rig, Type a, Type b, bool consumer_first, int seed) { + const int sb = a == b ? 1 : 0; + if (!rig.available[a] || sb >= rig.available[b]) return true; + std::string name = std::string("pair ") + type_name[a] + "->" + type_name[b] + + (consumer_first ? " consumer first" : " producer first"); + arm(name.c_str()); + Case c(rig, seed); + if (!c.make_resources()) return false; + const Case::Job produce{a, 0, nullptr, &c.stage[0], 3, {}, 0}; + const Case::Job consume{b, sb, &c.stage[0], nullptr, 3, {{0, 1}}, 2}; + if (consumer_first ? !(c.submit(consume) && c.submit(produce)) : !(c.submit(produce) && c.submit(consume))) + return false; + ++cases_run; + return c.wait_fence(2, 1) && c.verify(); +} + bool run_all(ID3D12Device* device, bool layer) { Rig rig; rig.device = device; - for (int t = 0; t < 3; ++t) - for (int i = 0; i < pool_size; ++i) { + for (int i = 0; i < pool_size; ++i) // one of each type first: a caller-owned device may hand over only a few + for (int t = 0; t < 3; ++t) { + if (rig.available[t] != i) continue; D3D12_COMMAND_QUEUE_DESC desc{}; desc.Type = list_type[t]; - if (FAILED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&rig.queues[t][i])))) break; - ++rig.available[t]; + if (SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&rig.queues[t][i])))) ++rig.available[t]; } std::printf("queues available per type (COPY/COMPUTE/DIRECT): %d/%d/%d\n", rig.available[0], rig.available[1], rig.available[2]); - if (!rig.available[0] || !rig.available[1] || !rig.available[2]) return true; // nothing to hand over between bool ok = true; int seed = 100, skipped = 0; + for (int a = 0; a < 3; ++a) + for (int b = 0; b < 3; ++b) + for (bool consumer_first : {true, false}) ok &= pair_case(rig, Type(a), Type(b), consumer_first, ++seed); std::array order{0, 1, 2}; for (int a = 0; a < 3; ++a) for (int b = 0; b < 3; ++b) @@ -511,12 +693,16 @@ bool run_all(ID3D12Device* device, bool layer) { for (int p = 0; p < 3; ++p) for (int q = 0; q < 3; ++q) for (bool first : {true, false}) ok &= cpu_gate(rig, Type(p), Type(q), first, ++seed); + ok &= concurrent_signalling(rig, 200, seed += 1000); if (layer) { // The layer hands out a limited number of VkQueues: give the spare ones back for the two cases below. for (auto& type_queues : rig.queues) for (int i = 1; i < pool_size; ++i) type_queues[i].Reset(); ok &= never_signaled(rig, ++seed); ok &= fence_released(rig, ++seed); + ok &= held_signal_survives_release(rig, ++seed); + ok &= monotonic_shared_fence(rig, ++seed); + ok &= teardown_wakes_cpu_waiters(rig, ++seed); } if (skipped) std::printf("(%d type assignments need more queues than the device gave)\n", skipped); return ok; @@ -539,7 +725,15 @@ ComPtr native_device(std::wstring& name) { } // namespace -int main() { +// Modes (argv[1]): +// (none) the standalone device, which gives each D3D12 queue its own VkQueue; then the host runtime +// --two-queues a caller-owned device with two VkQueues of the family handed over (VulkanDeviceInfo::command_queues): +// the D3D12 queues of a type share them, so a Wait and the Signal it needs can land on one VkQueue +// --shared-queue a caller-owned device that hands over its one VkQueue: every D3D12 queue shares it (the legacy +// single-queue behaviour), where a Wait submitted ahead of its Signal would never progress on the GPU +int main(int argc, char** argv) { + const bool two_queues = argc > 1 && std::strcmp(argv[1], "--two-queues") == 0; + const bool shared_queue = argc > 1 && std::strcmp(argv[1], "--shared-queue") == 0; std::thread([] { for (;;) { Sleep(100); @@ -552,8 +746,32 @@ int main() { } }).detach(); + vktest::Device vk; ComPtr layer; - if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&layer)))) { + if (two_queues || shared_queue) { + vk.queue_count_wanted = two_queues ? 2 : 1; + const auto status = vk.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + if (two_queues && vk.queues.size() < 2) { + std::puts("the queue family has one queue: two-queue mode skipped"); + return 77; + } + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = vk.instance_proc; + info.instance = vk.instance; + info.physical = vk.physical; + info.device = vk.device; + info.queue = vk.queue; + info.queue_family = vk.family; + if (two_queues) info.command_queues = vk.queues; + if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&layer)))) { + std::puts("Vulkan device unavailable"); + return 77; + } + std::printf("caller-owned device, %zu VkQueue(s) handed to the layer\n", + two_queues ? vk.queues.size() : size_t(1)); + } else if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&layer)))) { std::puts("Vulkan standalone device unavailable"); return 77; } @@ -562,6 +780,15 @@ int main() { if (!run_all(layer.Get(), true)) return 1; const int layer_cases = cases_run; std::printf("Vulkan layer: %d cases passed, every one exact\n", layer_cases); + layer.Reset(); + if (vk.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); + return 1; + } + if (two_queues || shared_queue) { + deadline = 0; + return 0; + } std::wstring name; if (auto host = native_device(name)) { -- cgit v1.2.3 From 48cee7c2c69e502cc864b0789a9cf5bb88e98658 Mon Sep 17 00:00:00 2001 From: AlxcBTW <187763517+AlxcBTW@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:20:36 +0100 Subject: Queue holds: second review fixes (claim after submit, presenter locking and bound, teardown pump, tests) - A Signal counts as submitted only after vkQueueSubmit succeeded: a failed submit releases no waiter and the retry goes through. - ~VulkanQueue pumps after dropping held work; fence keep-alives are also drained in wait() and marker(). - VulkanPresenter: counters are atomics, read_back/enable_capture take the presenter mutex, set_abort has its own mutex, a deferred present reports not tearing, and at most 8 presents queue up before the caller waits. - Tests: three presents (blit, blank, composed) queued behind held work run in order, a present behind a destroyed queue's held work runs, a failed Signal does not release its waiters; the handover modes also run on the host runtime. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12_vulkan.md | 16 ++++++- runtime/src/queue_holds.h | 18 ++++---- runtime/src/vulkan_backend.h | 30 +++++++++---- runtime/src/vulkan_present.h | 69 +++++++++++++++++++++++++----- runtime/test/d3d12_queue_handover_test.cpp | 7 +-- runtime/test/vk_presenter_sync_test.cpp | 56 ++++++++++++++++++++++-- runtime/test/vk_queue_query_sync_test.cpp | 27 ++++++++++++ 7 files changed, 183 insertions(+), 40 deletions(-) (limited to 'runtime/test/d3d12_queue_handover_test.cpp') diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index b1eea5885..4ad4935d1 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2057,7 +2057,10 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a Resources are not kept: a resource released while a batch that names it is held fails that batch at release. Order against other work: a held `Signal(F, v)` released after an unheld `Signal(F, w)` with `w >= v` leaves the Vulkan signal out (timelines only increase; waits for `v` already pass), decided under the submit lock so the - order of the checks is the order of the submissions; `Present` is queued behind held work too (below). Edge cases: + order of the checks is the order of the submissions, and the value counts as submitted only once the + `vkQueueSubmit` succeeded (a failed Signal releases nobody and its retry goes through); `Present` is queued behind + held work too (below). Fence keep-alives are released outside the queue lock, at the next `ExecuteCommandLists`, + `Signal`, `Wait` or marker once their submission has completed. Edge cases: a queue destroyed with held operations reports them once (stderr: `queue destroyed with N held operation(s) never submitted: waits for a fence value (V) that no Signal reached`) and goes on without waiting, and the CPU waits on the fences of its held Signals are completed, as a released fence completes them; queues that wait for those fences @@ -2076,12 +2079,21 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a releases the last operation held when it was called. It is not blocked on the calling thread because the Signal that releases the work may be one that thread makes after `Present` returns. Held work that is never released holds back the presents after it (device-wide, since the layer cannot tell which batch draws into which back buffer). A - blank present reads nothing and is only ordered behind earlier queued presents. + blank present reads nothing and is only ordered behind earlier queued presents. At most 8 presents queue up; the + next one waits for held work to release (logged once; `set_abort` ends the wait), as a full frame-latency queue + does. A queued present reports `last_present_tore()` false, which the Xbox PresentX path turns into the default + vblank sync for the frame pacer. The presenter's state is guarded by one mutex (the counters are atomics, so + reading them never waits for a present blocked on a swapchain image); `set_abort` has its own. Facts from vkd3d-proton (LGPL, approach only, nothing copied): it keeps a CPU-side virtual value and pending signals per fence and blocks the queue's submission thread until a signal that satisfies a wait has been submitted, so Vulkan never sees a wait without a submitted signal. Resources are `VK_SHARING_MODE_EXCLUSIVE` and every D3D12 queue is in the graphics family, so no ownership transfer is needed; with dedicated compute/transfer families they would need `CONCURRENT` (vkd3d-proton does that, because D3D12 gives no information for transfers). + Every mode of the handover test ends with the same cases on the host runtime (the expected data is the CPU's + pattern in all of them, so that run shows the cases are valid D3D12 and holds the layer's modes to one bar). + The pipeline-state and root-signature pins are covered end to end by `d3d12_m4_compute_test`: the compute list is + executed while held, its two PSOs and root signature are released and the list is Reset, the copy that releases + it is submitted, and the output is compared with the CPU (it reads zeros without the pins). Measured: `d3d12_queue_handover_test` (three modes: the standalone device with a `VkQueue` per D3D12 queue, then the host runtime; `--two-queues`, a caller-owned device with two `VkQueue`s handed over; `--shared-queue`, one) runs 592 cases on the layer on the Radeon 880M and the RTX 5070 (also with one shared `VkQueue`; 8 with two handed over) and 587 on the host runtime: pairs and three-stage chains (produce, relay, consume) diff --git a/runtime/src/queue_holds.h b/runtime/src/queue_holds.h index 4a1f990d8..2839d4210 100644 --- a/runtime/src/queue_holds.h +++ b/runtime/src/queue_holds.h @@ -81,18 +81,16 @@ public: if (it != fences_.end() && it->second < value) it->second = value; } - // A queue is about to submit a Signal of `value`; call inside the device submit lock, so the order of the - // calls is the order of the vkQueueSubmits. False when a Signal of at least `value` was already submitted: the - // timeline cannot go down or stay (VUID-VkSubmitInfo-pSignalSemaphores-03242 and the timeline rules), and a wait - // for `value` is already satisfied, so the Vulkan signal is left out. This happens when a held Signal(F, 2) is - // released after an unheld Signal(F, 3). Unknown semaphores are always signaled. - bool claim_signal(Semaphore semaphore, std::uint64_t value) { + // A queue is about to submit a Signal of `value`; call inside the device submit lock, and record the value with + // signaled() only once the vkQueueSubmit succeeded (a failed submit signals nothing: waiters must stay held and a + // retry must go through). False when a Signal of at least `value` was already submitted: the timeline cannot go + // down or stay (VUID-VkSubmitInfo-pSignalSemaphores-03242 and the timeline rules), and a wait for `value` is + // already satisfied, so the Vulkan signal is left out. This happens when a held Signal(F, 2) is released after an + // unheld Signal(F, 3). Unknown semaphores are always signaled. + bool would_signal(Semaphore semaphore, std::uint64_t value) const { std::lock_guard lock(mutex_); const auto it = fences_.find(semaphore); - if (it == fences_.end()) return true; - if (it->second >= value) return false; - it->second = value; - return true; + return it == fences_.end() || it->second < value; } // true when no submitted Signal reaches `value` yet. Unknown semaphores are satisfied. diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index 7faaaeaa5..979a836ed 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -1446,6 +1446,7 @@ public: auto& vk = context_.vk; context_.holds().detach(this); // no thread releases into this queue from here on report_held_at_teardown(); + context_.holds().pump_ready(); // presents queued behind what was just dropped can run if (queue_) { std::lock_guard lock(context_.submit_mutex()); for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); @@ -1602,10 +1603,14 @@ public: // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet). // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences). void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) { - std::lock_guard state(state_mutex_); - waits_.push_back(fence); - wait_values_.push_back(value); - if (pin) wait_pins_.push_back(pin()); + std::vector> retired; // fences whose submission has completed: released unlocked + { + std::lock_guard state(state_mutex_); + waits_.push_back(fence); + wait_values_.push_back(value); + if (pin) wait_pins_.push_back(pin()); + drain_pins(retired); + } } // The first failure of a held ExecuteCommandLists since the last call (what the call would have returned had it @@ -1618,7 +1623,9 @@ public: // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension. void marker(DebugMarker::Kind kind, const char* label) { + std::vector> retired; std::lock_guard state(state_mutex_); + drain_pins(retired); // destroyed after the lock (reverse declaration order) if (!held_.empty()) { // behind the held work, so behind it in the queue's labels too Deferred op; op.kind = Deferred::Kind::marker; @@ -2077,8 +2084,8 @@ private: case Deferred::Kind::batch: { std::vector lists; for (const CommandList& list : op.lists) lists.push_back(&list); - // The pipeline states and root signatures of the lists are in wait_pins_ too (see execute()): they live - // until here, and are released once the batch has been recorded. + // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until + // the batch has been recorded and then, with the fences, until its submission has completed (below). const ReplayResult result = execute_now(lists); if (result != ReplayResult::success) { int none = static_cast(ReplayResult::success); @@ -2350,10 +2357,12 @@ private: VkSemaphore signals[2]{progress_, VK_NULL_HANDLE}; std::uint64_t signal_values[2]{ticket, 0}; std::uint32_t signal_count = 1; - // Claimed under the submit lock, so the order of the claims is the order of the submissions. A Signal + // Decided under the submit lock, so the order of the checks is the order of the submissions. A Signal // that is not above what was already submitted for this fence (a held Signal(F, 2) released after an // unheld Signal(F, 3)) leaves the Vulkan signal out: the timeline cannot go down, and waits for 2 pass. - if (fence && context_.holds().claim_signal(fence, value)) { + // The value counts as submitted only after the submit succeeded (below). + const bool signals_fence = fence && context_.holds().would_signal(fence, value); + if (signals_fence) { signals[signal_count] = fence; signal_values[signal_count] = value; ++signal_count; @@ -2372,7 +2381,10 @@ private: submit.signalSemaphoreCount = signal_count; submit.pSignalSemaphores = signals; res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); - if (res == VK_SUCCESS) context_.record_submit_locked(progress_, ticket); + if (res == VK_SUCCESS) { + context_.record_submit_locked(progress_, ticket); + if (signals_fence) context_.holds().signaled(fence, value); + } } if (res == VK_ERROR_DEVICE_LOST) { context_.mark_device_lost(); diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index 4e35774c4..8c3329c1e 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -35,6 +35,8 @@ #include #include +#include +#include #include #include #include @@ -44,6 +46,7 @@ #include #include #include +#include #include namespace leonida { @@ -181,7 +184,10 @@ public: VulkanPresenter& operator=(const VulkanPresenter&) = delete; bool ok() const { return ok_; } - VkExtent2D extent() const { return extent_; } + VkExtent2D extent() const { + const std::uint64_t packed = extent_packed_; + return {std::uint32_t(packed >> 32), std::uint32_t(packed)}; + } VkFormat format() const { return format_; } std::uint64_t presented() const { return presented_; } // The present mode a tearing present uses (IMMEDIATE, else FIFO_RELAXED) while the current swapchain was created @@ -189,6 +195,7 @@ public: VkPresentModeKHR tear_mode() const { return tear_mode_; } bool tear_supported() const { return tear_mode_ != VK_PRESENT_MODE_MAX_ENUM_KHR; } // Whether the last present was queued in the tearing mode, and how many were. + // A present queued behind held work (see submit()) is reported as not tearing. bool last_present_tore() const { return last_tore_; } std::uint64_t tear_presents() const { return tear_presents_; } @@ -272,7 +279,10 @@ public: // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames. - void set_abort(std::function abort) { abort_ = std::move(abort); } + void set_abort(std::function abort) { + std::lock_guard lock(abort_mutex_); + abort_ = std::move(abort); + } // Presents a black frame: the swapchain image cleared, nothing read. PresentX with no planes. VkResult present_blank(bool vsync, bool tear = false) { @@ -283,6 +293,7 @@ public: // read_back(). False when the surface cannot do it or its format is not 8 bits per channel with 4 channels. // Call before the first present. bool enable_capture() { + std::lock_guard lock(present_mutex_); if (!ok_) return false; capture_ = true; stale_ = true; @@ -296,6 +307,7 @@ public: // The last presented frame as the swapchain stores it (4 bytes a texel, rows tightly packed, format() order). // Waits for the frame to finish. False if no captured frame is available or the wait fails. bool read_back(std::vector& pixels, VkExtent2D* extent, VkFormat* format) { + std::lock_guard lock(present_mutex_); if (!capture_ || !capture_ptr_ || !captured_) return false; const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; if (vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX) != VK_SUCCESS) @@ -315,9 +327,15 @@ public: // (its failure is printed there). Held work that is never released holds back the presents after it, as it // holds back the queue's own work; with nothing held this is the plain path. A blank present reads nothing and // is only ordered behind earlier presents. Waiting instead was rejected: the Signal that releases the work may - // be one the application's own thread makes after Present returns. + // be one the application's own thread makes after Present returns. Like a full frame-latency queue, a Present that + // finds max_deferred_presents queued ahead of it does wait, for held work to release (logged once; set_abort ends + // the wait), so the queue behind never-released work is bounded. A queued Present reports its tear as false + // (last_present_tore()): the frame pacer's default sync. + static constexpr std::size_t max_deferred_presents = 8; + VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { + wait_for_room(); std::lock_guard lock(present_mutex_); // `binding` null and `planes` null: clear instead of blit; `planes`: compose them (`binding`, `source`, // `source_rect` unused). Only a present that reads a texture waits for held work. @@ -328,11 +346,39 @@ public: if (source_rect) pending.rect = *source_rect; if (planes) pending.planes = *planes; deferred_.push_back(pending); + last_tore_ = false; context_.holds().after_held(this, [this] { run_deferred(); }); return VK_SUCCESS; } private: + bool should_abort() { + std::function abort; + { + std::lock_guard lock(abort_mutex_); + abort = abort_; + } + return abort && abort(); + } + + // Called without present_mutex_: the thread that releases the queued presents needs it. + void wait_for_room() { + bool logged = false; + for (;;) { + { + std::lock_guard lock(present_mutex_); + if (deferred_.size() < max_deferred_presents) return; + } + if (!logged) { + logged = true; + std::fprintf(stderr, "[rt] d3d12: %zu Presents are queued behind held work; this one waits for it\n", + max_deferred_presents); + } + if (should_abort()) return; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + } + struct PendingPresent { bool has_source; ResourceId source; @@ -777,7 +823,7 @@ private: const VkResult result = vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, VK_NULL_HANDLE, image); if (result != VK_TIMEOUT && result != VK_NOT_READY) return result; - if (abort_ && abort_()) return VK_NOT_READY; + if (should_abort()) return VK_NOT_READY; } } @@ -1057,6 +1103,7 @@ private: ready_ = std::move(ready); format_ = chosen.format; extent_ = extent; + extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height; hdr_active_ = chose_hdr; if (capture_) { // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. @@ -1140,13 +1187,15 @@ private: VkInstance instance_; VkPhysicalDevice physical_; VkQueue queue_; - std::recursive_mutex present_mutex_; // submit() and a deferred present on the releasing thread + mutable std::recursive_mutex present_mutex_; // all presenter state: submit(), a deferred present, the accessors + mutable std::mutex abort_mutex_; // abort_ alone: set_abort() must work while a present waits std::deque deferred_; // presents queued behind held work, in call order VkSurfaceKHR surface_; bool maintenance1_ = false; // VK_KHR/EXT_swapchain_maintenance1 (and the surface extension) are enabled VkPresentModeKHR tear_mode_ = VK_PRESENT_MODE_MAX_ENUM_KHR; // set with the swapchain, see tear_mode() - bool last_tore_ = false; - std::uint64_t tear_presents_ = 0; + std::atomic last_tore_{false}; + std::atomic extent_packed_{0}; // extent_ for readers that must not wait for a present + std::atomic tear_presents_{0}; VkSwapchainKHR swapchain_ = VK_NULL_HANDLE; VkFormat format_ = VK_FORMAT_UNDEFINED; VkExtent2D extent_{}; @@ -1155,15 +1204,15 @@ private: std::array frames_{}; VkCommandPool pool_ = VK_NULL_HANDLE; std::uint64_t frame_index_ = 0; - std::uint64_t presented_ = 0; + std::atomic presented_{0}; bool vsync_ = true; bool stale_ = false; bool ok_ = false; bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists) bool swapchain_hdr_req_ = false; // the swapchain was built for an HDR10 request (it has the format only if hdr_active_) bool hdr_active_ = false; - std::uint64_t composed_ = 0; - bool force_hdr_encoding_ = false; + std::atomic composed_{0}; + std::atomic force_hdr_encoding_{false}; bool warned_hdr_ = false; std::unique_ptr composer_; std::function abort_; diff --git a/runtime/test/d3d12_queue_handover_test.cpp b/runtime/test/d3d12_queue_handover_test.cpp index d3ed188f6..1fabcfb4e 100644 --- a/runtime/test/d3d12_queue_handover_test.cpp +++ b/runtime/test/d3d12_queue_handover_test.cpp @@ -785,11 +785,8 @@ int main(int argc, char** argv) { std::fprintf(stderr, "%u validation errors\n", vk.validation_errors()); return 1; } - if (two_queues || shared_queue) { - deadline = 0; - return 0; - } - + // Every mode ends with the same cases on the host runtime: the expected data is the CPU's pattern in all of + // them, so the host run shows the cases are valid D3D12 and the layer's modes are held to the same bar. std::wstring name; if (auto host = native_device(name)) { arm("host runtime", 300000); diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp index cc1764e21..96d8714a8 100644 --- a/runtime/test/vk_presenter_sync_test.cpp +++ b/runtime/test/vk_presenter_sync_test.cpp @@ -314,15 +314,27 @@ int main() { std::printf("presenter sync: capture-buffer WAW barriers (4/4) and read_back (%d,%d,%d) ok\n", r, g, b); // 2b. A Present behind held work shows what that work draws (queue_holds.h). The render waits for a gate with - // no submitted Signal, so the queue holds it; the Present is queued behind it instead of blitting the back - // buffer as it was. Two presents queue up and keep their order; the blank one in the middle reads nothing. + // no submitted Signal, so the queue holds it; the presents are queued behind it instead of blitting the + // back buffers as they were. Three presents queue up and keep their order: a blit, a blank one (reads + // nothing) and a composed one (present_planes), whose frame is the last one shown, so a reordering + // would end on the black frame. { VulkanFence gate(context, 0); EXPECT(gate.semaphore() != VK_NULL_HANDLE); + const VkImage plane_img = d.image(VK_FORMAT_R8G8B8A8_UNORM, 32, 32, 1, + VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); + EXPECT(plane_img != VK_NULL_HANDLE); + ResourceBinding plane_rb = side_rb; + plane_rb.image = plane_img; + plane_rb.sampled = true; + context.add_resource(2, plane_rb, VK_IMAGE_LAYOUT_UNDEFINED); CommandList red; EXPECT(red.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); EXPECT(red.clear_render_target({1, 0, 0, 1}, {0.9f, 0.1f, 0.2f, 1.0f})); EXPECT(red.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); + EXPECT(red.transition({2, 0, d3d12_state::common, d3d12_state::render_target})); + EXPECT(red.clear_render_target({2, 0, 0, 1}, {0.2f, 0.8f, 0.4f, 1.0f})); + EXPECT(red.transition({2, 0, d3d12_state::render_target, d3d12_state::pixel_shader_resource})); EXPECT(red.close()); const CommandList* ptr = &red; queue.wait(gate.semaphore(), 1); @@ -339,13 +351,49 @@ int main() { cb = bgr ? shot[at + 0] : shot[at + 2]; return true; }; + const std::uint64_t shown = presenter.presented(); + PresentPlanes planes; + planes.count = 1; + planes.plane[0].source = 2; int cr = 0, cg = 0, cb = 0; EXPECT(presenter.present(1, true) == VK_SUCCESS); // queued: returns at once + EXPECT(presenter.present_blank(true) == VK_SUCCESS); // queued behind the one before it + EXPECT(presenter.present_planes(planes, true) == VK_SUCCESS); + EXPECT(presenter.presented() == shown && !presenter.last_present_tore()); EXPECT(center(cr, cg, cb) && std::abs(cr - 51) <= 2 && std::abs(cg - 153) <= 2 && std::abs(cb - 230) <= 2); - EXPECT(gate.signal(1)); // releases the render, then the presents, on this thread + EXPECT(gate.signal(1)); // releases the render, then the presents, in order, on this thread EXPECT(queue.idle()); + EXPECT(presenter.presented() == shown + 3 && presenter.composed_presents() >= 1); + // The composed frame (0.2, 0.8, 0.4 in the plane) is the last one shown; a blank last would be black. + EXPECT(center(cr, cg, cb) && std::abs(cr - 51) <= 12 && std::abs(cg - 204) <= 12 && std::abs(cb - 102) <= 12); + // The blit alone, with nothing held, is the plain path again and shows the red the render drew. + EXPECT(presenter.present(1, true) == VK_SUCCESS); EXPECT(center(cr, cg, cb) && std::abs(cr - 230) <= 2 && std::abs(cg - 26) <= 2 && std::abs(cb - 51) <= 2); - std::printf("presenter sync: Present queued behind held work shows the rendered content (%d,%d,%d)\n", cr, cg, cb); + std::printf("presenter sync: three Presents queued behind held work ran in order (%d,%d,%d)\n", cr, cg, cb); + context.remove_resource(2); + } + + // 2c. A queue destroyed with held work lets the Presents queued behind it run (the work is dropped). + { + VulkanFence never(context, 0); + EXPECT(never.semaphore() != VK_NULL_HANDLE); + CommandList noop; + EXPECT(noop.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); + EXPECT(noop.clear_render_target({1, 0, 0, 1}, {0.0f, 0.0f, 0.0f, 1.0f})); // never replayed + EXPECT(noop.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); + EXPECT(noop.close()); + const CommandList* ptr = &noop; + const std::uint64_t shown = presenter.presented(); + { + VulkanQueue doomed(context, d.queue, d.family); + EXPECT(doomed.ok()); + doomed.wait(never.semaphore(), 1); + EXPECT(doomed.execute({&ptr, 1}) == ReplayResult::success); // held for good + EXPECT(presenter.present(1, true) == VK_SUCCESS); // queued behind it + EXPECT(presenter.presented() == shown); + } + EXPECT(presenter.presented() == shown + 1); + std::printf("presenter sync: Present queued behind a destroyed queue's held work ran\n"); } // 3. Concurrent present() + VulkanQueue::execute() + add/remove_resource() hammering LayoutTracker. diff --git a/runtime/test/vk_queue_query_sync_test.cpp b/runtime/test/vk_queue_query_sync_test.cpp index b7237b911..49f4015c8 100644 --- a/runtime/test/vk_queue_query_sync_test.cpp +++ b/runtime/test/vk_queue_query_sync_test.cpp @@ -331,6 +331,33 @@ int main() { std::printf("queue/query sync: failed held batch reported, its wait kept for the retry, Signal behind it ran\n"); } + // 3c. A Signal whose vkQueueSubmit fails signals nothing: a queue waiting for it stays held (the value is not + // counted as submitted), and the application's retry of the Signal goes through and releases it. + { + VulkanFence fence(context, 0); + EXPECT(fence.semaphore() != VK_NULL_HANDLE); + const std::uint64_t pattern = 0x5ca1ab1e0ddba11ULL; + std::memcpy(src_ptr, &pattern, sizeof(pattern)); + std::memset(dst_ptr, 0, sizeof(pattern)); + CommandList copy_list; + EXPECT(copy_list.copy_buffer({2, 0, 1, 0, sizeof(pattern)})); + EXPECT(copy_list.close()); + const CommandList* ptr = ©_list; + queue_b.wait(fence.semaphore(), 1); + EXPECT(queue_b.execute({&ptr, 1}) == ReplayResult::success); // held for the Signal + driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY); + EXPECT(!queue_a.signal(fence.semaphore(), 1)); // the submit fails + EXPECT(queue_b.idle() && fence.completed() == 0); + std::uint64_t got = 1; + std::memcpy(&got, dst_ptr, sizeof(got)); + EXPECT(got == 0); // the waiter did not run + EXPECT(queue_a.signal(fence.semaphore(), 1)); // the retry signals, and releases it + EXPECT(queue_b.idle() && queue_a.idle() && fence.completed() == 1); + std::memcpy(&got, dst_ptr, sizeof(got)); + EXPECT(got == pattern); + std::printf("queue/query sync: a failed Signal does not release its waiters; the retry does\n"); + } + // 4. Concurrent multi-queue EndQuery + ResolveQueries + temporary query pool add/remove stress. // Each iteration uses a distinct query slot so no slot is reset while another submission resolves it. { -- cgit v1.2.3