upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/src
diff options
context:
space:
mode:
Diffstat (limited to 'runtime/src')
-rw-r--r--runtime/src/queue_holds.h122
-rw-r--r--runtime/src/vulkan_backend.h219
-rw-r--r--runtime/src/vulkan_present.h125
3 files changed, 391 insertions, 75 deletions
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_;