upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 23:06:28 -0500
committerItsNotRexed <300290919+ItsNotRexed@users.noreply.github.com>2026-11-22 23:06:28 -0500
commit95b2e2c8bd7d20019231eda0007628fa2f2b5350 (patch)
tree588294b0fe61c6a9d21ada1f56277d000a4d47d6
parent1af1f9e39344ca73bfec9a0e3536fa4254a00b13 (diff)
parent003baa94c1fcba61e324dbeb947e8bd401f4f837 (diff)
Merge pull request #2951 from AlxcBTW
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--docs/d3d12_vulkan.md101
-rw-r--r--runtime/CMakeLists.txt6
-rw-r--r--runtime/shims/d3d12_com.cpp42
-rw-r--r--runtime/src/queue_holds.h122
-rw-r--r--runtime/src/vulkan_backend.h219
-rw-r--r--runtime/src/vulkan_present.h125
-rw-r--r--runtime/test/d3d12_m4_compute_test.cpp19
-rw-r--r--runtime/test/d3d12_queue_handover_test.cpp246
-rw-r--r--runtime/test/vk_presenter_sync_test.cpp83
-rw-r--r--runtime/test/vk_queue_query_sync_test.cpp67
10 files changed, 902 insertions, 128 deletions
diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md
index 21b99a78f..734b882b3 100644
--- a/docs/d3d12_vulkan.md
+++ b/docs/d3d12_vulkan.md
@@ -2312,37 +2312,76 @@ mapped stages/accesses, and if no single layout serves all uses, use `GENERAL` a
2312 (`CommandList` is a value; the application may `Reset` its list at once) and holds the operation. Everything the 2312 (`CommandList` is a value; the application may `Reset` its list at once) and holds the operation. Everything the
2313 queue is asked to do after it (batches, Signals, queue markers) goes behind it, so per-queue order is kept. 2313 queue is asked to do after it (batches, Signals, queue markers) goes behind it, so per-queue order is kept.
2314 The held operations are recorded and submitted, in order, on their own `VkQueue` as soon as the Signals they wait for 2314 The held operations are recorded and submitted, in order, on their own `VkQueue` as soon as the Signals they wait for
2315 have been submitted: by the thread that submits that Signal, after it has released its own queue's lock (or by the 2315 have been submitted: by the thread that submits that Signal (or makes the CPU `Signal`), after it has dropped its own
2316 thread of a CPU `Signal`). There is no worker thread and no caller ever waits for the GPU or for a Signal: the cost 2316 queue's state lock. There is no worker thread and no GPU wait is added, but the call that releases is not free: that
2317 moves to that thread and is what the held `ExecuteCommandLists` would have cost anyway. One thread releases at a time 2317 thread records the held batches (what the `ExecuteCommandLists` would have cost, including whatever `execute` does
2318 (the others leave a note and the running one makes another pass), a release that submits a Signal lets the next 2318 for the lists, such as the bindless upload's wait for the device until D3D-314 removes it) while it still holds the
2319 queue's front run in the same pass, so chains (C waits B, B waits A, in any submission order) and operations with 2319 mutex of the D3D12 queue whose `Signal` or `Wait` it is in, so other calls on that queue wait meanwhile; and
2320 several waits resolve in dependency order, and the layout tracker follows that order. A wait whose value has been 2320 `remove_fence`, queue destruction and presenter destruction wait for a release in progress. One thread releases at a
2321 reached by a submitted Signal never blocks again. The normal case (the Signal submitted first) is unchanged: no copy, 2321 time (the others leave a note and the running one makes another pass); a release that submits a Signal lets the
2322 no hold, the same `vkQueueSubmit`. Holding on the CPU also avoids a Wait and its Signal landing in the wrong order on 2322 next queue's front run in the same pass, so chains (C waits B, B waits A, in any submission order) and operations
2323 one `VkQueue`, which would not make forward progress on the GPU (Vulkan-Docs issue 1262). Edge cases: a queue 2323 with several waits resolve in dependency order, and the layout tracker follows that order. A wait whose value has
2324 destroyed with held operations reports them once (stderr: `queue destroyed with N held operation(s) never 2324 been reached by a submitted Signal never blocks again (vkd3d-proton's rule too). The normal case (the Signal
2325 submitted: waits for a fence value (V) that no Signal reached`) and goes on without waiting; a fence nobody signals 2325 submitted first) is unchanged: no copy, no hold, the same `vkQueueSubmit`. Holding on the CPU also avoids a Wait and
2326 holds back only the queues that wait for it (and those that wait for what they would have signaled), never the 2326 its Signal landing in the wrong order on one `VkQueue`, which would not make forward progress on the GPU
2327 others; a fence released while operations wait for it drops them and says so; a Signal value that is not above 2327 (Vulkan-Docs issue 1262): the test also runs with every D3D12 queue on one `VkQueue` and with two.
2328 the fence's (Vulkan timelines only increase) is still dropped with a note, as before. Failures of a held 2328 What a held operation keeps alive, as D3D12's queue does: the fences it waits on and signals, until its submission
2329 `ExecuteCommandLists` (what the call would have returned) are printed when it is released, not returned from the 2329 has completed on the GPU (a released fence stays until then, which also removes the destroy-while-pending
2330 call. Not covered: sparse `UpdateTileMappings` while a queue holds work still submits at once, and the resources a 2330 validation error the unheld path could hit); the pipeline states and root signatures of its lists (copied from the
2331 held batch names must stay alive until its fence signals (the layer does not pin them; the deferred-destruction 2331 recording before the application may `Reset` it, so releasing a PSO right after `ExecuteCommandLists` is fine).
2332 tickets only know submitted work, D3D-203). Facts from vkd3d-proton (LGPL, approach only, nothing copied): it keeps 2332 Resources are not kept: a resource released while a batch that names it is held fails that batch at release.
2333 a CPU-side virtual value and pending signals per fence and blocks the queue's submission thread until a signal that 2333 Order against other work: a held `Signal(F, v)` released after an unheld `Signal(F, w)` with `w >= v` leaves the
2334 satisfies a wait has been submitted, so Vulkan never sees a wait without a submitted signal; a satisfied wait stays 2334 Vulkan signal out (timelines only increase; waits for `v` already pass), decided under the submit lock so the
2335 satisfied. It also maps virtual fence values to physical timeline values so a D3D12 `Signal` of a lower value works; 2335 order of the checks is the order of the submissions, and the value counts as submitted only once the
2336 the layer does not yet (the value is dropped with a note). Resources are `VK_SHARING_MODE_EXCLUSIVE` and every 2336 `vkQueueSubmit` succeeded (a failed Signal releases nobody and its retry goes through); `Present` is queued behind
2337 D3D12 queue is in the graphics family, so no ownership transfer is needed; with dedicated compute/transfer families 2337 held work too (below). Fence keep-alives are released outside the queue lock, at the next `ExecuteCommandLists`,
2338 they would need `CONCURRENT` (vkd3d-proton does that, because D3D12 gives no information for transfers). 2338 `Signal`, `Wait` or marker once their submission has completed. Edge cases:
2339 Measured: `d3d12_queue_handover_test` runs 358 cases on the layer (371 on the RTX 5070 Laptop, which gives three 2339 a queue destroyed with held operations reports them once (stderr: `queue destroyed with N held operation(s) never
2340 queues per type) and 369 on the host runtime: three-stage chains (produce, relay, consume) over all 27 queue type 2340 submitted: waits for a fence value (V) that no Signal reached`) and goes on without waiting, and the CPU waits on
2341 assignments and all 6 submission orders (consumer first among them), two producers (texture from one queue, buffer 2341 the fences of its held Signals are completed, as a released fence completes them; queues that wait for those fences
2342 from another) with one consumer, a chain released by a CPU `Signal`, a CPU `Signal` before and after the `Wait`, 2342 stay held and are reported when they go; a fence nobody signals holds back only the queues that wait for it (and
2343 a never-signaled fence and a fence released while a batch waits; results compared byte for byte, sync validation 2343 for what they would have signaled), never the others; a Signal value that is not above the fence's is still
2344 clean. With holding disabled the same test fails 236 cases on the layer and validation reports 2344 dropped with a note at call time, as before (vkd3d-proton instead maps virtual fence values to physical timeline
2345 `VUID-vkCmdDraw-None-09600`. 2345 values; the layer does not yet). A held `ExecuteCommandLists` that fails when it is released does not return its
2346 result to a call that has returned: it is printed, `last_execute_result` and `VulkanQueue::take_held_failure`
2347 report it, the `Signal` behind it still signals (the work did not run; nothing waits forever, as for a failure that is
2348 not held), and its waits stay for the queue's next submission, as after a failed `vkQueueSubmit`. A queue does not
2349 hold `UpdateTileMappings` / `CopyTileMappings`: they still submit at once, before earlier held work, and take the
2350 queue's pending waits (documented limit). `VulkanQueue::idle` waits for submitted work only.
2351 `Present` (`VulkanPresenter`): when any queue holds work, a presented back buffer would be blitted as it was before
2352 that work, so the Present is queued instead (`QueueHolds::after_held`), returns success as a held
2353 `ExecuteCommandLists` does, and is submitted, in order with the presents queued before it, by the thread that
2354 releases the last operation held when it was called. It is not blocked on the calling thread because the Signal that
2355 releases the work may be one that thread makes after `Present` returns. Held work that is never released holds back
2356 the presents after it (device-wide, since the layer cannot tell which batch draws into which back buffer). A
2357 blank present reads nothing and is only ordered behind earlier queued presents. At most 8 presents queue up; the
2358 next one waits for held work to release (logged once; `set_abort` ends the wait), as a full frame-latency queue
2359 does. A queued present reports `last_present_tore()` false, which the Xbox PresentX path turns into the default
2360 vblank sync for the frame pacer. The presenter's state is guarded by one mutex (the counters are atomics, so
2361 reading them never waits for a present blocked on a swapchain image); `set_abort` has its own.
2362 Facts from vkd3d-proton (LGPL, approach only, nothing copied): it keeps a CPU-side virtual value and pending signals
2363 per fence and blocks the queue's submission thread until a signal that satisfies a wait has been submitted, so Vulkan
2364 never sees a wait without a submitted signal. Resources are `VK_SHARING_MODE_EXCLUSIVE` and every D3D12 queue is in
2365 the graphics family, so no ownership transfer is needed; with dedicated compute/transfer families they would need
2366 `CONCURRENT` (vkd3d-proton does that, because D3D12 gives no information for transfers).
2367 Every mode of the handover test ends with the same cases on the host runtime (the expected data is the CPU's
2368 pattern in all of them, so that run shows the cases are valid D3D12 and holds the layer's modes to one bar).
2369 The pipeline-state and root-signature pins are covered end to end by `d3d12_m4_compute_test`: the compute list is
2370 executed while held, its two PSOs and root signature are released and the list is Reset, the copy that releases
2371 it is submitted, and the output is compared with the CPU (it reads zeros without the pins).
2372 Measured: `d3d12_queue_handover_test` (three modes: the standalone device with a `VkQueue` per D3D12 queue, then the
2373 host runtime; `--two-queues`, a caller-owned device with two `VkQueue`s handed over; `--shared-queue`, one) runs
2374 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)
2375 over the queue type assignments that fit and all 6 submission orders (consumer first among them), two producers
2376 (texture from one queue, buffer from another) with one consumer, a chain released by a CPU `Signal`, a CPU
2377 `Signal` before and after the `Wait`, a never-signaled fence, a fence released while a batch waits, a held Signal
2378 of a fence the application released, a held Signal below an unheld one on a shared fence, teardown with a held
2379 Signal under a CPU wait, and 200 rounds with two threads signalling and releasing at once; results compared byte
2380 for byte, sync validation clean. With holding disabled the test fails 236 cases and validation reports
2381 `VUID-vkCmdDraw-None-09600`; with the monotonic check disabled it reports
2382 `VUID-VkSubmitInfo-pSignalSemaphores-03242`; `vk_presenter_sync_test` and `d3d12_m4_compute_test` (which
2383 submits the compute list first and releases its PSOs and root signature before the copy that feeds it) fail
2384 without the Present ordering and the pins.
2346- `SetEventOnCompletion(value, hEvent)`: a small wait thread calls `vkWaitSemaphores` and `SetEvent`. Reuse one 2385- `SetEventOnCompletion(value, hEvent)`: a small wait thread calls `vkWaitSemaphores` and `SetEvent`. Reuse one
2347 thread with a condition variable; do not create a thread per fence. 2386 thread with a condition variable; do not create a thread per fence.
2348- `GetCompletedValue` is `vkGetSemaphoreCounterValue`; CPU `Signal` is `vkSignalSemaphore`. 2387- `GetCompletedValue` is `vkGetSemaphoreCounterValue`; CPU `Signal` is `vkSignalSemaphore`.
diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt
index e339e9288..5d3c8e232 100644
--- a/runtime/CMakeLists.txt
+++ b/runtime/CMakeLists.txt
@@ -1195,6 +1195,12 @@ if(TARGET Vulkan::Headers)
1195 add_test(NAME d3d12_queue_handover COMMAND d3d12_queue_handover_test) 1195 add_test(NAME d3d12_queue_handover COMMAND d3d12_queue_handover_test)
1196 set_tests_properties(d3d12_queue_handover PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 400 1196 set_tests_properties(d3d12_queue_handover PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 400
1197 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-") 1197 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
1198 # The same on a caller-owned device: two VkQueues handed to the layer (the D3D12 queues share them), and one
1199 # (every D3D12 queue shares it, where a Wait ahead of its Signal would never progress on the GPU).
1200 add_test(NAME d3d12_queue_handover_two_queues COMMAND d3d12_queue_handover_test --two-queues)
1201 add_test(NAME d3d12_queue_handover_shared_queue COMMAND d3d12_queue_handover_test --shared-queue)
1202 set_tests_properties(d3d12_queue_handover_two_queues d3d12_queue_handover_shared_queue PROPERTIES
1203 SKIP_RETURN_CODE 77 TIMEOUT 400 FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
1198 1204
1199 # XDXR acceleration structures through BuildRaytracingAccelerationStructure (docs/d3d12_vulkan.md 4.8): the 1205 # XDXR acceleration structures through BuildRaytracingAccelerationStructure (docs/d3d12_vulkan.md 4.8): the
1200 # device builds them, tools/xdxr_bvh.py checks them. 1206 # device builds them, tools/xdxr_bvh.py checks them.
diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp
index 77a5bed87..55f1cb65d 100644
--- a/runtime/shims/d3d12_com.cpp
+++ b/runtime/shims/d3d12_com.cpp
@@ -197,6 +197,8 @@ public:
197 } 197 }
198 198
199 const leonida::CommandList& commands() const { return list_; } 199 const leonida::CommandList& commands() const { return list_; }
200 // The pipeline states and root signatures the recording names (it holds a reference to each until Reset).
201 const std::vector<IUnknown*>& pinned() const { return held_; }
200 UINT front_stencil_ref() const { return front_stencil_ref_; } 202 UINT front_stencil_ref() const { return front_stencil_ref_; }
201 UINT back_stencil_ref() const { return back_stencil_ref_; } 203 UINT back_stencil_ref() const { return back_stencil_ref_; }
202 204
@@ -1263,6 +1265,30 @@ public:
1263 // {e1a85d76-0b3f-4c29-a7d4-58f2c6e0b913} 1265 // {e1a85d76-0b3f-4c29-a7d4-58f2c6e0b913}
1264 static constexpr GUID kTag{0xe1a85d76, 0x0b3f, 0x4c29, {0xa7, 0xd4, 0x58, 0xf2, 0xc6, 0xe0, 0xb9, 0x13}}; 1266 static constexpr GUID kTag{0xe1a85d76, 0x0b3f, 0x4c29, {0xa7, 0xd4, 0x58, 0xf2, 0xc6, 0xe0, 0xb9, 0x13}};
1265 1267
1268 // What a held batch (queue_holds.h) keeps alive until it has run: the pipeline states and root signatures its
1269 // lists name, which the application may release and Reset away as soon as ExecuteCommandLists returns. Resources
1270 // are not held (a D3D12 application keeps them until the fence it signals; the docs, section 4.4, list this).
1271 static std::shared_ptr<void> pin_lists(const std::vector<const GraphicsCommandList*>& lists) {
1272 auto objects = std::shared_ptr<std::vector<IUnknown*>>(new std::vector<IUnknown*>, [](auto* held) {
1273 for (IUnknown* object : *held) object->Release();
1274 delete held;
1275 });
1276 for (const GraphicsCommandList* list : lists)
1277 for (IUnknown* object : list->pinned()) {
1278 object->AddRef();
1279 objects->push_back(object);
1280 }
1281 return objects;
1282 }
1283
1284 // A D3D12 queue holds the fences it waits on and signals until the work has been submitted.
1285 static leonida::VulkanQueue::PinFn fence_pin(ID3D12Fence* fence) {
1286 return [fence]() -> std::shared_ptr<void> {
1287 fence->AddRef();
1288 return std::shared_ptr<void>(fence, [](void* held) { static_cast<ID3D12Fence*>(held)->Release(); });
1289 };
1290 }
1291
1266 static leonida::VulkanQueue::QueueKind queue_kind_for(D3D12_COMMAND_LIST_TYPE type) { 1292 static leonida::VulkanQueue::QueueKind queue_kind_for(D3D12_COMMAND_LIST_TYPE type) {
1267 if (type == D3D12_COMMAND_LIST_TYPE_COPY) return leonida::VulkanQueue::QueueKind::copy; 1293 if (type == D3D12_COMMAND_LIST_TYPE_COPY) return leonida::VulkanQueue::QueueKind::copy;
1268 if (type == D3D12_COMMAND_LIST_TYPE_COMPUTE) return leonida::VulkanQueue::QueueKind::compute; 1294 if (type == D3D12_COMMAND_LIST_TYPE_COMPUTE) return leonida::VulkanQueue::QueueKind::compute;
@@ -1283,7 +1309,11 @@ public:
1283 } 1309 }
1284 1310
1285 bool ok() const { return queue_.ok(); } 1311 bool ok() const { return queue_.ok(); }
1286 leonida::ReplayResult last_result() const { return last_result_; } 1312 leonida::ReplayResult last_result() {
1313 // A batch the queue held fails when it is released, after the call returned: the failure is the result.
1314 if (const auto held = queue_.take_held_failure(); held != leonida::ReplayResult::success) last_result_ = held;
1315 return last_result_;
1316 }
1287 1317
1288 D3D12_COMMAND_QUEUE_DESC STDMETHODCALLTYPE GetDesc() override { 1318 D3D12_COMMAND_QUEUE_DESC STDMETHODCALLTYPE GetDesc() override {
1289 d3d12_trace::record("ID3D12CommandQueue::GetDesc"); 1319 d3d12_trace::record("ID3D12CommandQueue::GetDesc");
@@ -1296,6 +1326,7 @@ public:
1296 constexpr auto method = "ID3D12CommandQueue::ExecuteCommandLists"; 1326 constexpr auto method = "ID3D12CommandQueue::ExecuteCommandLists";
1297 std::lock_guard lock(mutex_); 1327 std::lock_guard lock(mutex_);
1298 std::vector<const leonida::CommandList*> recorded; 1328 std::vector<const leonida::CommandList*> recorded;
1329 std::vector<const GraphicsCommandList*> graphics;
1299 for (UINT i = 0; i < count; ++i) { 1330 for (UINT i = 0; i < count; ++i) {
1300 const GraphicsCommandList* list = GraphicsCommandList::from(lists[i]); 1331 const GraphicsCommandList* list = GraphicsCommandList::from(lists[i]);
1301 if (!list || list->type() == D3D12_COMMAND_LIST_TYPE_BUNDLE) { 1332 if (!list || list->type() == D3D12_COMMAND_LIST_TYPE_BUNDLE) {
@@ -1310,8 +1341,9 @@ public:
1310 return; 1341 return;
1311 } 1342 }
1312 recorded.push_back(&list->commands()); 1343 recorded.push_back(&list->commands());
1344 graphics.push_back(list);
1313 } 1345 }
1314 last_result_ = queue_.execute(recorded); 1346 last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); });
1315 d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); 1347 d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed");
1316 if (last_result_ != leonida::ReplayResult::success) 1348 if (last_result_ != leonida::ReplayResult::success)
1317 std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n", 1349 std::fprintf(stderr, "[rt] d3d12: ExecuteCommandLists failed: %s; nothing was submitted\n",
@@ -1369,7 +1401,7 @@ public:
1369 if (!f) return d3d12_trace::result(method, E_INVALIDARG); 1401 if (!f) return d3d12_trace::result(method, E_INVALIDARG);
1370 std::lock_guard lock(mutex_); 1402 std::lock_guard lock(mutex_);
1371 if (!f->claim(value, true)) return d3d12_trace::result(method, S_OK); 1403 if (!f->claim(value, true)) return d3d12_trace::result(method, S_OK);
1372 return d3d12_trace::result(method, queue_.signal(f->semaphore(), value) ? S_OK : E_FAIL); 1404 return d3d12_trace::result(method, queue_.signal(f->semaphore(), value, fence_pin(fence)) ? S_OK : E_FAIL);
1373 } 1405 }
1374 1406
1375 HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence* fence, UINT64 value) override { 1407 HRESULT STDMETHODCALLTYPE Wait(ID3D12Fence* fence, UINT64 value) override {
@@ -1377,7 +1409,7 @@ public:
1377 Fence* f = Fence::from(fence); 1409 Fence* f = Fence::from(fence);
1378 if (!f) return d3d12_trace::result(method, E_INVALIDARG); 1410 if (!f) return d3d12_trace::result(method, E_INVALIDARG);
1379 std::lock_guard lock(mutex_); 1411 std::lock_guard lock(mutex_);
1380 queue_.wait(f->semaphore(), value); 1412 queue_.wait(f->semaphore(), value, fence_pin(fence));
1381 return d3d12_trace::result(method, S_OK); 1413 return d3d12_trace::result(method, S_OK);
1382 } 1414 }
1383 1415
@@ -1713,7 +1745,7 @@ bool command_signature_info(ID3D12CommandSignature* signature, leonida::Indirect
1713 1745
1714leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue) { 1746leonida::ReplayResult last_execute_result(ID3D12CommandQueue* queue) {
1715 if (ID3D12CommandQueue* real = d3d12_xs::queue_proxy_real_queue(queue)) queue = real; // the Xbox-ABI proxy 1747 if (ID3D12CommandQueue* real = d3d12_xs::queue_proxy_real_queue(queue)) queue = real; // the Xbox-ABI proxy
1716 const CommandQueue* q = CommandQueue::from(queue); 1748 CommandQueue* q = CommandQueue::from(queue);
1717 return q ? q->last_result() : leonida::ReplayResult::unsupported; 1749 return q ? q->last_result() : leonida::ReplayResult::unsupported;
1718} 1750}
1719 1751
diff --git a/runtime/src/queue_holds.h b/runtime/src/queue_holds.h
index eafe3ebc8..2839d4210 100644
--- a/runtime/src/queue_holds.h
+++ b/runtime/src/queue_holds.h
@@ -2,14 +2,15 @@
2 2
3#include <atomic> 3#include <atomic>
4#include <cstdint> 4#include <cstdint>
5#include <cstdio> 5#include <deque>
6#include <functional>
6#include <mutex> 7#include <mutex>
7#include <unordered_map> 8#include <unordered_map>
8#include <vector> 9#include <vector>
9 10
10namespace leonida { 11namespace leonida {
11 12
12// Cross-queue Wait-before-Signal (docs section 4.4, "Wait before Signal"). 13// Cross-queue Wait-before-Signal (docs section 4.4, "Wait before Signal across queues").
13// 14//
14// A queue replays its ExecuteCommandLists against one device-wide layout tracker, in the order the calls reach the 15// A queue replays its ExecuteCommandLists against one device-wide layout tracker, in the order the calls reach the
15// layer. When queue B calls Wait(fence, v) and the Signal(fence, v) on queue A is only submitted afterwards, B's 16// layer. When queue B calls Wait(fence, v) and the Signal(fence, v) on queue A is only submitted afterwards, B's
@@ -19,23 +20,30 @@ namespace leonida {
19// own timeline semaphores still order the GPU work. 20// own timeline semaphores still order the GPU work.
20// 21//
21// This class is the device-wide half: for every fence, the highest value a Signal has been submitted for (or the 22// This class is the device-wide half: for every fence, the highest value a Signal has been submitted for (or the
22// CPU has set it to), which is not the completed value; and the held queues, which it asks to release whatever 23// CPU has set it to), which is not the completed value; the held queues, which it asks to release whatever became
23// became ready. It owns no Vulkan objects. Semaphores it was never told about count as satisfied, so a queue used 24// ready; and "after held work" callbacks (the presenter), which run once every operation held when they were
24// with a plain VkSemaphore behaves as before. 25// registered has been released. It owns no Vulkan objects. Semaphores it was never told about count as satisfied,
26// so a queue used with a plain VkSemaphore behaves as before.
25// 27//
26// Threads. Nothing here blocks on the GPU. The thread that makes a wait satisfiable (a queue's Signal, a CPU 28// Threads. No GPU wait happens here, but the thread that makes a wait satisfiable (a queue's Signal, a CPU Signal)
27// Signal) releases the ready batches itself, after it has released its own queue's lock: recording a held batch 29// does the release itself, after it has dropped its own queue's state lock: it records and submits the held
28// costs what its own ExecuteCommandLists would have. Only one thread releases at a time; a thread that finds 30// batches (a held ExecuteCommandLists costs what it would have cost when called, which includes whatever
29// another one releasing leaves a note and that one takes another pass, so no caller waits for another's recording. 31// execute_now does: the bindless upload's wait for the device is one) and runs the callbacks. The COM wrapper
32// still holds the mutex of the queue whose call that thread is in, so that queue's other calls wait meanwhile.
33// One thread releases at a time; a thread that finds another one releasing leaves a note and that one takes
34// another pass. detach() and cancel_after() (and remove_fence() from outside a release) wait for a running
35// release.
30template<class Semaphore> 36template<class Semaphore>
31class QueueHolds { 37class QueueHolds {
32public: 38public:
33 // A queue that can hold batches. Both calls take the queue's own lock; neither is called with it held. 39 // A queue that can hold batches. The calls take the queue's own lock; none is made with it held.
34 struct Holder { 40 struct Holder {
35 // Releases the held operations at the front of the queue whose waits are satisfied. True if any was. 41 // Releases the held operations at the front of the queue whose waits are satisfied. True if any was.
36 virtual bool release_ready() = 0; 42 virtual bool release_ready() = 0;
37 // Drops the held operations that wait on `semaphore` (its fence is gone), reporting each. 43 // Drops the held operations that wait on `semaphore` (its fence is gone), reporting each.
38 virtual void discard_waiting_on(Semaphore semaphore) = 0; 44 virtual void discard_waiting_on(Semaphore semaphore) = 0;
45 // Sequence number (next_seq()) of the oldest held operation, 0 when nothing is held.
46 virtual std::uint64_t oldest_held_seq() = 0;
39 47
40 protected: 48 protected:
41 ~Holder() = default; 49 ~Holder() = default;
@@ -46,16 +54,21 @@ public:
46 fences_[semaphore] = initial; 54 fences_[semaphore] = initial;
47 } 55 }
48 56
49 // The fence is released: held batches waiting on it can never run, so they are dropped and reported. 57 // The fence is gone. Operations that still reference it are dropped and reported (the COM layer keeps a fence
58 // alive while a held operation names it, so this is a safety net for direct users of VulkanFence). Not done
59 // from inside a release: the releasing thread already holds the lock, and what it is releasing cannot
60 // reference a fence whose last reference it is dropping, since that reference is the one it holds.
50 void remove_fence(Semaphore semaphore) { 61 void remove_fence(Semaphore semaphore) {
51 { 62 {
52 std::lock_guard lock(mutex_); 63 std::lock_guard lock(mutex_);
53 fences_.erase(semaphore); 64 fences_.erase(semaphore);
54 } 65 }
55 if (held_.load(std::memory_order_acquire) == 0) return; 66 if (held_.load(std::memory_order_acquire) == 0 || in_pump()) return;
56 { 67 {
57 std::lock_guard pump(pump_mutex_); 68 std::lock_guard pump(pump_mutex_);
69 in_pump() = true; // what is dropped may release other fences: they must not wait for this lock
58 for (Holder* holder : snapshot()) holder->discard_waiting_on(semaphore); 70 for (Holder* holder : snapshot()) holder->discard_waiting_on(semaphore);
71 in_pump() = false;
59 } 72 }
60 pump_ready(); 73 pump_ready();
61 } 74 }
@@ -68,6 +81,18 @@ public:
68 if (it != fences_.end() && it->second < value) it->second = value; 81 if (it != fences_.end() && it->second < value) it->second = value;
69 } 82 }
70 83
84 // A queue is about to submit a Signal of `value`; call inside the device submit lock, and record the value with
85 // signaled() only once the vkQueueSubmit succeeded (a failed submit signals nothing: waiters must stay held and a
86 // retry must go through). False when a Signal of at least `value` was already submitted: the timeline cannot go
87 // down or stay (VUID-VkSubmitInfo-pSignalSemaphores-03242 and the timeline rules), and a wait for `value` is
88 // already satisfied, so the Vulkan signal is left out. This happens when a held Signal(F, 2) is released after an
89 // unheld Signal(F, 3). Unknown semaphores are always signaled.
90 bool would_signal(Semaphore semaphore, std::uint64_t value) const {
91 std::lock_guard lock(mutex_);
92 const auto it = fences_.find(semaphore);
93 return it == fences_.end() || it->second < value;
94 }
95
71 // true when no submitted Signal reaches `value` yet. Unknown semaphores are satisfied. 96 // true when no submitted Signal reaches `value` yet. Unknown semaphores are satisfied.
72 bool pending(Semaphore semaphore, std::uint64_t value) const { 97 bool pending(Semaphore semaphore, std::uint64_t value) const {
73 std::lock_guard lock(mutex_); 98 std::lock_guard lock(mutex_);
@@ -94,14 +119,47 @@ public:
94 pump_ready(); 119 pump_ready();
95 } 120 }
96 121
122 // Sequence numbers of held operations, in the order they were held (across queues).
123 std::uint64_t next_seq() { return seq_.fetch_add(1, std::memory_order_acq_rel) + 1; }
124 std::uint64_t current_seq() const { return seq_.load(std::memory_order_acquire); }
125
126 // Runs `fn` once every operation held up to now has been released (or dropped), on the thread that releases the
127 // last of them, or right here if none is held. Callbacks of one owner run in registration order. Used by the
128 // presenter: a Present queued behind held work shows what that work draws.
129 void after_held(const void* owner, std::function<void()> fn) {
130 {
131 std::lock_guard lock(mutex_);
132 barriers_.push_back({owner, current_seq(), std::move(fn)});
133 barrier_count_.fetch_add(1, std::memory_order_acq_rel);
134 }
135 pump_ready();
136 }
137
138 // Drops the callbacks of `owner` that have not run, and waits for one that is running.
139 void cancel_after(const void* owner) {
140 {
141 std::lock_guard pump(pump_mutex_);
142 std::lock_guard lock(mutex_);
143 for (auto it = barriers_.begin(); it != barriers_.end();)
144 if (it->owner == owner) {
145 it = barriers_.erase(it);
146 barrier_count_.fetch_sub(1, std::memory_order_acq_rel);
147 } else {
148 ++it;
149 }
150 }
151 pump_ready();
152 }
153
97 // Held operations over all queues, for the cheap "is there anything to do" test. 154 // Held operations over all queues, for the cheap "is there anything to do" test.
98 void held_changed(std::int64_t delta) { held_.fetch_add(delta, std::memory_order_acq_rel); } 155 void held_changed(std::int64_t delta) { held_.fetch_add(delta, std::memory_order_acq_rel); }
99 bool any_held() const { return held_.load(std::memory_order_acquire) > 0; } 156 bool any_held() const { return held_.load(std::memory_order_acquire) > 0; }
100 157
101 // Releases every held operation that has become ready, in dependency order: a release can submit a Signal 158 // Releases every held operation that has become ready, in dependency order: a release can submit a Signal
102 // that makes another queue's front ready, so passes repeat until one finds nothing new. 159 // that makes another queue's front ready, so passes repeat until one finds nothing new. Then the callbacks
160 // whose held work is all gone.
103 void pump_ready() { 161 void pump_ready() {
104 if (!any_held()) return; 162 if (!any_held() && barrier_count_.load(std::memory_order_acquire) == 0) return;
105 dirty_.store(true, std::memory_order_release); 163 dirty_.store(true, std::memory_order_release);
106 if (in_pump()) return; // a release on this thread submitted a Signal: the running pass will go again 164 if (in_pump()) return; // a release on this thread submitted a Signal: the running pass will go again
107 for (;;) { 165 for (;;) {
@@ -114,6 +172,7 @@ public:
114 progress = false; 172 progress = false;
115 for (Holder* holder : snapshot()) progress |= holder->release_ready(); 173 for (Holder* holder : snapshot()) progress |= holder->release_ready();
116 } 174 }
175 run_barriers();
117 } 176 }
118 in_pump() = false; 177 in_pump() = false;
119 pump.unlock(); 178 pump.unlock();
@@ -122,6 +181,12 @@ public:
122 } 181 }
123 182
124private: 183private:
184 struct Barrier {
185 const void* owner;
186 std::uint64_t seq;
187 std::function<void()> fn;
188 };
189
125 static bool& in_pump() { 190 static bool& in_pump() {
126 static thread_local bool pumping = false; 191 static thread_local bool pumping = false;
127 return pumping; 192 return pumping;
@@ -132,11 +197,38 @@ private:
132 return holders_; 197 return holders_;
133 } 198 }
134 199
135 mutable std::mutex mutex_; // leaf: fences_ and holders_ 200 // Called with pump_mutex_ held. A callback runs when no held operation is older than the moment it was asked.
201 void run_barriers() {
202 for (;;) {
203 Barrier front;
204 {
205 std::lock_guard lock(mutex_);
206 if (barriers_.empty()) return;
207 front = barriers_.front();
208 }
209 for (Holder* holder : snapshot()) {
210 const std::uint64_t oldest = holder->oldest_held_seq();
211 if (oldest && oldest <= front.seq) return;
212 }
213 {
214 std::lock_guard lock(mutex_);
215 if (barriers_.empty() || barriers_.front().seq != front.seq || barriers_.front().owner != front.owner)
216 continue; // cancelled meanwhile
217 barriers_.pop_front();
218 barrier_count_.fetch_sub(1, std::memory_order_acq_rel);
219 }
220 front.fn();
221 }
222 }
223
224 mutable std::mutex mutex_; // leaf: fences_, holders_ and barriers_
136 std::mutex pump_mutex_; // one releasing thread; held across release_ready(), so detach() waits for it 225 std::mutex pump_mutex_; // one releasing thread; held across release_ready(), so detach() waits for it
137 std::unordered_map<Semaphore, std::uint64_t> fences_; 226 std::unordered_map<Semaphore, std::uint64_t> fences_;
138 std::vector<Holder*> holders_; 227 std::vector<Holder*> holders_;
228 std::deque<Barrier> barriers_;
139 std::atomic<std::int64_t> held_{0}; 229 std::atomic<std::int64_t> held_{0};
230 std::atomic<std::int64_t> barrier_count_{0};
231 std::atomic<std::uint64_t> seq_{0};
140 std::atomic<bool> dirty_{false}; 232 std::atomic<bool> dirty_{false};
141}; 233};
142 234
diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h
index 65d76532a..99add4faf 100644
--- a/runtime/src/vulkan_backend.h
+++ b/runtime/src/vulkan_backend.h
@@ -1572,6 +1572,7 @@ public:
1572 auto& vk = context_.vk; 1572 auto& vk = context_.vk;
1573 context_.holds().detach(this); // no thread releases into this queue from here on 1573 context_.holds().detach(this); // no thread releases into this queue from here on
1574 report_held_at_teardown(); 1574 report_held_at_teardown();
1575 context_.holds().pump_ready(); // presents queued behind what was just dropped can run
1575 if (queue_) { 1576 if (queue_) {
1576 std::lock_guard lock(context_.submit_mutex()); 1577 std::lock_guard lock(context_.submit_mutex());
1577 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_); 1578 for (; open_labels_; --open_labels_) context_.labels_.queue_end(queue_);
@@ -1678,10 +1679,17 @@ public:
1678 // the layout tracker as it was. Pending Wait()s are attached to this submission. When one of them (or an 1679 // the layout tracker as it was. Pending Wait()s are attached to this submission. When one of them (or an
1679 // earlier held operation) waits for a fence value no Signal has been submitted for, the lists are copied and 1680 // earlier held operation) waits for a fence value no Signal has been submitted for, the lists are copied and
1680 // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU 1681 // held instead, and the call succeeds: the batch is replayed by the thread that submits the Signal (or the CPU
1681 // Signal), which is also where its errors are reported. 1682 // Signal), which is also where its errors are reported (stderr, and take_held_failure()).
1682 ReplayResult execute(std::span<const CommandList* const> lists) { 1683 //
1684 // `pin`, called only when the batch is held, returns what has to stay alive until the batch has run: the COM layer
1685 // passes the pipeline states and root signatures the lists named (the application may release them and Reset
1686 // the lists as soon as the call returns).
1687 using PinFn = std::function<std::shared_ptr<void>()>;
1688
1689 ReplayResult execute(std::span<const CommandList* const> lists, const PinFn& pin = {}) {
1683 ReplayResult result = ReplayResult::success; 1690 ReplayResult result = ReplayResult::success;
1684 bool held = false; 1691 bool held = false;
1692 std::vector<std::shared_ptr<void>> retired; // destroyed after state_mutex_ is released
1685 { 1693 {
1686 std::lock_guard state(state_mutex_); 1694 std::lock_guard state(state_mutex_);
1687 if (!must_hold()) { 1695 if (!must_hold()) {
@@ -1693,18 +1701,23 @@ public:
1693 op.kind = Deferred::Kind::batch; 1701 op.kind = Deferred::Kind::batch;
1694 op.lists.reserve(lists.size()); 1702 op.lists.reserve(lists.size());
1695 for (const CommandList* list : lists) op.lists.push_back(*list); 1703 for (const CommandList* list : lists) op.lists.push_back(*list);
1704 if (pin) op.pins.push_back(pin());
1696 hold(std::move(op)); 1705 hold(std::move(op));
1697 held = true; 1706 held = true;
1698 } 1707 }
1708 drain_pins(retired);
1699 } 1709 }
1710 retired.clear();
1700 if (held) context_.holds().pump_ready(); // a Signal may have been submitted since the check 1711 if (held) context_.holds().pump_ready(); // a Signal may have been submitted since the check
1701 return result; 1712 return result;
1702 } 1713 }
1703 1714
1704 // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. Held behind earlier 1715 // ID3D12CommandQueue::Signal: the fence reaches `value` after all work submitted so far. Held behind earlier
1705 // held operations, so the fence does not run ahead of the work it follows. 1716 // held operations, so the fence does not run ahead of the work it follows. `pin` (called only when the Signal is
1706 bool signal(VkSemaphore fence, std::uint64_t value) { 1717 // held) keeps the fence object alive until it has been submitted, as D3D12 does.
1718 bool signal(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) {
1707 bool ok = true; 1719 bool ok = true;
1720 std::vector<std::shared_ptr<void>> retired;
1708 { 1721 {
1709 std::lock_guard state(state_mutex_); 1722 std::lock_guard state(state_mutex_);
1710 if (must_hold()) { 1723 if (must_hold()) {
@@ -1712,27 +1725,45 @@ public:
1712 op.kind = Deferred::Kind::signal; 1725 op.kind = Deferred::Kind::signal;
1713 op.fence = fence; 1726 op.fence = fence;
1714 op.value = value; 1727 op.value = value;
1728 if (pin) op.pins.push_back(pin());
1715 hold(std::move(op)); 1729 hold(std::move(op));
1716 } else { 1730 } else {
1717 ok = submit(VK_NULL_HANDLE, fence, value); 1731 ok = submit(VK_NULL_HANDLE, fence, value);
1718 } 1732 }
1733 drain_pins(retired);
1719 } 1734 }
1735 retired.clear();
1720 context_.holds().pump_ready(); // this Signal, or the hold above, may have made a held batch ready 1736 context_.holds().pump_ready(); // this Signal, or the hold above, may have made a held batch ready
1721 return ok; 1737 return ok;
1722 } 1738 }
1723 1739
1724 // ID3D12CommandQueue::Wait: later submissions wait for the fence. A wait in a Vulkan batch only holds back that 1740 // ID3D12CommandQueue::Wait: later submissions wait for the fence. A wait in a Vulkan batch only holds back that
1725 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet). 1741 // batch, so it is kept and attached to the next submission (held on the CPU if no Signal reaches it yet).
1726 void wait(VkSemaphore fence, std::uint64_t value) { 1742 // `pin` returns what keeps the fence object alive until then (a D3D12 queue holds its fences).
1727 std::lock_guard state(state_mutex_); 1743 void wait(VkSemaphore fence, std::uint64_t value, const PinFn& pin = {}) {
1728 waits_.push_back(fence); 1744 std::vector<std::shared_ptr<void>> retired; // fences whose submission has completed: released unlocked
1729 wait_values_.push_back(value); 1745 {
1746 std::lock_guard state(state_mutex_);
1747 waits_.push_back(fence);
1748 wait_values_.push_back(value);
1749 if (pin) wait_pins_.push_back(pin());
1750 drain_pins(retired);
1751 }
1752 }
1753
1754 // The first failure of a held ExecuteCommandLists since the last call (what the call would have returned had it
1755 // not been held), or success. A Signal behind a failed batch still signals, as when the failure is not held: the
1756 // work did not run, the application is told here and on stderr, and nothing waits forever.
1757 ReplayResult take_held_failure() {
1758 return static_cast<ReplayResult>(held_failure_.exchange(static_cast<int>(ReplayResult::success)));
1730 } 1759 }
1731 1760
1732 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end 1761 // ID3D12CommandQueue::SetMarker/BeginEvent/EndEvent: queue labels, between the submissions around them. An end
1733 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension. 1762 // with no begin open on this queue is dropped, as Vulkan requires a matching begin. No-ops without the extension.
1734 void marker(DebugMarker::Kind kind, const char* label) { 1763 void marker(DebugMarker::Kind kind, const char* label) {
1764 std::vector<std::shared_ptr<void>> retired;
1735 std::lock_guard state(state_mutex_); 1765 std::lock_guard state(state_mutex_);
1766 drain_pins(retired); // destroyed after the lock (reverse declaration order)
1736 if (!held_.empty()) { // behind the held work, so behind it in the queue's labels too 1767 if (!held_.empty()) { // behind the held work, so behind it in the queue's labels too
1737 Deferred op; 1768 Deferred op;
1738 op.kind = Deferred::Kind::marker; 1769 op.kind = Deferred::Kind::marker;
@@ -2156,6 +2187,7 @@ private:
2156 struct Deferred { 2187 struct Deferred {
2157 enum class Kind : std::uint8_t { batch, signal, marker }; 2188 enum class Kind : std::uint8_t { batch, signal, marker };
2158 Kind kind = Kind::batch; 2189 Kind kind = Kind::batch;
2190 std::uint64_t seq = 0; // QueueHolds::next_seq(): the order operations were held in, across queues
2159 std::vector<VkSemaphore> waits; 2191 std::vector<VkSemaphore> waits;
2160 std::vector<std::uint64_t> wait_values; 2192 std::vector<std::uint64_t> wait_values;
2161 std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call 2193 std::vector<CommandList> lists; // batch: copies, so the application may Reset its lists after the call
@@ -2163,6 +2195,10 @@ private:
2163 std::uint64_t value = 0; 2195 std::uint64_t value = 0;
2164 DebugMarker::Kind marker_kind = DebugMarker::Kind::set; // marker 2196 DebugMarker::Kind marker_kind = DebugMarker::Kind::set; // marker
2165 std::string label; 2197 std::string label;
2198 // Alive until the operation has run: the fences it waits on and signals, the pipeline states and root
2199 // signatures of the lists (the application may release them right after the call).
2200 std::vector<std::shared_ptr<void>> pins;
2201 std::vector<std::shared_ptr<void>> wait_pins; // the fences of `waits`
2166 }; 2202 };
2167 2203
2168 bool waits_pending(const std::vector<VkSemaphore>& semaphores, const std::vector<std::uint64_t>& values) const { 2204 bool waits_pending(const std::vector<VkSemaphore>& semaphores, const std::vector<std::uint64_t>& values) const {
@@ -2175,32 +2211,75 @@ private:
2175 // has no submitted Signal yet. Called with state_mutex_ held. 2211 // has no submitted Signal yet. Called with state_mutex_ held.
2176 bool must_hold() const { return !held_.empty() || waits_pending(waits_, wait_values_); } 2212 bool must_hold() const { return !held_.empty() || waits_pending(waits_, wait_values_); }
2177 2213
2214 // The waits are consumed: submitted as `ticket` (0: dropped on device loss). What the application may release
2215 // (the fences they named) is kept until that submission has completed on the GPU, as a D3D12 queue does:
2216 // destroying a semaphore a pending submission uses is a validation error. Retired pins are destroyed by the
2217 // caller after state_mutex_ is released (drain_pins): the last release of a fence waits for a running release,
2218 // which must not be waiting for this lock.
2219 void clear_waits(std::uint64_t ticket = 0) {
2220 waits_.clear();
2221 wait_values_.clear();
2222 retire_pins(wait_pins_, ticket);
2223 }
2224
2225 void retire_pins(std::vector<std::shared_ptr<void>>& pins, std::uint64_t ticket) {
2226 for (auto& pin : pins) {
2227 if (ticket) pin_queue_.push_back({ticket, std::move(pin)});
2228 else retired_pins_.push_back(std::move(pin));
2229 }
2230 pins.clear();
2231 }
2232
2233 // Moves the pins whose submission has completed (and the ones retired outright) to `out`. state_mutex_ held.
2234 void drain_pins(std::vector<std::shared_ptr<void>>& out) {
2235 out.swap(retired_pins_);
2236 if (pin_queue_.empty()) return;
2237 const std::uint64_t done = completed();
2238 while (!pin_queue_.empty() && pin_queue_.front().ticket <= done) {
2239 out.push_back(std::move(pin_queue_.front().pin));
2240 pin_queue_.pop_front();
2241 }
2242 }
2243
2178 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held. 2244 // Appends `op`, which takes the pending waits with it (a marker has none). Called with state_mutex_ held.
2179 void hold(Deferred&& op) { 2245 void hold(Deferred&& op) {
2246 op.seq = context_.holds().next_seq();
2180 if (op.kind != Deferred::Kind::marker) { 2247 if (op.kind != Deferred::Kind::marker) {
2181 op.waits = std::move(waits_); 2248 op.waits = std::move(waits_);
2182 op.wait_values = std::move(wait_values_); 2249 op.wait_values = std::move(wait_values_);
2250 op.wait_pins = std::move(wait_pins_);
2183 waits_.clear(); 2251 waits_.clear();
2184 wait_values_.clear(); 2252 wait_values_.clear();
2253 wait_pins_.clear();
2185 } 2254 }
2186 held_.push_back(std::move(op)); 2255 held_.push_back(std::move(op));
2187 context_.holds().held_changed(1); 2256 context_.holds().held_changed(1);
2188 } 2257 }
2189 2258
2190 // Runs one held operation as the call would have, with its own waits and none of the ones queued since. 2259 // Runs one held operation as the call would have, with its own waits and none of the ones queued since.
2260 // A submission that fails leaves its waits for the next one, as when the call is not held (a transient
2261 // vkQueueSubmit failure is retried by the application's next call), ahead of the waits asked for since.
2191 void run(Deferred& op) { 2262 void run(Deferred& op) {
2192 auto later_waits = std::move(waits_); 2263 auto later_waits = std::move(waits_);
2193 auto later_values = std::move(wait_values_); 2264 auto later_values = std::move(wait_values_);
2265 auto later_pins = std::move(wait_pins_);
2194 waits_ = std::move(op.waits); 2266 waits_ = std::move(op.waits);
2195 wait_values_ = std::move(op.wait_values); 2267 wait_values_ = std::move(op.wait_values);
2268 wait_pins_ = std::move(op.wait_pins); // the fences stay alive until the submission has consumed their waits
2196 switch (op.kind) { 2269 switch (op.kind) {
2197 case Deferred::Kind::batch: { 2270 case Deferred::Kind::batch: {
2198 std::vector<const CommandList*> lists; 2271 std::vector<const CommandList*> lists;
2199 for (const CommandList& list : op.lists) lists.push_back(&list); 2272 for (const CommandList& list : op.lists) lists.push_back(&list);
2273 // The pipeline states and root signatures of the lists are in op.pins (see execute()): they live until
2274 // the batch has been recorded and then, with the fences, until its submission has completed (below).
2200 const ReplayResult result = execute_now(lists); 2275 const ReplayResult result = execute_now(lists);
2201 if (result != ReplayResult::success) 2276 if (result != ReplayResult::success) {
2277 int none = static_cast<int>(ReplayResult::success);
2278 held_failure_.compare_exchange_strong(none, static_cast<int>(result));
2202 std::fprintf(stderr, "[rt] d3d12: a held ExecuteCommandLists failed when it was released (result %d); " 2279 std::fprintf(stderr, "[rt] d3d12: a held ExecuteCommandLists failed when it was released (result %d); "
2203 "nothing was submitted\n", static_cast<int>(result)); 2280 "nothing was submitted for it, and a Signal behind it still signals\n",
2281 static_cast<int>(result));
2282 }
2204 break; 2283 break;
2205 } 2284 }
2206 case Deferred::Kind::signal: 2285 case Deferred::Kind::signal:
@@ -2211,55 +2290,83 @@ private:
2211 marker_now(op.marker_kind, op.label.c_str()); 2290 marker_now(op.marker_kind, op.label.c_str());
2212 break; 2291 break;
2213 } 2292 }
2214 waits_ = std::move(later_waits); // a failed submission leaves its waits behind: drop them with the batch 2293 retire_pins(op.pins, submitted_); // the fence it signals, the pipeline states: until its submission is done
2215 wait_values_ = std::move(later_values); 2294 waits_.insert(waits_.end(), later_waits.begin(), later_waits.end());
2295 wait_values_.insert(wait_values_.end(), later_values.begin(), later_values.end());
2296 for (auto& pin : later_pins) wait_pins_.push_back(std::move(pin));
2216 } 2297 }
2217 2298
2218 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); } 2299 bool ready(const Deferred& op) const { return !waits_pending(op.waits, op.wait_values); }
2219 2300
2220 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held). 2301 // Holder: called by the thread whose Signal made a held operation ready (never with a queue lock held).
2221 bool release_ready() override { 2302 bool release_ready() override {
2222 std::lock_guard state(state_mutex_); 2303 std::vector<std::shared_ptr<void>> retired;
2223 bool released = false; 2304 bool released = false;
2224 while (!held_.empty() && (context_.is_device_lost() || ready(held_.front()))) { 2305 {
2225 Deferred op = std::move(held_.front()); 2306 std::lock_guard state(state_mutex_);
2226 held_.pop_front(); 2307 while (!held_.empty() && (context_.is_device_lost() || ready(held_.front()))) {
2227 context_.holds().held_changed(-1); 2308 Deferred op = std::move(held_.front());
2228 if (!context_.is_device_lost()) run(op); 2309 held_.pop_front();
2229 released = true; 2310 context_.holds().held_changed(-1);
2311 if (!context_.is_device_lost()) run(op);
2312 released = true;
2313 }
2314 drain_pins(retired);
2230 } 2315 }
2231 return released; 2316 return released;
2232 } 2317 }
2233 2318
2234 // Holder: the fence is released, so what waits on it can never run. 2319 // Holder: the fence is released, so what waits on it can never run.
2235 void discard_waiting_on(VkSemaphore semaphore) override { 2320 void discard_waiting_on(VkSemaphore semaphore) override {
2236 std::lock_guard state(state_mutex_); 2321 std::vector<Deferred> dropped;
2237 for (auto it = held_.begin(); it != held_.end();) { 2322 {
2238 if (std::find(it->waits.begin(), it->waits.end(), semaphore) == it->waits.end()) { 2323 std::lock_guard state(state_mutex_);
2239 ++it; 2324 for (auto it = held_.begin(); it != held_.end();) {
2240 continue; 2325 if (std::find(it->waits.begin(), it->waits.end(), semaphore) == it->waits.end() &&
2326 !(it->kind == Deferred::Kind::signal && it->fence == semaphore)) {
2327 ++it;
2328 continue;
2329 }
2330 std::fprintf(stderr, "[rt] d3d12: a fence was released while a queue still held work that names it; "
2331 "that work is dropped\n");
2332 dropped.push_back(std::move(*it));
2333 it = held_.erase(it);
2334 context_.holds().held_changed(-1);
2241 } 2335 }
2242 std::fprintf(stderr, "[rt] d3d12: a fence was released while a queue still held work waiting on it; "
2243 "that work is dropped\n");
2244 it = held_.erase(it);
2245 context_.holds().held_changed(-1);
2246 } 2336 }
2247 } 2337 }
2248 2338
2249 // A queue destroyed with held work: the fence it waits on was never signaled. Reported, not waited for; nothing 2339 // Holder: the sequence number of the oldest held operation.
2250 // was submitted for it, so the VkQueue is idle and the destructor goes on. 2340 std::uint64_t oldest_held_seq() override {
2251 void report_held_at_teardown() {
2252 std::lock_guard state(state_mutex_); 2341 std::lock_guard state(state_mutex_);
2253 if (held_.empty()) return; 2342 return held_.empty() ? 0 : held_.front().seq;
2254 std::uint64_t value = 0; 2343 }
2255 for (const Deferred& op : held_) 2344
2256 for (std::size_t i = 0; i < op.waits.size() && !value; ++i) 2345 // A queue destroyed with held work. Reported, not waited for: nothing was submitted for it, so the VkQueue is
2257 if (context_.holds().pending(op.waits[i], op.wait_values[i])) value = op.wait_values[i]; 2346 // idle and the destructor goes on. The fences of held Signals will never reach their values, so what is waiting
2258 std::fprintf(stderr, "[rt] d3d12: queue destroyed with %zu held operation(s) never submitted: waits for a " 2347 // for them on the CPU (SetEventOnCompletion, as a released fence completes them) is woken, and the batches
2259 "fence value (%llu) that no Signal reached; the fence was never signaled\n", 2348 // that wait for them on other queues stay held (and are reported when those queues are destroyed).
2260 held_.size(), static_cast<unsigned long long>(value)); 2349 void report_held_at_teardown() {
2261 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size())); 2350 std::deque<Deferred> dropped;
2262 held_.clear(); 2351 {
2352 std::lock_guard state(state_mutex_);
2353 if (held_.empty()) return;
2354 std::uint64_t value = 0;
2355 for (const Deferred& op : held_)
2356 for (std::size_t i = 0; i < op.waits.size() && !value; ++i)
2357 if (context_.holds().pending(op.waits[i], op.wait_values[i])) value = op.wait_values[i];
2358 std::size_t signals = 0;
2359 for (const Deferred& op : held_) signals += op.kind == Deferred::Kind::signal;
2360 std::fprintf(stderr, "[rt] d3d12: queue destroyed with %zu held operation(s) never submitted: waits for a "
2361 "fence value (%llu) that no Signal reached; the fence was never signaled%s\n",
2362 held_.size(), static_cast<unsigned long long>(value),
2363 signals ? "; CPU waits on the fences of its held Signals are completed" : "");
2364 for (const Deferred& op : held_)
2365 if (op.kind == Deferred::Kind::signal) context_.cancel_fence_waits(op.fence);
2366 context_.holds().held_changed(-static_cast<std::int64_t>(held_.size()));
2367 dropped.swap(held_);
2368 }
2369 // The pins (fences, pipeline states) are released here, outside the lock.
2263 } 2370 }
2264 2371
2265 struct CommandSlot { 2372 struct CommandSlot {
@@ -2396,8 +2503,7 @@ private:
2396 context_.record_submit_locked(progress_, ticket); 2503 context_.record_submit_locked(progress_, ticket);
2397 } 2504 }
2398 submitted_ = last_sparse_ = ticket; 2505 submitted_ = last_sparse_ = ticket;
2399 waits_.clear(); 2506 clear_waits(ticket);
2400 wait_values_.clear();
2401 for (auto it = changes.begin(); it != changes.end();) { 2507 for (auto it = changes.begin(); it != changes.end();) {
2402 resource->mapped.erase(it->first); 2508 resource->mapped.erase(it->first);
2403 if (it->second.heap) ++it; 2509 if (it->second.heap) ++it;
@@ -2490,7 +2596,12 @@ private:
2490 VkSemaphore signals[2]{progress_, VK_NULL_HANDLE}; 2596 VkSemaphore signals[2]{progress_, VK_NULL_HANDLE};
2491 std::uint64_t signal_values[2]{ticket, 0}; 2597 std::uint64_t signal_values[2]{ticket, 0};
2492 std::uint32_t signal_count = 1; 2598 std::uint32_t signal_count = 1;
2493 if (fence) { 2599 // Decided under the submit lock, so the order of the checks is the order of the submissions. A Signal
2600 // that is not above what was already submitted for this fence (a held Signal(F, 2) released after an
2601 // unheld Signal(F, 3)) leaves the Vulkan signal out: the timeline cannot go down, and waits for 2 pass.
2602 // The value counts as submitted only after the submit succeeded (below).
2603 const bool signals_fence = fence && context_.holds().would_signal(fence, value);
2604 if (signals_fence) {
2494 signals[signal_count] = fence; 2605 signals[signal_count] = fence;
2495 signal_values[signal_count] = value; 2606 signal_values[signal_count] = value;
2496 ++signal_count; 2607 ++signal_count;
@@ -2509,20 +2620,20 @@ private:
2509 submit.signalSemaphoreCount = signal_count; 2620 submit.signalSemaphoreCount = signal_count;
2510 submit.pSignalSemaphores = signals; 2621 submit.pSignalSemaphores = signals;
2511 res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE); 2622 res = context_.vk.vkQueueSubmit(queue_, 1, &submit, VK_NULL_HANDLE);
2512 if (res == VK_SUCCESS) context_.record_submit_locked(progress_, ticket); 2623 if (res == VK_SUCCESS) {
2624 context_.record_submit_locked(progress_, ticket);
2625 if (signals_fence) context_.holds().signaled(fence, value);
2626 }
2513 } 2627 }
2514 if (res == VK_ERROR_DEVICE_LOST) { 2628 if (res == VK_ERROR_DEVICE_LOST) {
2515 context_.mark_device_lost(); 2629 context_.mark_device_lost();
2516 waits_.clear(); 2630 clear_waits();
2517 wait_values_.clear();
2518 return false; 2631 return false;
2519 } 2632 }
2520 const bool ok = (res == VK_SUCCESS); 2633 const bool ok = (res == VK_SUCCESS);
2521 if (ok) { 2634 if (ok) {
2522 if (fence) context_.holds().signaled(fence, value); // held batches waiting for it: the caller pumps
2523 submitted_ = ticket; 2635 submitted_ = ticket;
2524 waits_.clear(); 2636 clear_waits(ticket);
2525 wait_values_.clear();
2526 for (auto& slot : buffers_) 2637 for (auto& slot : buffers_)
2527 if (slot.buffer == command_buffer) slot.ticket = ticket; 2638 if (slot.buffer == command_buffer) slot.ticket = ticket;
2528 } 2639 }
@@ -2554,6 +2665,14 @@ private:
2554 // guards the members above that execute, signal, wait and marker touch. 2665 // guards the members above that execute, signal, wait and marker touch.
2555 std::mutex state_mutex_; 2666 std::mutex state_mutex_;
2556 std::deque<Deferred> held_; 2667 std::deque<Deferred> held_;
2668 std::vector<std::shared_ptr<void>> wait_pins_; // keep the fences of waits_ alive
2669 std::vector<std::shared_ptr<void>> retired_pins_; // released by the caller once state_mutex_ is dropped
2670 struct TicketedPin {
2671 std::uint64_t ticket;
2672 std::shared_ptr<void> pin;
2673 };
2674 std::deque<TicketedPin> pin_queue_; // released once progress_ reaches the ticket
2675 std::atomic<int> held_failure_{0}; // a ReplayResult: the first held batch that failed
2557}; 2676};
2558 2677
2559} // namespace leonida 2678} // namespace leonida
diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h
index a29cce3fa..deeb3ca5c 100644
--- a/runtime/src/vulkan_present.h
+++ b/runtime/src/vulkan_present.h
@@ -35,13 +35,18 @@
35 35
36#include <algorithm> 36#include <algorithm>
37#include <array> 37#include <array>
38#include <atomic>
39#include <chrono>
38#include <cmath> 40#include <cmath>
39#include <cstdint> 41#include <cstdint>
40#include <cstdio> 42#include <cstdio>
41#include <cstring> 43#include <cstring>
42#include <functional> 44#include <functional>
43#include <map> 45#include <map>
46#include <deque>
44#include <memory> 47#include <memory>
48#include <mutex>
49#include <thread>
45#include <vector> 50#include <vector>
46 51
47namespace leonida { 52namespace leonida {
@@ -161,6 +166,7 @@ public:
161 } 166 }
162 167
163 ~VulkanPresenter() { 168 ~VulkanPresenter() {
169 context_.holds().cancel_after(this); // presents still queued behind held work are dropped
164 auto& vk = context_.vk; 170 auto& vk = context_.vk;
165 const VkDevice device = context_.device(); 171 const VkDevice device = context_.device();
166 { 172 {
@@ -186,7 +192,10 @@ public:
186 VulkanPresenter& operator=(const VulkanPresenter&) = delete; 192 VulkanPresenter& operator=(const VulkanPresenter&) = delete;
187 193
188 bool ok() const { return ok_; } 194 bool ok() const { return ok_; }
189 VkExtent2D extent() const { return extent_; } 195 VkExtent2D extent() const {
196 const std::uint64_t packed = extent_packed_;
197 return {std::uint32_t(packed >> 32), std::uint32_t(packed)};
198 }
190 VkFormat format() const { return format_; } 199 VkFormat format() const { return format_; }
191 std::uint64_t presented() const { return presented_; } 200 std::uint64_t presented() const { return presented_; }
192 // The present mode a tearing present uses (IMMEDIATE, else FIFO_RELAXED) while the current swapchain was created 201 // The present mode a tearing present uses (IMMEDIATE, else FIFO_RELAXED) while the current swapchain was created
@@ -194,6 +203,7 @@ public:
194 VkPresentModeKHR tear_mode() const { return tear_mode_; } 203 VkPresentModeKHR tear_mode() const { return tear_mode_; }
195 bool tear_supported() const { return tear_mode_ != VK_PRESENT_MODE_MAX_ENUM_KHR; } 204 bool tear_supported() const { return tear_mode_ != VK_PRESENT_MODE_MAX_ENUM_KHR; }
196 // Whether the last present was queued in the tearing mode, and how many were. 205 // Whether the last present was queued in the tearing mode, and how many were.
206 // A present queued behind held work (see submit()) is reported as not tearing.
197 bool last_present_tore() const { return last_tore_; } 207 bool last_present_tore() const { return last_tore_; }
198 std::uint64_t tear_presents() const { return tear_presents_; } 208 std::uint64_t tear_presents() const { return tear_presents_; }
199 209
@@ -279,7 +289,10 @@ public:
279 289
280 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with 290 // Polled while a present waits for a swapchain image (every 50 ms): when it returns true the present gives up with
281 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames. 291 // VK_NOT_READY, so a caller that is being suspended is never held by a window that stopped taking frames.
282 void set_abort(std::function<bool()> abort) { abort_ = std::move(abort); } 292 void set_abort(std::function<bool()> abort) {
293 std::lock_guard lock(abort_mutex_);
294 abort_ = std::move(abort);
295 }
283 296
284 // Presents a black frame: the swapchain image cleared, nothing read. PresentX with no planes. 297 // Presents a black frame: the swapchain image cleared, nothing read. PresentX with no planes.
285 VkResult present_blank(bool vsync, bool tear = false) { 298 VkResult present_blank(bool vsync, bool tear = false) {
@@ -290,6 +303,7 @@ public:
290 // read_back(). False when the surface cannot do it or its format is not 8 bits per channel with 4 channels. 303 // read_back(). False when the surface cannot do it or its format is not 8 bits per channel with 4 channels.
291 // Call before the first present. 304 // Call before the first present.
292 bool enable_capture() { 305 bool enable_capture() {
306 std::lock_guard lock(present_mutex_);
293 if (!ok_) return false; 307 if (!ok_) return false;
294 capture_ = true; 308 capture_ = true;
295 stale_ = true; 309 stale_ = true;
@@ -305,6 +319,7 @@ public:
305 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next 319 // that was skipped because the window is minimised (it returned VK_SUCCESS but showed nothing), until the next
306 // frame that is shown (the frame before it is not what the window was last asked to show), or when the wait fails. 320 // frame that is shown (the frame before it is not what the window was last asked to show), or when the wait fails.
307 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format) { 321 bool read_back(std::vector<std::uint8_t>& pixels, VkExtent2D* extent, VkFormat* format) {
322 std::lock_guard lock(present_mutex_);
308 if (!capture_ || !capture_ptr_ || !captured_) return false; 323 if (!capture_ || !capture_ptr_ || !captured_) return false;
309 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()]; 324 const Frame& frame = frames_[(frame_index_ + frames_.size() - 1) % frames_.size()];
310 if (vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX) != VK_SUCCESS) 325 if (vkWaitForFences_(context_.device(), 1, &frame.done, VK_TRUE, UINT64_MAX) != VK_SUCCESS)
@@ -315,10 +330,95 @@ public:
315 return true; 330 return true;
316 } 331 }
317 332
318 // Shared by present(), present_blank() and present_planes(). `binding` null and `planes` null: clear instead of blit; 333 // Shared by present(), present_blank() and present_planes().
319 // `planes`: compose them (`binding`, `source`, `source_rect` unused). 334 //
335 // A Present is ordered behind the work the queues hold (a batch that waits for a Signal not yet submitted,
336 // queue_holds.h): it would otherwise blit whatever the source texture held before that batch ran. It is not
337 // blocked: it is queued, returns VK_SUCCESS as ExecuteCommandLists does for a held batch, and is submitted,
338 // in order with the presents before it, by the thread that releases the last operation held when it was called
339 // (its failure is printed there). Held work that is never released holds back the presents after it, as it
340 // holds back the queue's own work; with nothing held this is the plain path. A blank present reads nothing and
341 // is only ordered behind earlier presents. Waiting instead was rejected: the Signal that releases the work may
342 // be one the application's own thread makes after Present returns. Like a full frame-latency queue, a Present that
343 // finds max_deferred_presents queued ahead of it does wait, for held work to release (logged once; set_abort ends
344 // the wait), so the queue behind never-released work is bounded. A queued Present reports its tear as false
345 // (last_present_tore()): the frame pacer's default sync.
346 static constexpr std::size_t max_deferred_presents = 8;
347
320 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect, 348 VkResult submit(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect,
321 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) { 349 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
350 wait_for_room();
351 std::lock_guard lock(present_mutex_);
352 // `binding` null and `planes` null: clear instead of blit; `planes`: compose them (`binding`, `source`,
353 // `source_rect` unused). Only a present that reads a texture waits for held work.
354 if (deferred_.empty() && !((binding || planes) && context_.holds().any_held()))
355 return submit_now(binding, source, vsync, source_rect, srgb, tear, planes);
356 PendingPresent pending{binding != nullptr, source, vsync, source_rect != nullptr, {}, srgb, tear,
357 planes != nullptr, {}};
358 if (source_rect) pending.rect = *source_rect;
359 if (planes) pending.planes = *planes;
360 deferred_.push_back(pending);
361 last_tore_ = false;
362 context_.holds().after_held(this, [this] { run_deferred(); });
363 return VK_SUCCESS;
364 }
365
366private:
367 bool should_abort() {
368 std::function<bool()> abort;
369 {
370 std::lock_guard lock(abort_mutex_);
371 abort = abort_;
372 }
373 return abort && abort();
374 }
375
376 // Called without present_mutex_: the thread that releases the queued presents needs it.
377 void wait_for_room() {
378 bool logged = false;
379 for (;;) {
380 {
381 std::lock_guard lock(present_mutex_);
382 if (deferred_.size() < max_deferred_presents) return;
383 }
384 if (!logged) {
385 logged = true;
386 std::fprintf(stderr, "[rt] d3d12: %zu Presents are queued behind held work; this one waits for it\n",
387 max_deferred_presents);
388 }
389 if (should_abort()) return;
390 std::this_thread::sleep_for(std::chrono::milliseconds(1));
391 }
392 }
393
394 struct PendingPresent {
395 bool has_source;
396 ResourceId source;
397 bool vsync;
398 bool has_rect;
399 PresentRect rect;
400 bool srgb;
401 bool tear;
402 bool has_planes;
403 PresentPlanes planes;
404 };
405
406 void run_deferred() {
407 std::lock_guard lock(present_mutex_);
408 if (deferred_.empty()) return;
409 const PendingPresent p = deferred_.front();
410 deferred_.pop_front();
411 ResourceBinding binding{};
412 const VkResult result = submit_now(p.has_source ? &binding : nullptr, p.source, p.vsync,
413 p.has_rect ? &p.rect : nullptr, p.srgb, p.tear,
414 p.has_planes ? &p.planes : nullptr);
415 if (result != VK_SUCCESS)
416 std::fprintf(stderr, "[rt] d3d12: a Present held behind queued work failed when it was released (%d)\n",
417 int(result));
418 }
419
420 VkResult submit_now(const ResourceBinding* binding, ResourceId source, bool vsync, const PresentRect* source_rect,
421 bool srgb, bool tear = false, const PresentPlanes* planes = nullptr) {
322 last_tore_ = false; 422 last_tore_ = false;
323 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED; 423 if (!ok_) return VK_ERROR_INITIALIZATION_FAILED;
324 // The swapchain's HDR10 format is only for composed planes that ask for it; a blit of an SDR source or a blank 424 // The swapchain's HDR10 format is only for composed planes that ask for it; a blit of an SDR source or a blank
@@ -741,7 +841,7 @@ private:
741 const VkResult result = vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore, 841 const VkResult result = vkAcquireNextImageKHR_(context_.device(), swapchain_, 50'000'000, semaphore,
742 VK_NULL_HANDLE, image); 842 VK_NULL_HANDLE, image);
743 if (result != VK_TIMEOUT && result != VK_NOT_READY) return result; 843 if (result != VK_TIMEOUT && result != VK_NOT_READY) return result;
744 if (abort_ && abort_()) return VK_NOT_READY; 844 if (should_abort()) return VK_NOT_READY;
745 } 845 }
746 } 846 }
747 847
@@ -1029,6 +1129,7 @@ private:
1029 ready_ = std::move(ready); 1129 ready_ = std::move(ready);
1030 format_ = chosen.format; 1130 format_ = chosen.format;
1031 extent_ = extent; 1131 extent_ = extent;
1132 extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height;
1032 hdr_active_ = chose_hdr; 1133 hdr_active_ = chose_hdr;
1033 if (capture_) { 1134 if (capture_) {
1034 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. 1135 // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set.
@@ -1112,11 +1213,15 @@ private:
1112 VkInstance instance_; 1213 VkInstance instance_;
1113 VkPhysicalDevice physical_; 1214 VkPhysicalDevice physical_;
1114 VkQueue queue_; 1215 VkQueue queue_;
1216 mutable std::recursive_mutex present_mutex_; // all presenter state: submit(), a deferred present, the accessors
1217 mutable std::mutex abort_mutex_; // abort_ alone: set_abort() must work while a present waits
1218 std::deque<PendingPresent> deferred_; // presents queued behind held work, in call order
1115 VkSurfaceKHR surface_; 1219 VkSurfaceKHR surface_;
1116 bool maintenance1_ = false; // VK_KHR/EXT_swapchain_maintenance1 (and the surface extension) are enabled 1220 bool maintenance1_ = false; // VK_KHR/EXT_swapchain_maintenance1 (and the surface extension) are enabled
1117 VkPresentModeKHR tear_mode_ = VK_PRESENT_MODE_MAX_ENUM_KHR; // set with the swapchain, see tear_mode() 1221 VkPresentModeKHR tear_mode_ = VK_PRESENT_MODE_MAX_ENUM_KHR; // set with the swapchain, see tear_mode()
1118 bool last_tore_ = false; 1222 std::atomic<bool> last_tore_{false};
1119 std::uint64_t tear_presents_ = 0; 1223 std::atomic<std::uint64_t> extent_packed_{0}; // extent_ for readers that must not wait for a present
1224 std::atomic<std::uint64_t> tear_presents_{0};
1120 VkSwapchainKHR swapchain_ = VK_NULL_HANDLE; 1225 VkSwapchainKHR swapchain_ = VK_NULL_HANDLE;
1121 VkFormat format_ = VK_FORMAT_UNDEFINED; 1226 VkFormat format_ = VK_FORMAT_UNDEFINED;
1122 VkExtent2D extent_{}; 1227 VkExtent2D extent_{};
@@ -1125,15 +1230,15 @@ private:
1125 std::array<Frame, 2> frames_{}; 1230 std::array<Frame, 2> frames_{};
1126 VkCommandPool pool_ = VK_NULL_HANDLE; 1231 VkCommandPool pool_ = VK_NULL_HANDLE;
1127 std::uint64_t frame_index_ = 0; 1232 std::uint64_t frame_index_ = 0;
1128 std::uint64_t presented_ = 0; 1233 std::atomic<std::uint64_t> presented_{0};
1129 bool vsync_ = true; 1234 bool vsync_ = true;
1130 bool stale_ = false; 1235 bool stale_ = false;
1131 bool ok_ = false; 1236 bool ok_ = false;
1132 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists) 1237 bool swapchain_srgb_ = false; // the swapchain format follows the source being presented (set once it exists)
1133 bool swapchain_hdr_req_ = false; // the swapchain was built for an HDR10 request (it has the format only if hdr_active_) 1238 bool swapchain_hdr_req_ = false; // the swapchain was built for an HDR10 request (it has the format only if hdr_active_)
1134 bool hdr_active_ = false; 1239 bool hdr_active_ = false;
1135 std::uint64_t composed_ = 0; 1240 std::atomic<std::uint64_t> composed_{0};
1136 bool force_hdr_encoding_ = false; 1241 std::atomic<bool> force_hdr_encoding_{false};
1137 bool warned_hdr_ = false; 1242 bool warned_hdr_ = false;
1138 std::unique_ptr<PresentComposer> composer_; 1243 std::unique_ptr<PresentComposer> composer_;
1139 std::function<bool()> abort_; 1244 std::function<bool()> abort_;
diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp
index a4530345d..9f1d1dacb 100644
--- a/runtime/test/d3d12_m4_compute_test.cpp
+++ b/runtime/test/d3d12_m4_compute_test.cpp
@@ -17,7 +17,8 @@
17// CopyTextureRegion) to a READBACK buffer, Signal(copy fence, 2). The CPU waits for that with 17// CopyTextureRegion) to a READBACK buffer, Signal(copy fence, 2). The CPU waits for that with
18// SetEventOnCompletion and an event. 18// SetEventOnCompletion and an event.
19// When the Vulkan family has two queues, the copy and the compute D3D12 queue get their own VkQueue (so the fences are 19// When the Vulkan family has two queues, the copy and the compute D3D12 queue get their own VkQueue (so the fences are
20// real cross-queue semaphores); with one, they share it. Either way the readback batch is submitted before the compute batch it waits for (the layer holds it until that Signal has been submitted). 20// real cross-queue semaphores); with one, they share it. Either way the compute batch is submitted before the copy that feeds it: the layer holds it until that Signal
21// has been submitted, with the PSOs and root signature the application released in between.
21// Compared with a CPU reference, word by word, error 0: the input after the round trip, the structured buffer, the 22// Compared with a CPU reference, word by word, error 0: the input after the round trip, the structured buffer, the
22// argument buffer, the image and the indirect dispatch's output (which also shows that exactly the 3 groups the 23// argument buffer, the image and the indirect dispatch's output (which also shows that exactly the 3 groups the
23// first dispatch asked for ran). 24// first dispatch asked for ran).
@@ -331,11 +332,17 @@ int main() {
331 return SUCCEEDED(compute_queue->Wait(copy_fence.p, 1)) && execute(compute_queue.p, compute_list.p) && 332 return SUCCEEDED(compute_queue->Wait(copy_fence.p, 1)) && execute(compute_queue.p, compute_list.p) &&
332 SUCCEEDED(compute_queue->Signal(compute_fence.p, 1)); 333 SUCCEEDED(compute_queue->Signal(compute_fence.p, 1));
333 }; 334 };
334 // The compute list goes last, after the copy-queue list that reads its results (the copy queue keeps its own 335 // The compute list goes first, before the copy that feeds it: it waits for a Signal not yet submitted, so the
335 // order): a list that waits for a Signal submitted later is held by the layer 336 // layer holds it until the copy has been submitted, and its layouts follow the dependency order (docs section
336 // until it has been, so its layouts follow the dependency order (docs section 4.4; d3d12_queue_handover_test 337 // 4.4; d3d12_queue_handover_test covers every order). The application may release what the list uses as soon
337 // covers every order). 338 // as ExecuteCommandLists returns: the pipeline states and the root signature go and the list is Reset, all
338 EXPECT(submit_copy() && submit_readback() && submit_compute()); 339 // while the batch is still held, so the layer has to keep them until it runs.
340 EXPECT(submit_compute());
341 pso_fill.reset();
342 pso_indirect.reset();
343 root.reset();
344 EXPECT(compute_list->Reset(compute_alloc.p, nullptr) == S_OK && compute_list->Close() == S_OK);
345 EXPECT(submit_copy() && submit_readback());
339 346
340 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); 347 const HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
341 EXPECT(event != nullptr); 348 EXPECT(event != nullptr);
diff --git a/runtime/test/d3d12_queue_handover_test.cpp b/runtime/test/d3d12_queue_handover_test.cpp
index c445fdfe6..1fabcfb4e 100644
--- a/runtime/test/d3d12_queue_handover_test.cpp
+++ b/runtime/test/d3d12_queue_handover_test.cpp
@@ -17,6 +17,7 @@
17// compared byte for byte with the data written by the CPU: a consumer replayed against the layout from before its 17// compared byte for byte with the data written by the CPU: a consumer replayed against the layout from before its
18// producer ran reads a zero-filled texture and fails here (and with LEONIDA_VK_VALIDATION=1 under sync validation). 18// producer ran reads a zero-filled texture and fails here (and with LEONIDA_VK_VALIDATION=1 under sync validation).
19// No game data. 19// No game data.
20#include "vk_test_device.h"
20#include "../shims/d3d12_com.h" 21#include "../shims/d3d12_com.h"
21 22
22#include <dxgi1_4.h> 23#include <dxgi1_4.h>
@@ -364,6 +365,7 @@ bool cpu_released_chain(Rig& rig, const Roles& roles, int seed) {
364 365
365// A CPU Signal that comes before the Wait (nothing is held), and one that comes after the batch was submitted. 366// A CPU Signal that comes before the Wait (nothing is held), and one that comes after the batch was submitted.
366bool cpu_gate(Rig& rig, Type producer, Type consumer, bool signal_first, int seed) { 367bool cpu_gate(Rig& rig, Type producer, Type consumer, bool signal_first, int seed) {
368 if (!rig.available[producer] || !rig.available[consumer]) return true;
367 if (producer == consumer && rig.available[producer] < 2) return true; 369 if (producer == consumer && rig.available[producer] < 2) return true;
368 const int cslot = producer == consumer ? 1 : 0; 370 const int cslot = producer == consumer ? 1 : 0;
369 std::string name = std::string("CPU Signal ") + (signal_first ? "before" : "after") + " the consumer's Wait, " + 371 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<void()>& body) {
413// A batch waits for a fence nobody signals. The other queues keep working, the batch never runs, destroying the queue 415// A batch waits for a fence nobody signals. The other queues keep working, the batch never runs, destroying the queue
414// does not hang and the layer says why. Layer only: the host runtime has nothing to report. 416// does not hang and the layer says why. Layer only: the host runtime has nothing to report.
415bool never_signaled(Rig& rig, int seed) { 417bool never_signaled(Rig& rig, int seed) {
418 if (!rig.available[copy_q] || !rig.available[direct_q]) return true;
416 arm("fence nobody signals"); 419 arm("fence nobody signals");
417 Case c(rig, seed); 420 Case c(rig, seed);
418 if (!c.make_resources()) return false; 421 if (!c.make_resources()) return false;
@@ -463,31 +466,210 @@ bool fence_released(Rig& rig, int seed) {
463 ID3D12CommandList* batch[] = {held}; 466 ID3D12CommandList* batch[] = {held};
464 if (FAILED(victim->Wait(doomed.Get(), 9))) return c.fail("Wait", __LINE__); 467 if (FAILED(victim->Wait(doomed.Get(), 9))) return c.fail("Wait", __LINE__);
465 victim->ExecuteCommandLists(1, batch); 468 victim->ExecuteCommandLists(1, batch);
466 const std::string log = capture_stderr([&] { doomed.Reset(); victim.Reset(); }); 469 // The queue holds the fence it waits on, as D3D12 does: the application's release does not free it under the held
467 if (log.find("fence was released while a queue still held work") == std::string::npos) { 470 // batch. The batch stays held (nothing ran) and is reported when the queue goes.
471 doomed.Reset();
472 Sleep(50);
473 const std::string log = capture_stderr([&] { victim.Reset(); });
474 if (log.find("queue destroyed with") == std::string::npos) {
475 std::fprintf(stderr, "stderr was: \"%s\"\n", log.c_str());
476 return c.fail("no report for the held batch", __LINE__);
477 }
478 ++cases_run;
479 return true;
480}
481
482// Review item 4: a held Signal names a fence the application has released. The fence lives until the Signal has been
483// submitted (a queue behind it that waits for the fence proves it was signaled), with nothing used after free.
484bool held_signal_survives_release(Rig& rig, int seed) {
485 if (!rig.available[direct_q] || !rig.available[compute_q]) return true;
486 arm("held Signal of a released fence");
487 Case c(rig, seed);
488 if (!c.make_resources()) return false;
489 ComPtr<ID3D12Fence> gate, target;
490 if (FAILED(rig.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate))) ||
491 FAILED(rig.device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&target))))
492 return false;
493 ID3D12CommandQueue* a = rig.queues[direct_q][0].Get();
494 ID3D12CommandQueue* b = rig.queues[compute_q][0].Get();
495 // a: Wait(gate), copy upload -> stage[0], Signal(target) (held until the CPU signals the gate)
496 ID3D12GraphicsCommandList* produce = c.make_list(direct_q, nullptr, &c.stage[0], 3);
497 ID3D12GraphicsCommandList* consume = c.make_list(compute_q, &c.stage[0], nullptr, 3);
498 if (!produce || !consume) return c.fail("setup", __LINE__);
499 if (FAILED(a->Wait(gate.Get(), 1))) return c.fail("Wait", __LINE__);
500 ID3D12CommandList* pb[] = {produce};
501 a->ExecuteCommandLists(1, pb);
502 if (FAILED(a->Signal(target.Get(), 1))) return c.fail("Signal", __LINE__);
503 if (FAILED(b->Wait(target.Get(), 1))) return c.fail("Wait", __LINE__);
504 ID3D12CommandList* cb[] = {consume};
505 b->ExecuteCommandLists(1, cb);
506 if (FAILED(b->Signal(c.fence(2), 1))) return c.fail("Signal", __LINE__);
507 target.Reset(); // the application is done with it; both queues still name it
508 Sleep(20);
509 if (FAILED(gate->Signal(1))) return c.fail("CPU Signal", __LINE__);
510 ++cases_run;
511 return c.wait_fence(2, 1) && c.verify();
512}
513
514// Review item 3: Signal(F, 2) is held, Signal(F, 3) on another queue is not. When the held one is released the
515// timeline is already at 3 and must not be signaled lower; a wait for 2 passes and F reads 3. Layer only (D3D12 sets
516// the fence to the lower value).
517bool monotonic_shared_fence(Rig& rig, int seed) {
518 if (!rig.available[direct_q] || !rig.available[copy_q] || !rig.available[compute_q]) return true;
519 arm("held Signal below an unheld one");
520 Case c(rig, seed);
521 if (!c.make_resources()) return false;
522 ID3D12CommandQueue* a = rig.queues[direct_q][0].Get();
523 ID3D12CommandQueue* b = rig.queues[copy_q][0].Get();
524 ID3D12CommandQueue* w = rig.queues[compute_q][0].Get();
525 ID3D12Fence *gate = c.fence(0), *shared = c.fence(1);
526 ID3D12GraphicsCommandList* produce = c.make_list(copy_q, nullptr, &c.stage[0], 3);
527 ID3D12GraphicsCommandList* consume = c.make_list(compute_q, &c.stage[0], nullptr, 3);
528 if (!gate || !shared || !produce || !consume) return c.fail("setup", __LINE__);
529 if (FAILED(a->Wait(gate, 1)) || FAILED(a->Signal(shared, 2))) return c.fail("held Signal", __LINE__); // held
530 ID3D12CommandList* pb[] = {produce};
531 b->ExecuteCommandLists(1, pb);
532 if (FAILED(b->Signal(shared, 3))) return c.fail("Signal", __LINE__); // not held
533 if (c.wait_fence(1, 3) == false) return false;
534 if (FAILED(gate->Signal(1))) return c.fail("CPU Signal", __LINE__); // releases a
535 // A queue that waits for 2 now: satisfied, and the data the copy queue wrote is what it reads.
536 if (FAILED(w->Wait(shared, 2))) return c.fail("Wait", __LINE__);
537 ID3D12CommandList* cb[] = {consume};
538 w->ExecuteCommandLists(1, cb);
539 if (FAILED(w->Signal(c.fence(2), 1))) return c.fail("Signal", __LINE__);
540 if (!c.wait_fence(2, 1) || !c.verify()) return false;
541 Sleep(50);
542 if (shared->GetCompletedValue() != 3) return c.fail("the fence went below 3", __LINE__);
543 ++cases_run;
544 return true;
545}
546
547// Review item 5: a queue destroyed with a held Signal wakes the CPU wait on that fence (with a report) instead of
548// leaving it hanging.
549bool teardown_wakes_cpu_waiters(Rig& rig, int seed) {
550 arm("teardown with a held Signal");
551 Case c(rig, seed);
552 if (!c.make_resources()) return false;
553 ComPtr<ID3D12CommandQueue> victim;
554 const D3D12_COMMAND_QUEUE_DESC desc{D3D12_COMMAND_LIST_TYPE_DIRECT};
555 if (FAILED(rig.device->CreateCommandQueue(&desc, IID_PPV_ARGS(&victim)))) return true;
556 ID3D12Fence *never = c.fence(0), *target = c.fence(1);
557 if (FAILED(victim->Wait(never, 1)) || FAILED(victim->Signal(target, 1))) return c.fail("setup", __LINE__);
558 HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
559 if (FAILED(target->SetEventOnCompletion(1, event))) return c.fail("SetEventOnCompletion", __LINE__);
560 const std::string log = capture_stderr([&] { victim.Reset(); });
561 const bool woke = WaitForSingleObject(event, 5000) == WAIT_OBJECT_0;
562 CloseHandle(event);
563 if (!woke) return c.fail("the CPU wait on the held Signal's fence was never woken", __LINE__);
564 if (log.find("CPU waits on the fences of its held Signals are completed") == std::string::npos) {
468 std::fprintf(stderr, "stderr was: \"%s\"\n", log.c_str()); 565 std::fprintf(stderr, "stderr was: \"%s\"\n", log.c_str());
469 return c.fail("no report for the dropped batch", __LINE__); 566 return c.fail("no report", __LINE__);
470 } 567 }
471 ++cases_run; 568 ++cases_run;
472 return true; 569 return true;
473} 570}
474 571
572// Two threads: one submits a consumer and a relay (both held, waiting for fences that are signaled by queues it does
573// not own), the other submits the producer and signals a CPU gate the producer waits on, at the same moment, many
574// times over. Everything is built up front; the threads only make queue calls.
575bool concurrent_signalling(Rig& rig, int iterations, int seed) {
576 if (!Roles::make(copy_q, compute_q, direct_q).fits(rig)) return true; // needs one queue of each type
577 arm("two threads signalling and releasing", 120000);
578 struct Round {
579 std::unique_ptr<Case> c;
580 Case::Job jobs[3];
581 ID3D12GraphicsCommandList* lists[3];
582 };
583 std::vector<Round> rounds(iterations);
584 const Roles roles = Roles::make(copy_q, compute_q, direct_q);
585 for (int i = 0; i < iterations; ++i) {
586 Round& r = rounds[i];
587 r.c = std::make_unique<Case>(rig, seed + i);
588 Case& c = *r.c;
589 if (!c.make_resources()) return false;
590 const bool gated = i % 2 == 0;
591 r.jobs[0] = {roles.type[0], roles.slot[0], nullptr, &c.stage[0], 3, gated ? std::vector<std::pair<int, UINT64>>{{3, 1}} : std::vector<std::pair<int, UINT64>>{}, 0};
592 r.jobs[1] = {roles.type[1], roles.slot[1], &c.stage[0], &c.stage[1], 3, {{0, 1}}, 1};
593 r.jobs[2] = {roles.type[2], roles.slot[2], &c.stage[1], nullptr, 3, {{1, 1}}, 2};
594 for (int j = 0; j < 3; ++j) {
595 r.lists[j] = c.make_list(r.jobs[j].type, r.jobs[j].src, r.jobs[j].dst, r.jobs[j].mask);
596 if (!r.lists[j]) return false;
597 }
598 if (!c.fence(3)) return false;
599 }
600 std::atomic<int> turn{-1}, ready{0}, failed{0};
601 const auto fire = [&](Case& c, const Case::Job& job, ID3D12GraphicsCommandList* list) {
602 ID3D12CommandQueue* queue = rig.queues[job.type][job.slot].Get();
603 for (const auto& [f, v] : job.waits)
604 if (FAILED(queue->Wait(c.fences[f].Get(), v))) failed++;
605 ID3D12CommandList* batch[] = {list};
606 queue->ExecuteCommandLists(1, batch);
607 if (job.signal >= 0 && FAILED(queue->Signal(c.fences[job.signal].Get(), 1))) failed++;
608 };
609 std::thread consumer_side([&] {
610 for (int i = 0; i < iterations; ++i) {
611 ready++;
612 while (turn.load() < i) std::this_thread::yield();
613 fire(*rounds[i].c, rounds[i].jobs[2], rounds[i].lists[2]);
614 fire(*rounds[i].c, rounds[i].jobs[1], rounds[i].lists[1]);
615 }
616 });
617 std::thread producer_side([&] {
618 for (int i = 0; i < iterations; ++i) {
619 while (ready.load() <= i) std::this_thread::yield();
620 turn = i;
621 fire(*rounds[i].c, rounds[i].jobs[0], rounds[i].lists[0]);
622 if (i % 2 == 0 && FAILED(rounds[i].c->fences[3]->Signal(1))) failed++;
623 }
624 });
625 producer_side.join();
626 consumer_side.join();
627 if (failed) return rounds[0].c->fail("a queue call failed", __LINE__);
628 bool ok = true;
629 for (int i = 0; i < iterations; ++i) {
630 arm("two threads signalling and releasing", 20000);
631 ok &= rounds[i].c->wait_fence(2, 1) && rounds[i].c->verify();
632 }
633 cases_run += iterations;
634 return ok;
635}
636
637// Producer and consumer on two queues, in both submission orders: what fits when the device hands over only two
638// VkQueues (the D3D12 queues share them) and what M4's copy -> compute -> copy path does.
639bool pair_case(Rig& rig, Type a, Type b, bool consumer_first, int seed) {
640 const int sb = a == b ? 1 : 0;
641 if (!rig.available[a] || sb >= rig.available[b]) return true;
642 std::string name = std::string("pair ") + type_name[a] + "->" + type_name[b] +
643 (consumer_first ? " consumer first" : " producer first");
644 arm(name.c_str());
645 Case c(rig, seed);
646 if (!c.make_resources()) return false;
647 const Case::Job produce{a, 0, nullptr, &c.stage[0], 3, {}, 0};
648 const Case::Job consume{b, sb, &c.stage[0], nullptr, 3, {{0, 1}}, 2};
649 if (consumer_first ? !(c.submit(consume) && c.submit(produce)) : !(c.submit(produce) && c.submit(consume)))
650 return false;
651 ++cases_run;
652 return c.wait_fence(2, 1) && c.verify();
653}
654
475bool run_all(ID3D12Device* device, bool layer) { 655bool run_all(ID3D12Device* device, bool layer) {
476 Rig rig; 656 Rig rig;
477 rig.device = device; 657 rig.device = device;
478 for (int t = 0; t < 3; ++t) 658 for (int i = 0; i < pool_size; ++i) // one of each type first: a caller-owned device may hand over only a few
479 for (int i = 0; i < pool_size; ++i) { 659 for (int t = 0; t < 3; ++t) {
660 if (rig.available[t] != i) continue;
480 D3D12_COMMAND_QUEUE_DESC desc{}; 661 D3D12_COMMAND_QUEUE_DESC desc{};
481 desc.Type = list_type[t]; 662 desc.Type = list_type[t];
482 if (FAILED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&rig.queues[t][i])))) break; 663 if (SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&rig.queues[t][i])))) ++rig.available[t];
483 ++rig.available[t];
484 } 664 }
485 std::printf("queues available per type (COPY/COMPUTE/DIRECT): %d/%d/%d\n", rig.available[0], rig.available[1], 665 std::printf("queues available per type (COPY/COMPUTE/DIRECT): %d/%d/%d\n", rig.available[0], rig.available[1],
486 rig.available[2]); 666 rig.available[2]);
487 if (!rig.available[0] || !rig.available[1] || !rig.available[2]) return true; // nothing to hand over between
488 667
489 bool ok = true; 668 bool ok = true;
490 int seed = 100, skipped = 0; 669 int seed = 100, skipped = 0;
670 for (int a = 0; a < 3; ++a)
671 for (int b = 0; b < 3; ++b)
672 for (bool consumer_first : {true, false}) ok &= pair_case(rig, Type(a), Type(b), consumer_first, ++seed);
491 std::array<int, 3> order{0, 1, 2}; 673 std::array<int, 3> order{0, 1, 2};
492 for (int a = 0; a < 3; ++a) 674 for (int a = 0; a < 3; ++a)
493 for (int b = 0; b < 3; ++b) 675 for (int b = 0; b < 3; ++b)
@@ -511,12 +693,16 @@ bool run_all(ID3D12Device* device, bool layer) {
511 for (int p = 0; p < 3; ++p) 693 for (int p = 0; p < 3; ++p)
512 for (int q = 0; q < 3; ++q) 694 for (int q = 0; q < 3; ++q)
513 for (bool first : {true, false}) ok &= cpu_gate(rig, Type(p), Type(q), first, ++seed); 695 for (bool first : {true, false}) ok &= cpu_gate(rig, Type(p), Type(q), first, ++seed);
696 ok &= concurrent_signalling(rig, 200, seed += 1000);
514 if (layer) { 697 if (layer) {
515 // The layer hands out a limited number of VkQueues: give the spare ones back for the two cases below. 698 // The layer hands out a limited number of VkQueues: give the spare ones back for the two cases below.
516 for (auto& type_queues : rig.queues) 699 for (auto& type_queues : rig.queues)
517 for (int i = 1; i < pool_size; ++i) type_queues[i].Reset(); 700 for (int i = 1; i < pool_size; ++i) type_queues[i].Reset();
518 ok &= never_signaled(rig, ++seed); 701 ok &= never_signaled(rig, ++seed);
519 ok &= fence_released(rig, ++seed); 702 ok &= fence_released(rig, ++seed);
703 ok &= held_signal_survives_release(rig, ++seed);
704 ok &= monotonic_shared_fence(rig, ++seed);
705 ok &= teardown_wakes_cpu_waiters(rig, ++seed);
520 } 706 }
521 if (skipped) std::printf("(%d type assignments need more queues than the device gave)\n", skipped); 707 if (skipped) std::printf("(%d type assignments need more queues than the device gave)\n", skipped);
522 return ok; 708 return ok;
@@ -539,7 +725,15 @@ ComPtr<ID3D12Device> native_device(std::wstring& name) {
539 725
540} // namespace 726} // namespace
541 727
542int main() { 728// Modes (argv[1]):
729// (none) the standalone device, which gives each D3D12 queue its own VkQueue; then the host runtime
730// --two-queues a caller-owned device with two VkQueues of the family handed over (VulkanDeviceInfo::command_queues):
731// the D3D12 queues of a type share them, so a Wait and the Signal it needs can land on one VkQueue
732// --shared-queue a caller-owned device that hands over its one VkQueue: every D3D12 queue shares it (the legacy
733// single-queue behaviour), where a Wait submitted ahead of its Signal would never progress on the GPU
734int main(int argc, char** argv) {
735 const bool two_queues = argc > 1 && std::strcmp(argv[1], "--two-queues") == 0;
736 const bool shared_queue = argc > 1 && std::strcmp(argv[1], "--shared-queue") == 0;
543 std::thread([] { 737 std::thread([] {
544 for (;;) { 738 for (;;) {
545 Sleep(100); 739 Sleep(100);
@@ -552,8 +746,32 @@ int main() {
552 } 746 }
553 }).detach(); 747 }).detach();
554 748
749 vktest::Device vk;
555 ComPtr<ID3D12Device> layer; 750 ComPtr<ID3D12Device> layer;
556 if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&layer)))) { 751 if (two_queues || shared_queue) {
752 vk.queue_count_wanted = two_queues ? 2 : 1;
753 const auto status = vk.initialize();
754 if (status == vktest::DeviceStatus::unavailable) return 77;
755 if (status != vktest::DeviceStatus::ready) return 1;
756 if (two_queues && vk.queues.size() < 2) {
757 std::puts("the queue family has one queue: two-queue mode skipped");
758 return 77;
759 }
760 rt::d3d12::VulkanDeviceInfo info{};
761 info.get_instance_proc = vk.instance_proc;
762 info.instance = vk.instance;
763 info.physical = vk.physical;
764 info.device = vk.device;
765 info.queue = vk.queue;
766 info.queue_family = vk.family;
767 if (two_queues) info.command_queues = vk.queues;
768 if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&layer)))) {
769 std::puts("Vulkan device unavailable");
770 return 77;
771 }
772 std::printf("caller-owned device, %zu VkQueue(s) handed to the layer\n",
773 two_queues ? vk.queues.size() : size_t(1));
774 } else if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&layer)))) {
557 std::puts("Vulkan standalone device unavailable"); 775 std::puts("Vulkan standalone device unavailable");
558 return 77; 776 return 77;
559 } 777 }
@@ -562,7 +780,13 @@ int main() {
562 if (!run_all(layer.Get(), true)) return 1; 780 if (!run_all(layer.Get(), true)) return 1;
563 const int layer_cases = cases_run; 781 const int layer_cases = cases_run;
564 std::printf("Vulkan layer: %d cases passed, every one exact\n", layer_cases); 782 std::printf("Vulkan layer: %d cases passed, every one exact\n", layer_cases);
565 783 layer.Reset();
784 if (vk.validation_errors()) {
785 std::fprintf(stderr, "%u validation errors\n", vk.validation_errors());
786 return 1;
787 }
788 // Every mode ends with the same cases on the host runtime: the expected data is the CPU's pattern in all of
789 // them, so the host run shows the cases are valid D3D12 and the layer's modes are held to the same bar.
566 std::wstring name; 790 std::wstring name;
567 if (auto host = native_device(name)) { 791 if (auto host = native_device(name)) {
568 arm("host runtime", 300000); 792 arm("host runtime", 300000);
diff --git a/runtime/test/vk_presenter_sync_test.cpp b/runtime/test/vk_presenter_sync_test.cpp
index 3834c5c08..5791ec184 100644
--- a/runtime/test/vk_presenter_sync_test.cpp
+++ b/runtime/test/vk_presenter_sync_test.cpp
@@ -346,6 +346,89 @@ int main() {
346 EXPECT(std::abs(r - 51) <= 2 && std::abs(g - 153) <= 2 && std::abs(b - 230) <= 2); 346 EXPECT(std::abs(r - 51) <= 2 && std::abs(g - 153) <= 2 && std::abs(b - 230) <= 2);
347 std::printf("presenter sync: capture-buffer WAW barriers (4/4) and read_back (%d,%d,%d) ok\n", r, g, b); 347 std::printf("presenter sync: capture-buffer WAW barriers (4/4) and read_back (%d,%d,%d) ok\n", r, g, b);
348 348
349 // 2b. A Present behind held work shows what that work draws (queue_holds.h). The render waits for a gate with
350 // no submitted Signal, so the queue holds it; the presents are queued behind it instead of blitting the
351 // back buffers as they were. Three presents queue up and keep their order: a blit, a blank one (reads
352 // nothing) and a composed one (present_planes), whose frame is the last one shown, so a reordering
353 // would end on the black frame.
354 {
355 VulkanFence gate(context, 0);
356 EXPECT(gate.semaphore() != VK_NULL_HANDLE);
357 const VkImage plane_img = d.image(VK_FORMAT_R8G8B8A8_UNORM, 32, 32, 1,
358 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
359 EXPECT(plane_img != VK_NULL_HANDLE);
360 ResourceBinding plane_rb = side_rb;
361 plane_rb.image = plane_img;
362 plane_rb.sampled = true;
363 context.add_resource(2, plane_rb, VK_IMAGE_LAYOUT_UNDEFINED);
364 CommandList red;
365 EXPECT(red.transition({1, 0, d3d12_state::common, d3d12_state::render_target}));
366 EXPECT(red.clear_render_target({1, 0, 0, 1}, {0.9f, 0.1f, 0.2f, 1.0f}));
367 EXPECT(red.transition({1, 0, d3d12_state::render_target, d3d12_state::common}));
368 EXPECT(red.transition({2, 0, d3d12_state::common, d3d12_state::render_target}));
369 EXPECT(red.clear_render_target({2, 0, 0, 1}, {0.2f, 0.8f, 0.4f, 1.0f}));
370 EXPECT(red.transition({2, 0, d3d12_state::render_target, d3d12_state::pixel_shader_resource}));
371 EXPECT(red.close());
372 const CommandList* ptr = &red;
373 queue.wait(gate.semaphore(), 1);
374 EXPECT(queue.execute({&ptr, 1}) == ReplayResult::success); // held
375 const auto center = [&](int& cr, int& cg, int& cb) {
376 std::vector<std::uint8_t> shot;
377 VkExtent2D e{};
378 VkFormat f{};
379 if (!presenter.read_back(shot, &e, &f)) return false;
380 const std::size_t at = (std::size_t(e.height / 2) * e.width + e.width / 2) * 4;
381 const bool bgr = (f == VK_FORMAT_B8G8R8A8_UNORM || f == VK_FORMAT_B8G8R8A8_SRGB);
382 cr = bgr ? shot[at + 2] : shot[at + 0];
383 cg = shot[at + 1];
384 cb = bgr ? shot[at + 0] : shot[at + 2];
385 return true;
386 };
387 const std::uint64_t shown = presenter.presented();
388 PresentPlanes planes;
389 planes.count = 1;
390 planes.plane[0].source = 2;
391 int cr = 0, cg = 0, cb = 0;
392 EXPECT(presenter.present(1, true) == VK_SUCCESS); // queued: returns at once
393 EXPECT(presenter.present_blank(true) == VK_SUCCESS); // queued behind the one before it
394 EXPECT(presenter.present_planes(planes, true) == VK_SUCCESS);
395 EXPECT(presenter.presented() == shown && !presenter.last_present_tore());
396 EXPECT(center(cr, cg, cb) && std::abs(cr - 51) <= 2 && std::abs(cg - 153) <= 2 && std::abs(cb - 230) <= 2);
397 EXPECT(gate.signal(1)); // releases the render, then the presents, in order, on this thread
398 EXPECT(queue.idle());
399 EXPECT(presenter.presented() == shown + 3 && presenter.composed_presents() >= 1);
400 // The composed frame (0.2, 0.8, 0.4 in the plane) is the last one shown; a blank last would be black.
401 EXPECT(center(cr, cg, cb) && std::abs(cr - 51) <= 12 && std::abs(cg - 204) <= 12 && std::abs(cb - 102) <= 12);
402 // The blit alone, with nothing held, is the plain path again and shows the red the render drew.
403 EXPECT(presenter.present(1, true) == VK_SUCCESS);
404 EXPECT(center(cr, cg, cb) && std::abs(cr - 230) <= 2 && std::abs(cg - 26) <= 2 && std::abs(cb - 51) <= 2);
405 std::printf("presenter sync: three Presents queued behind held work ran in order (%d,%d,%d)\n", cr, cg, cb);
406 context.remove_resource(2);
407 }
408
409 // 2c. A queue destroyed with held work lets the Presents queued behind it run (the work is dropped).
410 {
411 VulkanFence never(context, 0);
412 EXPECT(never.semaphore() != VK_NULL_HANDLE);
413 CommandList noop;
414 EXPECT(noop.transition({1, 0, d3d12_state::common, d3d12_state::render_target}));
415 EXPECT(noop.clear_render_target({1, 0, 0, 1}, {0.0f, 0.0f, 0.0f, 1.0f})); // never replayed
416 EXPECT(noop.transition({1, 0, d3d12_state::render_target, d3d12_state::common}));
417 EXPECT(noop.close());
418 const CommandList* ptr = &noop;
419 const std::uint64_t shown = presenter.presented();
420 {
421 VulkanQueue doomed(context, d.queue, d.family);
422 EXPECT(doomed.ok());
423 doomed.wait(never.semaphore(), 1);
424 EXPECT(doomed.execute({&ptr, 1}) == ReplayResult::success); // held for good
425 EXPECT(presenter.present(1, true) == VK_SUCCESS); // queued behind it
426 EXPECT(presenter.presented() == shown);
427 }
428 EXPECT(presenter.presented() == shown + 1);
429 std::printf("presenter sync: Present queued behind a destroyed queue's held work ran\n");
430 }
431
349 // 3. Concurrent present() + VulkanQueue::execute() + add/remove_resource() hammering LayoutTracker. 432 // 3. Concurrent present() + VulkanQueue::execute() + add/remove_resource() hammering LayoutTracker.
350 std::atomic<bool> stop{false}; 433 std::atomic<bool> stop{false};
351 std::atomic<bool> worker_failed{false}; 434 std::atomic<bool> worker_failed{false};
diff --git a/runtime/test/vk_queue_query_sync_test.cpp b/runtime/test/vk_queue_query_sync_test.cpp
index a03e369b9..49f4015c8 100644
--- a/runtime/test/vk_queue_query_sync_test.cpp
+++ b/runtime/test/vk_queue_query_sync_test.cpp
@@ -291,6 +291,73 @@ int main() {
291 std::printf("queue/query sync: pending Wait() preserved across failed vkQueueSubmit ok\n"); 291 std::printf("queue/query sync: pending Wait() preserved across failed vkQueueSubmit ok\n");
292 } 292 }
293 293
294 // 3b. The same for a batch held behind a Wait with no submitted Signal (queue_holds.h): its submission
295 // fails when the CPU Signal releases it, the failure is reported through take_held_failure(), and its
296 // waits stay for the next submission, as when the call is not held. A Signal queued behind the failed
297 // batch still runs.
298 {
299 VulkanFence gate(context, 0), after(context, 0);
300 EXPECT(gate.semaphore() != VK_NULL_HANDLE && after.semaphore() != VK_NULL_HANDLE);
301 const std::uint64_t pattern = 0x0badf00dcafe1234ULL;
302 std::memcpy(src_ptr, &pattern, sizeof(pattern));
303 std::memset(dst_ptr, 0, sizeof(pattern));
304 CommandList copy_list;
305 EXPECT(copy_list.copy_buffer({2, 0, 1, 0, sizeof(pattern)}));
306 EXPECT(copy_list.close());
307 const CommandList* ptr = &copy_list;
308
309 queue_a.wait(gate.semaphore(), 1);
310 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::success); // held: the Signal is not submitted yet
311 EXPECT(queue_a.signal(after.semaphore(), 1)); // held behind it
312 EXPECT(after.completed() == 0 && queue_a.take_held_failure() == ReplayResult::success);
313 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
314 EXPECT(gate.signal(1)); // releases the batch on this thread
315 EXPECT(queue_a.take_held_failure() == ReplayResult::unsupported);
316 EXPECT(queue_a.take_held_failure() == ReplayResult::success); // reported once
317 EXPECT(queue_a.idle() && after.completed() == 1); // the Signal behind it still signaled
318
319 driver::captured_wait_count.store(0);
320 driver::captured_wait_sem.store(0);
321 driver::captured_wait_val.store(0);
322 driver::capture_next_waits.store(true);
323 EXPECT(queue_a.execute({&ptr, 1}) == ReplayResult::success);
324 EXPECT(queue_a.idle());
325 EXPECT(driver::captured_wait_count.load() == 1); // the failed batch's wait on (gate, 1) came along
326 EXPECT(driver::captured_wait_sem.load() == reinterpret_cast<std::uintptr_t>(gate.semaphore()));
327 EXPECT(driver::captured_wait_val.load() == 1);
328 std::uint64_t got = 0;
329 std::memcpy(&got, dst_ptr, sizeof(got));
330 EXPECT(got == pattern);
331 std::printf("queue/query sync: failed held batch reported, its wait kept for the retry, Signal behind it ran\n");
332 }
333
334 // 3c. A Signal whose vkQueueSubmit fails signals nothing: a queue waiting for it stays held (the value is not
335 // counted as submitted), and the application's retry of the Signal goes through and releases it.
336 {
337 VulkanFence fence(context, 0);
338 EXPECT(fence.semaphore() != VK_NULL_HANDLE);
339 const std::uint64_t pattern = 0x5ca1ab1e0ddba11ULL;
340 std::memcpy(src_ptr, &pattern, sizeof(pattern));
341 std::memset(dst_ptr, 0, sizeof(pattern));
342 CommandList copy_list;
343 EXPECT(copy_list.copy_buffer({2, 0, 1, 0, sizeof(pattern)}));
344 EXPECT(copy_list.close());
345 const CommandList* ptr = &copy_list;
346 queue_b.wait(fence.semaphore(), 1);
347 EXPECT(queue_b.execute({&ptr, 1}) == ReplayResult::success); // held for the Signal
348 driver::fail_next_submit.store(VK_ERROR_OUT_OF_HOST_MEMORY);
349 EXPECT(!queue_a.signal(fence.semaphore(), 1)); // the submit fails
350 EXPECT(queue_b.idle() && fence.completed() == 0);
351 std::uint64_t got = 1;
352 std::memcpy(&got, dst_ptr, sizeof(got));
353 EXPECT(got == 0); // the waiter did not run
354 EXPECT(queue_a.signal(fence.semaphore(), 1)); // the retry signals, and releases it
355 EXPECT(queue_b.idle() && queue_a.idle() && fence.completed() == 1);
356 std::memcpy(&got, dst_ptr, sizeof(got));
357 EXPECT(got == pattern);
358 std::printf("queue/query sync: a failed Signal does not release its waiters; the retry does\n");
359 }
360
294 // 4. Concurrent multi-queue EndQuery + ResolveQueries + temporary query pool add/remove stress. 361 // 4. Concurrent multi-queue EndQuery + ResolveQueries + temporary query pool add/remove stress.
295 // Each iteration uses a distinct query slot so no slot is reset while another submission resolves it. 362 // Each iteration uses a distinct query slot so no slot is reset while another submission resolves it.
296 { 363 {