blob: da6599a9795497aeaa38778ff5df077e377f4473 [file] [log] [blame]
Jeremy Gebben4d51c552022-01-06 21:27:15 -07001/* Copyright (c) 2019-2022 The Khronos Group Inc.
2 * Copyright (c) 2019-2022 Valve Corporation
3 * Copyright (c) 2019-2022 LunarG, Inc.
John Zulauf9cb530d2019-09-30 14:14:10 -06004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author: John Zulauf <jzulauf@lunarg.com>
John Zulaufab7756b2020-12-29 16:10:16 -070018 * Author: Locke Lin <locke@lunarg.com>
19 * Author: Jeremy Gebben <jeremyg@lunarg.com>
John Zulauf9cb530d2019-09-30 14:14:10 -060020 */
21
22#include <limits>
23#include <vector>
locke-lunarg296a3c92020-03-25 01:04:29 -060024#include <memory>
25#include <bitset>
John Zulauf9cb530d2019-09-30 14:14:10 -060026#include "synchronization_validation.h"
Jeremy Gebben5f585ae2021-02-02 09:03:06 -070027#include "sync_utils.h"
John Zulauf9cb530d2019-09-30 14:14:10 -060028
John Zulaufea943c52022-02-22 11:05:17 -070029// Utilities to DRY up Get... calls
30template <typename Map, typename Key = typename Map::key_type, typename RetVal = layer_data::optional<typename Map::mapped_type>>
31RetVal GetMappedOptional(const Map &map, const Key &key) {
32 RetVal ret_val;
33 auto it = map.find(key);
34 if (it != map.cend()) {
35 ret_val.emplace(it->second);
36 }
37 return ret_val;
38}
39template <typename Map, typename Fn>
40typename Map::mapped_type GetMapped(const Map &map, const typename Map::key_type &key, Fn &&default_factory) {
41 auto value = GetMappedOptional(map, key);
42 return (value) ? *value : default_factory();
43}
44
45template <typename Map, typename Fn>
John Zulauf397e68b2022-04-19 11:44:07 -060046typename Map::mapped_type GetMappedInsert(Map &map, const typename Map::key_type &key, Fn &&emplace_factory) {
John Zulaufea943c52022-02-22 11:05:17 -070047 auto value = GetMappedOptional(map, key);
48 if (value) {
49 return *value;
50 }
John Zulauf397e68b2022-04-19 11:44:07 -060051 auto insert_it = map.emplace(std::make_pair(key, emplace_factory()));
John Zulaufea943c52022-02-22 11:05:17 -070052 assert(insert_it.second);
53
54 return insert_it.first->second;
55}
56
57template <typename Map, typename Key = typename Map::key_type, typename Mapped = typename Map::mapped_type,
58 typename Value = typename Mapped::element_type>
59Value *GetMappedPlainFromShared(const Map &map, const Key &key) {
60 auto value = GetMappedOptional<Map, Key>(map, key);
61 if (value) return value->get();
62 return nullptr;
63}
64
Jeremy Gebben6fbf8242021-06-21 09:14:46 -060065static bool SimpleBinding(const BINDABLE &bindable) { return !bindable.sparse && bindable.Binding(); }
John Zulauf264cce02021-02-05 14:40:47 -070066
John Zulauf29d00532021-03-04 13:28:54 -070067static bool SimpleBinding(const IMAGE_STATE &image_state) {
Jeremy Gebben62c3bf42021-07-21 15:38:24 -060068 bool simple =
Jeremy Gebben82e11d52021-07-26 09:19:37 -060069 SimpleBinding(static_cast<const BINDABLE &>(image_state)) || image_state.IsSwapchainImage() || image_state.bind_swapchain;
John Zulauf29d00532021-03-04 13:28:54 -070070
71 // If it's not simple we must have an encoder.
72 assert(!simple || image_state.fragment_encoder.get());
73 return simple;
74}
75
John Zulauf4fa68462021-04-26 21:04:22 -060076static const ResourceAccessRange kFullRange(std::numeric_limits<VkDeviceSize>::min(), std::numeric_limits<VkDeviceSize>::max());
77static const std::array<AccessAddressType, static_cast<size_t>(AccessAddressType::kTypeCount)> kAddressTypes = {
John Zulauf43cc7462020-12-03 12:33:12 -070078 AccessAddressType::kLinear, AccessAddressType::kIdealized};
79
John Zulaufd5115702021-01-18 12:34:33 -070080static constexpr AccessAddressType GetAccessAddressType(const BUFFER_STATE &) { return AccessAddressType::kLinear; };
John Zulauf264cce02021-02-05 14:40:47 -070081static AccessAddressType GetAccessAddressType(const IMAGE_STATE &image) {
82 return SimpleBinding(image) ? AccessContext::ImageAddressType(image) : AccessAddressType::kIdealized;
83}
John Zulaufd5115702021-01-18 12:34:33 -070084
John Zulauf9cb530d2019-09-30 14:14:10 -060085static const char *string_SyncHazardVUID(SyncHazard hazard) {
86 switch (hazard) {
87 case SyncHazard::NONE:
John Zulauf2f952d22020-02-10 11:34:51 -070088 return "SYNC-HAZARD-NONE";
John Zulauf9cb530d2019-09-30 14:14:10 -060089 break;
90 case SyncHazard::READ_AFTER_WRITE:
91 return "SYNC-HAZARD-READ_AFTER_WRITE";
92 break;
93 case SyncHazard::WRITE_AFTER_READ:
94 return "SYNC-HAZARD-WRITE_AFTER_READ";
95 break;
96 case SyncHazard::WRITE_AFTER_WRITE:
97 return "SYNC-HAZARD-WRITE_AFTER_WRITE";
98 break;
John Zulauf2f952d22020-02-10 11:34:51 -070099 case SyncHazard::READ_RACING_WRITE:
100 return "SYNC-HAZARD-READ-RACING-WRITE";
101 break;
102 case SyncHazard::WRITE_RACING_WRITE:
103 return "SYNC-HAZARD-WRITE-RACING-WRITE";
104 break;
105 case SyncHazard::WRITE_RACING_READ:
106 return "SYNC-HAZARD-WRITE-RACING-READ";
107 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600108 default:
109 assert(0);
110 }
111 return "SYNC-HAZARD-INVALID";
112}
113
John Zulauf59e25072020-07-17 10:55:21 -0600114static bool IsHazardVsRead(SyncHazard hazard) {
115 switch (hazard) {
116 case SyncHazard::NONE:
117 return false;
118 break;
119 case SyncHazard::READ_AFTER_WRITE:
120 return false;
121 break;
122 case SyncHazard::WRITE_AFTER_READ:
123 return true;
124 break;
125 case SyncHazard::WRITE_AFTER_WRITE:
126 return false;
127 break;
128 case SyncHazard::READ_RACING_WRITE:
129 return false;
130 break;
131 case SyncHazard::WRITE_RACING_WRITE:
132 return false;
133 break;
134 case SyncHazard::WRITE_RACING_READ:
135 return true;
136 break;
137 default:
138 assert(0);
139 }
140 return false;
141}
142
John Zulauf9cb530d2019-09-30 14:14:10 -0600143static const char *string_SyncHazard(SyncHazard hazard) {
144 switch (hazard) {
145 case SyncHazard::NONE:
146 return "NONR";
147 break;
148 case SyncHazard::READ_AFTER_WRITE:
149 return "READ_AFTER_WRITE";
150 break;
151 case SyncHazard::WRITE_AFTER_READ:
152 return "WRITE_AFTER_READ";
153 break;
154 case SyncHazard::WRITE_AFTER_WRITE:
155 return "WRITE_AFTER_WRITE";
156 break;
John Zulauf2f952d22020-02-10 11:34:51 -0700157 case SyncHazard::READ_RACING_WRITE:
158 return "READ_RACING_WRITE";
159 break;
160 case SyncHazard::WRITE_RACING_WRITE:
161 return "WRITE_RACING_WRITE";
162 break;
163 case SyncHazard::WRITE_RACING_READ:
164 return "WRITE_RACING_READ";
165 break;
John Zulauf9cb530d2019-09-30 14:14:10 -0600166 default:
167 assert(0);
168 }
169 return "INVALID HAZARD";
170}
171
John Zulauf37ceaed2020-07-03 16:18:15 -0600172static const SyncStageAccessInfoType *SyncStageAccessInfoFromMask(SyncStageAccessFlags flags) {
173 // Return the info for the first bit found
174 const SyncStageAccessInfoType *info = nullptr;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700175 for (size_t i = 0; i < flags.size(); i++) {
176 if (flags.test(i)) {
177 info = &syncStageAccessInfoByStageAccessIndex[i];
178 break;
John Zulauf37ceaed2020-07-03 16:18:15 -0600179 }
180 }
181 return info;
182}
183
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700184static std::string string_SyncStageAccessFlags(const SyncStageAccessFlags &flags, const char *sep = "|") {
John Zulauf59e25072020-07-17 10:55:21 -0600185 std::string out_str;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700186 if (flags.none()) {
John Zulauf389c34b2020-07-28 11:19:35 -0600187 out_str = "0";
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700188 } else {
189 for (size_t i = 0; i < syncStageAccessInfoByStageAccessIndex.size(); i++) {
190 const auto &info = syncStageAccessInfoByStageAccessIndex[i];
191 if ((flags & info.stage_access_bit).any()) {
192 if (!out_str.empty()) {
193 out_str.append(sep);
194 }
195 out_str.append(info.name);
John Zulauf59e25072020-07-17 10:55:21 -0600196 }
John Zulauf59e25072020-07-17 10:55:21 -0600197 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700198 if (out_str.length() == 0) {
199 out_str.append("Unhandled SyncStageAccess");
200 }
John Zulauf59e25072020-07-17 10:55:21 -0600201 }
202 return out_str;
203}
204
John Zulauf397e68b2022-04-19 11:44:07 -0600205std::ostream &operator<<(std::ostream &out, const ResourceUsageRecord &record) {
206 out << "command: " << CommandTypeString(record.command);
207 out << ", seq_no: " << record.seq_num;
208 if (record.sub_command != 0) {
209 out << ", subcmd: " << record.sub_command;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700210 }
John Zulauf397e68b2022-04-19 11:44:07 -0600211 return out;
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700212}
John Zulauf397e68b2022-04-19 11:44:07 -0600213
John Zulauf4fa68462021-04-26 21:04:22 -0600214static std::string string_UsageIndex(SyncStageAccessIndex usage_index) {
215 const char *stage_access_name = "INVALID_STAGE_ACCESS";
216 if (usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size())) {
217 stage_access_name = syncStageAccessInfoByStageAccessIndex[usage_index].name;
218 }
219 return std::string(stage_access_name);
220}
221
John Zulauf397e68b2022-04-19 11:44:07 -0600222struct SyncNodeFormatter {
223 const debug_report_data *report_data;
224 const BASE_NODE *node;
225 const char *label;
226
227 SyncNodeFormatter(const SyncValidator &sync_state, const CMD_BUFFER_STATE *cb_state)
228 : report_data(sync_state.report_data), node(cb_state), label("command_buffer") {}
229 SyncNodeFormatter(const SyncValidator &sync_state, const QUEUE_STATE *q_state)
230 : report_data(sync_state.report_data), node(q_state), label("queue") {}
231};
232
233std::ostream &operator<<(std::ostream &out, const SyncNodeFormatter &formater) {
234 if (formater.node) {
235 out << ", " << formater.label << ": " << formater.report_data->FormatHandle(formater.node->Handle()).c_str();
236 if (formater.node->Destroyed()) {
237 out << " (destroyed)";
238 }
239 } else {
240 out << ", " << formater.label << ": null handle";
241 }
242 return out;
243}
244
245std::ostream &operator<<(std::ostream &out, const HazardResult &hazard) {
246 assert(hazard.usage_index < static_cast<SyncStageAccessIndex>(syncStageAccessInfoByStageAccessIndex.size()));
247 const auto &usage_info = syncStageAccessInfoByStageAccessIndex[hazard.usage_index];
248 const auto *info = SyncStageAccessInfoFromMask(hazard.prior_access);
249 const char *stage_access_name = info ? info->name : "INVALID_STAGE_ACCESS";
250 out << "(";
251 if (!hazard.recorded_access.get()) {
252 // if we have a recorded usage the usage is reported from the recorded contexts point of view
253 out << "usage: " << usage_info.name << ", ";
254 }
255 out << "prior_usage: " << stage_access_name;
256 if (IsHazardVsRead(hazard.hazard)) {
257 const auto barriers = hazard.access_state->GetReadBarriers(hazard.prior_access);
258 out << ", read_barriers: " << string_VkPipelineStageFlags2KHR(barriers);
259 } else {
260 SyncStageAccessFlags write_barrier = hazard.access_state->GetWriteBarriers();
261 out << ", write_barriers: " << string_SyncStageAccessFlags(write_barrier);
262 }
263 return out;
264}
265
John Zulauf4fa68462021-04-26 21:04:22 -0600266struct NoopBarrierAction {
267 explicit NoopBarrierAction() {}
268 void operator()(ResourceAccessState *access) const {}
John Zulauf5c628d02021-05-04 15:46:36 -0600269 const bool layout_transition = false;
John Zulauf4fa68462021-04-26 21:04:22 -0600270};
271
272// NOTE: Make sure the proxy doesn't outlive from, as the proxy is pointing directly to access contexts owned by from.
273CommandBufferAccessContext::CommandBufferAccessContext(const CommandBufferAccessContext &from, AsProxyContext dummy)
274 : CommandBufferAccessContext(from.sync_state_) {
275 // Copy only the needed fields out of from for a temporary, proxy command buffer context
276 cb_state_ = from.cb_state_;
277 queue_flags_ = from.queue_flags_;
278 destroyed_ = from.destroyed_;
279 access_log_ = from.access_log_; // potentially large, but no choice given tagging lookup.
280 command_number_ = from.command_number_;
281 subcommand_number_ = from.subcommand_number_;
282 reset_count_ = from.reset_count_;
283
284 const auto *from_context = from.GetCurrentAccessContext();
285 assert(from_context);
286
287 // Construct a fully resolved single access context out of from
288 const NoopBarrierAction noop_barrier;
289 for (AccessAddressType address_type : kAddressTypes) {
290 from_context->ResolveAccessRange(address_type, kFullRange, noop_barrier,
291 &cb_access_context_.GetAccessStateMap(address_type), nullptr);
292 }
293 // The proxy has flatten the current render pass context (if any), but the async contexts are needed for hazard detection
294 cb_access_context_.ImportAsyncContexts(*from_context);
295
296 events_context_ = from.events_context_;
297
298 // We don't want to copy the full render_pass_context_ history just for the proxy.
299}
300
301std::string CommandBufferAccessContext::FormatUsage(const ResourceUsageTag tag) const {
John Zulauf397e68b2022-04-19 11:44:07 -0600302 if (tag >= access_log_.size()) return std::string();
303
John Zulauf4fa68462021-04-26 21:04:22 -0600304 std::stringstream out;
305 assert(tag < access_log_.size());
306 const auto &record = access_log_[tag];
John Zulauf397e68b2022-04-19 11:44:07 -0600307 out << record;
308 if (cb_state_.get() != record.cb_state) {
309 out << SyncNodeFormatter(*sync_state_, record.cb_state);
John Zulauf4fa68462021-04-26 21:04:22 -0600310 }
John Zulaufd142c9a2022-04-12 14:22:44 -0600311 out << ", reset_no: " << std::to_string(record.reset_count);
John Zulauf4fa68462021-04-26 21:04:22 -0600312 return out.str();
313}
John Zulauf397e68b2022-04-19 11:44:07 -0600314
John Zulauf4fa68462021-04-26 21:04:22 -0600315std::string CommandBufferAccessContext::FormatUsage(const ResourceFirstAccess &access) const {
316 std::stringstream out;
317 out << "(recorded_usage: " << string_UsageIndex(access.usage_index);
318 out << ", " << FormatUsage(access.tag) << ")";
319 return out.str();
320}
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -0700321
John Zulauf397e68b2022-04-19 11:44:07 -0600322std::string CommandExecutionContext::FormatHazard(const HazardResult &hazard) const {
John Zulauf1dae9192020-06-16 15:46:44 -0600323 std::stringstream out;
John Zulauf397e68b2022-04-19 11:44:07 -0600324 out << hazard;
325 out << ", " << FormatUsage(hazard.tag) << ")";
John Zulauf1dae9192020-06-16 15:46:44 -0600326 return out.str();
327}
328
John Zulauf0223f142022-07-06 09:05:39 -0600329bool CommandExecutionContext::ValidForSyncOps() const {
330 bool valid = GetCurrentEventsContext() && GetCurrentAccessContext();
331 assert(valid);
332 return valid;
333}
334
John Zulaufd14743a2020-07-03 09:42:39 -0600335// NOTE: the attachement read flag is put *only* in the access scope and not in the exect scope, since the ordering
336// rules apply only to this specific access for this stage, and not the stage as a whole. The ordering detection
337// also reflects this special case for read hazard detection (using access instead of exec scope)
Jeremy Gebben40a22942020-12-22 14:22:06 -0700338static constexpr VkPipelineStageFlags2KHR kColorAttachmentExecScope = VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700339static const SyncStageAccessFlags kColorAttachmentAccessScope =
340 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_BIT |
341 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT |
342 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE_BIT |
343 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebben40a22942020-12-22 14:22:06 -0700344static constexpr VkPipelineStageFlags2KHR kDepthStencilAttachmentExecScope =
345 VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT_KHR | VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT_KHR;
Jeremy Gebbend0de1f82020-11-09 08:21:07 -0700346static const SyncStageAccessFlags kDepthStencilAttachmentAccessScope =
347 SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
348 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
349 SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT; // Note: this is intentionally not in the exec scope
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -0700350static constexpr VkPipelineStageFlags2KHR kRasterAttachmentExecScope = kDepthStencilAttachmentExecScope | kColorAttachmentExecScope;
John Zulauf8e3c3e92021-01-06 11:19:36 -0700351static const SyncStageAccessFlags kRasterAttachmentAccessScope = kDepthStencilAttachmentAccessScope | kColorAttachmentAccessScope;
John Zulaufb027cdb2020-05-21 14:25:22 -0600352
John Zulauf8e3c3e92021-01-06 11:19:36 -0700353ResourceAccessState::OrderingBarriers ResourceAccessState::kOrderingRules = {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700354 {{VK_PIPELINE_STAGE_2_NONE_KHR, SyncStageAccessFlags()},
John Zulauf8e3c3e92021-01-06 11:19:36 -0700355 {kColorAttachmentExecScope, kColorAttachmentAccessScope},
356 {kDepthStencilAttachmentExecScope, kDepthStencilAttachmentAccessScope},
357 {kRasterAttachmentExecScope, kRasterAttachmentAccessScope}}};
358
John Zulaufee984022022-04-13 16:39:50 -0600359// Sometimes we have an internal access conflict, and we using the kInvalidTag to set and detect in temporary/proxy contexts
360static const ResourceUsageTag kInvalidTag(ResourceUsageRecord::kMaxIndex);
John Zulaufb027cdb2020-05-21 14:25:22 -0600361
Jeremy Gebben62c3bf42021-07-21 15:38:24 -0600362static VkDeviceSize ResourceBaseAddress(const BINDABLE &bindable) { return bindable.GetFakeBaseAddress(); }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600363
John Zulaufcb7e1672022-05-04 13:46:08 -0600364VkDeviceSize GetRealWholeSize(VkDeviceSize offset, VkDeviceSize size, VkDeviceSize whole_size) {
locke-lunarg3c038002020-04-30 23:08:08 -0600365 if (size == VK_WHOLE_SIZE) {
366 return (whole_size - offset);
367 }
368 return size;
369}
370
John Zulauf3e86bf02020-09-12 10:47:57 -0600371static inline VkDeviceSize GetBufferWholeSize(const BUFFER_STATE &buf_state, VkDeviceSize offset, VkDeviceSize size) {
372 return GetRealWholeSize(offset, size, buf_state.createInfo.size);
373}
374
John Zulauf16adfc92020-04-08 10:28:33 -0600375template <typename T>
John Zulauf355e49b2020-04-24 15:11:15 -0600376static ResourceAccessRange MakeRange(const T &has_offset_and_size) {
John Zulauf16adfc92020-04-08 10:28:33 -0600377 return ResourceAccessRange(has_offset_and_size.offset, (has_offset_and_size.offset + has_offset_and_size.size));
378}
379
John Zulauf355e49b2020-04-24 15:11:15 -0600380static ResourceAccessRange MakeRange(VkDeviceSize start, VkDeviceSize size) { return ResourceAccessRange(start, (start + size)); }
John Zulauf16adfc92020-04-08 10:28:33 -0600381
John Zulauf3e86bf02020-09-12 10:47:57 -0600382static inline ResourceAccessRange MakeRange(const BUFFER_STATE &buffer, VkDeviceSize offset, VkDeviceSize size) {
383 return MakeRange(offset, GetBufferWholeSize(buffer, offset, size));
384}
385
386static inline ResourceAccessRange MakeRange(const BUFFER_VIEW_STATE &buf_view_state) {
387 return MakeRange(*buf_view_state.buffer_state.get(), buf_view_state.create_info.offset, buf_view_state.create_info.range);
388}
389
John Zulauf4a6105a2020-11-17 15:11:05 -0700390// Range generators for to allow event scope filtration to be limited to the top of the resource access traversal pipeline
391//
John Zulauf10f1f522020-12-18 12:00:35 -0700392// Note: there is no "begin/end" or reset facility. These are each written as "one time through" generators.
393//
John Zulauf4a6105a2020-11-17 15:11:05 -0700394// Usage:
395// Constructor() -- initializes the generator to point to the begin of the space declared.
396// * -- the current range of the generator empty signfies end
397// ++ -- advance to the next non-empty range (or end)
398
399// A wrapper for a single range with the same semantics as the actual generators below
400template <typename KeyType>
401class SingleRangeGenerator {
402 public:
403 SingleRangeGenerator(const KeyType &range) : current_(range) {}
John Zulaufd5115702021-01-18 12:34:33 -0700404 const KeyType &operator*() const { return current_; }
405 const KeyType *operator->() const { return &current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700406 SingleRangeGenerator &operator++() {
407 current_ = KeyType(); // just one real range
408 return *this;
409 }
410
411 bool operator==(const SingleRangeGenerator &other) const { return current_ == other.current_; }
412
413 private:
414 SingleRangeGenerator() = default;
415 const KeyType range_;
416 KeyType current_;
417};
418
John Zulaufae842002021-04-15 18:20:55 -0600419// Generate the ranges that are the intersection of range and the entries in the RangeMap
420template <typename RangeMap, typename KeyType = typename RangeMap::key_type>
421class MapRangesRangeGenerator {
John Zulauf4a6105a2020-11-17 15:11:05 -0700422 public:
John Zulaufd5115702021-01-18 12:34:33 -0700423 // Default constructed is safe to dereference for "empty" test, but for no other operation.
John Zulaufae842002021-04-15 18:20:55 -0600424 MapRangesRangeGenerator() : range_(), map_(nullptr), map_pos_(), current_() {
John Zulaufd5115702021-01-18 12:34:33 -0700425 // Default construction for KeyType *must* be empty range
426 assert(current_.empty());
427 }
John Zulaufae842002021-04-15 18:20:55 -0600428 MapRangesRangeGenerator(const RangeMap &filter, const KeyType &range) : range_(range), map_(&filter), map_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700429 SeekBegin();
430 }
John Zulaufae842002021-04-15 18:20:55 -0600431 MapRangesRangeGenerator(const MapRangesRangeGenerator &from) = default;
John Zulaufd5115702021-01-18 12:34:33 -0700432
John Zulauf4a6105a2020-11-17 15:11:05 -0700433 const KeyType &operator*() const { return current_; }
434 const KeyType *operator->() const { return &current_; }
John Zulaufae842002021-04-15 18:20:55 -0600435 MapRangesRangeGenerator &operator++() {
436 ++map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700437 UpdateCurrent();
438 return *this;
439 }
440
John Zulaufae842002021-04-15 18:20:55 -0600441 bool operator==(const MapRangesRangeGenerator &other) const { return current_ == other.current_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700442
John Zulaufae842002021-04-15 18:20:55 -0600443 protected:
John Zulauf4a6105a2020-11-17 15:11:05 -0700444 void UpdateCurrent() {
John Zulaufae842002021-04-15 18:20:55 -0600445 if (map_pos_ != map_->cend()) {
446 current_ = range_ & map_pos_->first;
John Zulauf4a6105a2020-11-17 15:11:05 -0700447 } else {
448 current_ = KeyType();
449 }
450 }
451 void SeekBegin() {
John Zulaufae842002021-04-15 18:20:55 -0600452 map_pos_ = map_->lower_bound(range_);
John Zulauf4a6105a2020-11-17 15:11:05 -0700453 UpdateCurrent();
454 }
John Zulaufae842002021-04-15 18:20:55 -0600455
456 // Adding this functionality here, to avoid gratuitous Base:: qualifiers in the derived class
457 // Note: Not exposed in this classes public interface to encourage using a consistent ++/empty generator semantic
458 template <typename Pred>
459 MapRangesRangeGenerator &PredicatedIncrement(Pred &pred) {
460 do {
461 ++map_pos_;
462 } while (map_pos_ != map_->cend() && map_pos_->first.intersects(range_) && !pred(map_pos_));
463 UpdateCurrent();
464 return *this;
465 }
466
John Zulauf4a6105a2020-11-17 15:11:05 -0700467 const KeyType range_;
John Zulaufae842002021-04-15 18:20:55 -0600468 const RangeMap *map_;
469 typename RangeMap::const_iterator map_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700470 KeyType current_;
471};
John Zulaufd5115702021-01-18 12:34:33 -0700472using SingleAccessRangeGenerator = SingleRangeGenerator<ResourceAccessRange>;
John Zulaufae842002021-04-15 18:20:55 -0600473using EventSimpleRangeGenerator = MapRangesRangeGenerator<SyncEventState::ScopeMap>;
John Zulauf4a6105a2020-11-17 15:11:05 -0700474
John Zulaufae842002021-04-15 18:20:55 -0600475// Generate the ranges for entries meeting the predicate that are the intersection of range and the entries in the RangeMap
476template <typename RangeMap, typename Predicate, typename KeyType = typename RangeMap::key_type>
477class PredicatedMapRangesRangeGenerator : public MapRangesRangeGenerator<RangeMap, KeyType> {
478 public:
479 using Base = MapRangesRangeGenerator<RangeMap, KeyType>;
480 // Default constructed is safe to dereference for "empty" test, but for no other operation.
481 PredicatedMapRangesRangeGenerator() : Base(), pred_() {}
482 PredicatedMapRangesRangeGenerator(const RangeMap &filter, const KeyType &range, Predicate pred)
483 : Base(filter, range), pred_(pred) {}
484 PredicatedMapRangesRangeGenerator(const PredicatedMapRangesRangeGenerator &from) = default;
485
486 PredicatedMapRangesRangeGenerator &operator++() {
487 Base::PredicatedIncrement(pred_);
488 return *this;
489 }
490
491 protected:
492 Predicate pred_;
493};
John Zulauf4a6105a2020-11-17 15:11:05 -0700494
495// Generate the ranges that are the intersection of the RangeGen ranges and the entries in the FilterMap
John Zulaufae842002021-04-15 18:20:55 -0600496// Templated to allow for different Range generators or map sources...
497template <typename RangeMap, typename RangeGen, typename KeyType = typename RangeMap::key_type>
John Zulauf4a6105a2020-11-17 15:11:05 -0700498class FilteredGeneratorGenerator {
499 public:
John Zulaufd5115702021-01-18 12:34:33 -0700500 // Default constructed is safe to dereference for "empty" test, but for no other operation.
501 FilteredGeneratorGenerator() : filter_(nullptr), gen_(), filter_pos_(), current_() {
502 // Default construction for KeyType *must* be empty range
503 assert(current_.empty());
504 }
John Zulaufae842002021-04-15 18:20:55 -0600505 FilteredGeneratorGenerator(const RangeMap &filter, RangeGen &gen) : filter_(&filter), gen_(gen), filter_pos_(), current_() {
John Zulauf4a6105a2020-11-17 15:11:05 -0700506 SeekBegin();
507 }
John Zulaufd5115702021-01-18 12:34:33 -0700508 FilteredGeneratorGenerator(const FilteredGeneratorGenerator &from) = default;
John Zulauf4a6105a2020-11-17 15:11:05 -0700509 const KeyType &operator*() const { return current_; }
510 const KeyType *operator->() const { return &current_; }
511 FilteredGeneratorGenerator &operator++() {
512 KeyType gen_range = GenRange();
513 KeyType filter_range = FilterRange();
514 current_ = KeyType();
515 while (gen_range.non_empty() && filter_range.non_empty() && current_.empty()) {
516 if (gen_range.end > filter_range.end) {
517 // if the generated range is beyond the filter_range, advance the filter range
518 filter_range = AdvanceFilter();
519 } else {
520 gen_range = AdvanceGen();
521 }
522 current_ = gen_range & filter_range;
523 }
524 return *this;
525 }
526
527 bool operator==(const FilteredGeneratorGenerator &other) const { return current_ == other.current_; }
528
529 private:
530 KeyType AdvanceFilter() {
531 ++filter_pos_;
532 auto filter_range = FilterRange();
533 if (filter_range.valid()) {
534 FastForwardGen(filter_range);
535 }
536 return filter_range;
537 }
538 KeyType AdvanceGen() {
John Zulaufd5115702021-01-18 12:34:33 -0700539 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700540 auto gen_range = GenRange();
541 if (gen_range.valid()) {
542 FastForwardFilter(gen_range);
543 }
544 return gen_range;
545 }
546
547 KeyType FilterRange() const { return (filter_pos_ != filter_->cend()) ? filter_pos_->first : KeyType(); }
John Zulaufd5115702021-01-18 12:34:33 -0700548 KeyType GenRange() const { return *gen_; }
John Zulauf4a6105a2020-11-17 15:11:05 -0700549
550 KeyType FastForwardFilter(const KeyType &range) {
551 auto filter_range = FilterRange();
552 int retry_count = 0;
John Zulauf10f1f522020-12-18 12:00:35 -0700553 const static int kRetryLimit = 2; // TODO -- determine whether this limit is optimal
John Zulauf4a6105a2020-11-17 15:11:05 -0700554 while (!filter_range.empty() && (filter_range.end <= range.begin)) {
555 if (retry_count < kRetryLimit) {
556 ++filter_pos_;
557 filter_range = FilterRange();
558 retry_count++;
559 } else {
560 // Okay we've tried walking, do a seek.
561 filter_pos_ = filter_->lower_bound(range);
562 break;
563 }
564 }
565 return FilterRange();
566 }
567
568 // TODO: Consider adding "seek" (or an absolute bound "get" to range generators to make this walk
569 // faster.
570 KeyType FastForwardGen(const KeyType &range) {
571 auto gen_range = GenRange();
572 while (!gen_range.empty() && (gen_range.end <= range.begin)) {
John Zulaufd5115702021-01-18 12:34:33 -0700573 ++gen_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700574 gen_range = GenRange();
575 }
576 return gen_range;
577 }
578
579 void SeekBegin() {
580 auto gen_range = GenRange();
581 if (gen_range.empty()) {
582 current_ = KeyType();
583 filter_pos_ = filter_->cend();
584 } else {
585 filter_pos_ = filter_->lower_bound(gen_range);
586 current_ = gen_range & FilterRange();
587 }
588 }
589
John Zulaufae842002021-04-15 18:20:55 -0600590 const RangeMap *filter_;
John Zulaufd5115702021-01-18 12:34:33 -0700591 RangeGen gen_;
John Zulaufae842002021-04-15 18:20:55 -0600592 typename RangeMap::const_iterator filter_pos_;
John Zulauf4a6105a2020-11-17 15:11:05 -0700593 KeyType current_;
594};
595
596using EventImageRangeGenerator = FilteredGeneratorGenerator<SyncEventState::ScopeMap, subresource_adapter::ImageRangeGenerator>;
597
John Zulauf5c5e88d2019-12-26 11:22:02 -0700598
John Zulauf3e86bf02020-09-12 10:47:57 -0600599ResourceAccessRange GetBufferRange(VkDeviceSize offset, VkDeviceSize buf_whole_size, uint32_t first_index, uint32_t count,
600 VkDeviceSize stride) {
601 VkDeviceSize range_start = offset + first_index * stride;
602 VkDeviceSize range_size = 0;
locke-lunargff255f92020-05-13 18:53:52 -0600603 if (count == UINT32_MAX) {
604 range_size = buf_whole_size - range_start;
605 } else {
606 range_size = count * stride;
607 }
John Zulauf3e86bf02020-09-12 10:47:57 -0600608 return MakeRange(range_start, range_size);
locke-lunargff255f92020-05-13 18:53:52 -0600609}
610
locke-lunarg654e3692020-06-04 17:19:15 -0600611SyncStageAccessIndex GetSyncStageAccessIndexsByDescriptorSet(VkDescriptorType descriptor_type, const interface_var &descriptor_data,
612 VkShaderStageFlagBits stage_flag) {
613 if (descriptor_type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) {
614 assert(stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT);
615 return SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ;
616 }
617 auto stage_access = syncStageAccessMaskByShaderStage.find(stage_flag);
618 if (stage_access == syncStageAccessMaskByShaderStage.end()) {
619 assert(0);
620 }
621 if (descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || descriptor_type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) {
622 return stage_access->second.uniform_read;
623 }
624
625 // If the desriptorSet is writable, we don't need to care SHADER_READ. SHADER_WRITE is enough.
626 // Because if write hazard happens, read hazard might or might not happen.
627 // But if write hazard doesn't happen, read hazard is impossible to happen.
628 if (descriptor_data.is_writable) {
Jeremy Gebben40a22942020-12-22 14:22:06 -0700629 return stage_access->second.storage_write;
locke-lunarg654e3692020-06-04 17:19:15 -0600630 }
Jeremy Gebben40a22942020-12-22 14:22:06 -0700631 // TODO: sampled_read
632 return stage_access->second.storage_read;
locke-lunarg654e3692020-06-04 17:19:15 -0600633}
634
locke-lunarg37047832020-06-12 13:44:45 -0600635bool IsImageLayoutDepthWritable(VkImageLayout image_layout) {
636 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
637 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL ||
638 image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL)
639 ? true
640 : false;
641}
642
643bool IsImageLayoutStencilWritable(VkImageLayout image_layout) {
644 return (image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL ||
645 image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL ||
646 image_layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL)
647 ? true
648 : false;
649}
650
John Zulauf355e49b2020-04-24 15:11:15 -0600651// Class AccessContext stores the state of accesses specific to a Command, Subpass, or Queue
John Zulaufb02c1eb2020-10-06 16:33:36 -0600652template <typename Action>
653static void ApplyOverImageRange(const IMAGE_STATE &image_state, const VkImageSubresourceRange &subresource_range_arg,
654 Action &action) {
655 // At this point the "apply over range" logic only supports a single memory binding
656 if (!SimpleBinding(image_state)) return;
657 auto subresource_range = NormalizeSubresourceRange(image_state.createInfo, subresource_range_arg);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600658 const auto base_address = ResourceBaseAddress(image_state);
John Zulauf150e5332020-12-03 08:52:52 -0700659 subresource_adapter::ImageRangeGenerator range_gen(*image_state.fragment_encoder.get(), subresource_range, {0, 0, 0},
Aitor Camachoe67f2c72022-06-08 14:41:58 +0200660 image_state.createInfo.extent, base_address, false);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600661 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -0700662 action(*range_gen);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600663 }
664}
665
John Zulauf7635de32020-05-29 17:14:15 -0600666// Tranverse the attachment resolves for this a specific subpass, and do action() to them.
667// Used by both validation and record operations
668//
669// The signature for Action() reflect the needs of both uses.
670template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -0700671void ResolveOperation(Action &action, const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
672 uint32_t subpass) {
John Zulauf7635de32020-05-29 17:14:15 -0600673 const auto &rp_ci = rp_state.createInfo;
674 const auto *attachment_ci = rp_ci.pAttachments;
675 const auto &subpass_ci = rp_ci.pSubpasses[subpass];
676
677 // Color resolves -- require an inuse color attachment and a matching inuse resolve attachment
678 const auto *color_attachments = subpass_ci.pColorAttachments;
679 const auto *color_resolve = subpass_ci.pResolveAttachments;
680 if (color_resolve && color_attachments) {
681 for (uint32_t i = 0; i < subpass_ci.colorAttachmentCount; i++) {
682 const auto &color_attach = color_attachments[i].attachment;
683 const auto &resolve_attach = subpass_ci.pResolveAttachments[i].attachment;
684 if ((color_attach != VK_ATTACHMENT_UNUSED) && (resolve_attach != VK_ATTACHMENT_UNUSED)) {
685 action("color", "resolve read", color_attach, resolve_attach, attachment_views[color_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700686 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ,
687 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600688 action("color", "resolve write", color_attach, resolve_attach, attachment_views[resolve_attach],
John Zulaufd0ec59f2021-03-13 14:25:08 -0700689 AttachmentViewGen::Gen::kRenderArea, SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE,
690 SyncOrdering::kColorAttachment);
John Zulauf7635de32020-05-29 17:14:15 -0600691 }
692 }
693 }
694
695 // Depth stencil resolve only if the extension is present
Mark Lobodzinski1f887d32020-12-30 15:31:33 -0700696 const auto ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_ci.pNext);
John Zulauf7635de32020-05-29 17:14:15 -0600697 if (ds_resolve && ds_resolve->pDepthStencilResolveAttachment &&
698 (ds_resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) && subpass_ci.pDepthStencilAttachment &&
699 (subpass_ci.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED)) {
700 const auto src_at = subpass_ci.pDepthStencilAttachment->attachment;
701 const auto src_ci = attachment_ci[src_at];
702 // The formats are required to match so we can pick either
703 const bool resolve_depth = (ds_resolve->depthResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasDepth(src_ci.format);
704 const bool resolve_stencil = (ds_resolve->stencilResolveMode != VK_RESOLVE_MODE_NONE) && FormatHasStencil(src_ci.format);
705 const auto dst_at = ds_resolve->pDepthStencilResolveAttachment->attachment;
John Zulauf7635de32020-05-29 17:14:15 -0600706
707 // Figure out which aspects are actually touched during resolve operations
708 const char *aspect_string = nullptr;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700709 AttachmentViewGen::Gen gen_type = AttachmentViewGen::Gen::kRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600710 if (resolve_depth && resolve_stencil) {
John Zulauf7635de32020-05-29 17:14:15 -0600711 aspect_string = "depth/stencil";
712 } else if (resolve_depth) {
713 // Validate depth only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700714 gen_type = AttachmentViewGen::Gen::kDepthOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600715 aspect_string = "depth";
716 } else if (resolve_stencil) {
717 // Validate all stencil only
John Zulaufd0ec59f2021-03-13 14:25:08 -0700718 gen_type = AttachmentViewGen::Gen::kStencilOnlyRenderArea;
John Zulauf7635de32020-05-29 17:14:15 -0600719 aspect_string = "stencil";
720 }
721
John Zulaufd0ec59f2021-03-13 14:25:08 -0700722 if (aspect_string) {
723 action(aspect_string, "resolve read", src_at, dst_at, attachment_views[src_at], gen_type,
724 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ, SyncOrdering::kRaster);
725 action(aspect_string, "resolve write", src_at, dst_at, attachment_views[dst_at], gen_type,
726 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulauf7635de32020-05-29 17:14:15 -0600727 }
728 }
729}
730
731// Action for validating resolve operations
732class ValidateResolveAction {
733 public:
John Zulauffaea0ee2021-01-14 14:01:32 -0700734 ValidateResolveAction(VkRenderPass render_pass, uint32_t subpass, const AccessContext &context,
sjfricke0bea06e2022-06-05 09:22:26 +0900735 const CommandExecutionContext &exec_context, CMD_TYPE cmd_type)
John Zulauf7635de32020-05-29 17:14:15 -0600736 : render_pass_(render_pass),
737 subpass_(subpass),
738 context_(context),
John Zulaufbb890452021-12-14 11:30:18 -0700739 exec_context_(exec_context),
sjfricke0bea06e2022-06-05 09:22:26 +0900740 cmd_type_(cmd_type),
John Zulauf7635de32020-05-29 17:14:15 -0600741 skip_(false) {}
742 void operator()(const char *aspect_name, const char *attachment_name, uint32_t src_at, uint32_t dst_at,
John Zulaufd0ec59f2021-03-13 14:25:08 -0700743 const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage,
744 SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600745 HazardResult hazard;
John Zulaufd0ec59f2021-03-13 14:25:08 -0700746 hazard = context_.DetectHazard(view_gen, gen_type, current_usage, ordering_rule);
John Zulauf7635de32020-05-29 17:14:15 -0600747 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +0900748 skip_ |= exec_context_.GetSyncState().LogError(
749 render_pass_, string_SyncHazardVUID(hazard.hazard),
750 "%s: Hazard %s in subpass %" PRIu32 "during %s %s, from attachment %" PRIu32 " to resolve attachment %" PRIu32
751 ". Access info %s.",
752 CommandTypeString(cmd_type_), string_SyncHazard(hazard.hazard), subpass_, aspect_name, attachment_name, src_at,
753 dst_at, exec_context_.FormatHazard(hazard).c_str());
John Zulauf7635de32020-05-29 17:14:15 -0600754 }
755 }
756 // Providing a mechanism for the constructing caller to get the result of the validation
757 bool GetSkip() const { return skip_; }
758
759 private:
760 VkRenderPass render_pass_;
761 const uint32_t subpass_;
762 const AccessContext &context_;
John Zulaufbb890452021-12-14 11:30:18 -0700763 const CommandExecutionContext &exec_context_;
sjfricke0bea06e2022-06-05 09:22:26 +0900764 CMD_TYPE cmd_type_;
John Zulauf7635de32020-05-29 17:14:15 -0600765 bool skip_;
766};
767
768// Update action for resolve operations
769class UpdateStateResolveAction {
770 public:
John Zulauf14940722021-04-12 15:19:02 -0600771 UpdateStateResolveAction(AccessContext &context, ResourceUsageTag tag) : context_(context), tag_(tag) {}
John Zulaufd0ec59f2021-03-13 14:25:08 -0700772 void operator()(const char *, const char *, uint32_t, uint32_t, const AttachmentViewGen &view_gen,
773 AttachmentViewGen::Gen gen_type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) {
John Zulauf7635de32020-05-29 17:14:15 -0600774 // Ignores validation only arguments...
John Zulaufd0ec59f2021-03-13 14:25:08 -0700775 context_.UpdateAccessState(view_gen, gen_type, current_usage, ordering_rule, tag_);
John Zulauf7635de32020-05-29 17:14:15 -0600776 }
777
778 private:
779 AccessContext &context_;
John Zulauf14940722021-04-12 15:19:02 -0600780 const ResourceUsageTag tag_;
John Zulauf7635de32020-05-29 17:14:15 -0600781};
782
John Zulauf59e25072020-07-17 10:55:21 -0600783void HazardResult::Set(const ResourceAccessState *access_state_, SyncStageAccessIndex usage_index_, SyncHazard hazard_,
John Zulauf14940722021-04-12 15:19:02 -0600784 const SyncStageAccessFlags &prior_, const ResourceUsageTag tag_) {
John Zulauf4fa68462021-04-26 21:04:22 -0600785 access_state = layer_data::make_unique<const ResourceAccessState>(*access_state_);
John Zulauf59e25072020-07-17 10:55:21 -0600786 usage_index = usage_index_;
787 hazard = hazard_;
788 prior_access = prior_;
789 tag = tag_;
790}
791
John Zulauf4fa68462021-04-26 21:04:22 -0600792void HazardResult::AddRecordedAccess(const ResourceFirstAccess &first_access) {
793 recorded_access = layer_data::make_unique<const ResourceFirstAccess>(first_access);
794}
795
John Zulauf1d5f9c12022-05-13 14:51:08 -0600796void AccessContext::DeleteAccess(const AddressRange &address) { GetAccessStateMap(address.type).erase_range(address.range); }
797
John Zulauf540266b2020-04-06 18:54:53 -0600798AccessContext::AccessContext(uint32_t subpass, VkQueueFlags queue_flags,
799 const std::vector<SubpassDependencyGraphNode> &dependencies,
John Zulauf1a224292020-06-30 14:52:13 -0600800 const std::vector<AccessContext> &contexts, const AccessContext *external_context) {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600801 Reset();
802 const auto &subpass_dep = dependencies[subpass];
John Zulauf22aefed2021-03-11 18:14:35 -0700803 bool has_barrier_from_external = subpass_dep.barrier_from_external.size() > 0U;
804 prev_.reserve(subpass_dep.prev.size() + (has_barrier_from_external ? 1U : 0U));
John Zulauf355e49b2020-04-24 15:11:15 -0600805 prev_by_subpass_.resize(subpass, nullptr); // Can't be more prevs than the subpass we're on
John Zulauf3d84f1b2020-03-09 13:33:25 -0600806 for (const auto &prev_dep : subpass_dep.prev) {
John Zulaufbaea94f2020-09-15 17:55:16 -0600807 const auto prev_pass = prev_dep.first->pass;
808 const auto &prev_barriers = prev_dep.second;
809 assert(prev_dep.second.size());
810 prev_.emplace_back(&contexts[prev_pass], queue_flags, prev_barriers);
811 prev_by_subpass_[prev_pass] = &prev_.back();
John Zulauf5c5e88d2019-12-26 11:22:02 -0700812 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600813
814 async_.reserve(subpass_dep.async.size());
815 for (const auto async_subpass : subpass_dep.async) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700816 async_.emplace_back(&contexts[async_subpass]);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600817 }
John Zulauf22aefed2021-03-11 18:14:35 -0700818 if (has_barrier_from_external) {
819 // Store the barrier from external with the reat, but save pointer for "by subpass" lookups.
820 prev_.emplace_back(external_context, queue_flags, subpass_dep.barrier_from_external);
821 src_external_ = &prev_.back();
John Zulaufe5da6e52020-03-18 15:32:18 -0600822 }
John Zulaufbaea94f2020-09-15 17:55:16 -0600823 if (subpass_dep.barrier_to_external.size()) {
824 dst_external_ = TrackBack(this, queue_flags, subpass_dep.barrier_to_external);
John Zulauf3d84f1b2020-03-09 13:33:25 -0600825 }
John Zulauf5c5e88d2019-12-26 11:22:02 -0700826}
827
John Zulauf5f13a792020-03-10 07:31:21 -0600828template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600829HazardResult AccessContext::DetectPreviousHazard(AccessAddressType type, Detector &detector,
John Zulauf540266b2020-04-06 18:54:53 -0600830 const ResourceAccessRange &range) const {
John Zulauf5f13a792020-03-10 07:31:21 -0600831 ResourceAccessRangeMap descent_map;
John Zulauf69133422020-05-20 14:55:53 -0600832 ResolvePreviousAccess(type, range, &descent_map, nullptr);
John Zulauf5f13a792020-03-10 07:31:21 -0600833
834 HazardResult hazard;
835 for (auto prev = descent_map.begin(); prev != descent_map.end() && !hazard.hazard; ++prev) {
836 hazard = detector.Detect(prev);
837 }
838 return hazard;
839}
840
John Zulauf4a6105a2020-11-17 15:11:05 -0700841template <typename Action>
842void AccessContext::ForAll(Action &&action) {
843 for (const auto address_type : kAddressTypes) {
844 auto &accesses = GetAccessStateMap(address_type);
John Zulauf1d5f9c12022-05-13 14:51:08 -0600845 for (auto &access : accesses) {
John Zulauf4a6105a2020-11-17 15:11:05 -0700846 action(address_type, access);
847 }
848 }
849}
850
John Zulauf3d84f1b2020-03-09 13:33:25 -0600851// A recursive range walker for hazard detection, first for the current context and the (DetectHazardRecur) to walk
852// the DAG of the contexts (for example subpasses)
853template <typename Detector>
John Zulaufe0757ba2022-06-10 16:51:45 -0600854HazardResult AccessContext::DetectHazard(AccessAddressType type, Detector &detector, const ResourceAccessRange &range,
John Zulauf355e49b2020-04-24 15:11:15 -0600855 DetectOptions options) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -0600856 HazardResult hazard;
John Zulauf5f13a792020-03-10 07:31:21 -0600857
John Zulauf1a224292020-06-30 14:52:13 -0600858 if (static_cast<uint32_t>(options) & DetectOptions::kDetectAsync) {
John Zulauf355e49b2020-04-24 15:11:15 -0600859 // Async checks don't require recursive lookups, as the async lists are exhaustive for the top-level context
860 // so we'll check these first
861 for (const auto &async_context : async_) {
862 hazard = async_context->DetectAsyncHazard(type, detector, range);
863 if (hazard.hazard) return hazard;
864 }
John Zulauf5f13a792020-03-10 07:31:21 -0600865 }
866
John Zulauf1a224292020-06-30 14:52:13 -0600867 const bool detect_prev = (static_cast<uint32_t>(options) & DetectOptions::kDetectPrevious) != 0;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600868
John Zulauf69133422020-05-20 14:55:53 -0600869 const auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600870 const auto the_end = accesses.cend(); // End is not invalidated
871 auto pos = accesses.lower_bound(range);
John Zulauf69133422020-05-20 14:55:53 -0600872 ResourceAccessRange gap = {range.begin, range.begin};
John Zulauf5f13a792020-03-10 07:31:21 -0600873
John Zulauf3cafbf72021-03-26 16:55:19 -0600874 while (pos != the_end && pos->first.begin < range.end) {
John Zulauf69133422020-05-20 14:55:53 -0600875 // Cover any leading gap, or gap between entries
876 if (detect_prev) {
877 // TODO: After profiling we may want to change the descent logic such that we don't recur per gap...
878 // Cover any leading gap, or gap between entries
879 gap.end = pos->first.begin; // We know this begin is < range.end
John Zulauf355e49b2020-04-24 15:11:15 -0600880 if (gap.non_empty()) {
John Zulauf69133422020-05-20 14:55:53 -0600881 // Recur on all gaps
John Zulauf16adfc92020-04-08 10:28:33 -0600882 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf5f13a792020-03-10 07:31:21 -0600883 if (hazard.hazard) return hazard;
884 }
John Zulauf69133422020-05-20 14:55:53 -0600885 // Set up for the next gap. If pos..end is >= range.end, loop will exit, and trailing gap will be empty
886 gap.begin = pos->first.end;
887 }
888
889 hazard = detector.Detect(pos);
890 if (hazard.hazard) return hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600891 ++pos;
John Zulauf69133422020-05-20 14:55:53 -0600892 }
893
894 if (detect_prev) {
895 // Detect in the trailing empty as needed
896 gap.end = range.end;
897 if (gap.non_empty()) {
898 hazard = DetectPreviousHazard(type, detector, gap);
John Zulauf16adfc92020-04-08 10:28:33 -0600899 }
John Zulauf3d84f1b2020-03-09 13:33:25 -0600900 }
901
902 return hazard;
903}
904
905// A non recursive range walker for the asynchronous contexts (those we have no barriers with)
906template <typename Detector>
John Zulauf43cc7462020-12-03 12:33:12 -0700907HazardResult AccessContext::DetectAsyncHazard(AccessAddressType type, const Detector &detector,
908 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -0600909 auto &accesses = GetAccessStateMap(type);
John Zulauf3cafbf72021-03-26 16:55:19 -0600910 auto pos = accesses.lower_bound(range);
911 const auto the_end = accesses.end();
John Zulauf16adfc92020-04-08 10:28:33 -0600912
John Zulauf3d84f1b2020-03-09 13:33:25 -0600913 HazardResult hazard;
John Zulauf3cafbf72021-03-26 16:55:19 -0600914 while (pos != the_end && pos->first.begin < range.end) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -0700915 hazard = detector.DetectAsync(pos, start_tag_);
John Zulauf3cafbf72021-03-26 16:55:19 -0600916 if (hazard.hazard) break;
917 ++pos;
John Zulauf3d84f1b2020-03-09 13:33:25 -0600918 }
John Zulauf16adfc92020-04-08 10:28:33 -0600919
John Zulauf3d84f1b2020-03-09 13:33:25 -0600920 return hazard;
921}
922
John Zulaufb02c1eb2020-10-06 16:33:36 -0600923struct ApplySubpassTransitionBarriersAction {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -0700924 explicit ApplySubpassTransitionBarriersAction(const std::vector<SyncBarrier> &barriers_) : barriers(barriers_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600925 void operator()(ResourceAccessState *access) const {
926 assert(access);
927 access->ApplyBarriers(barriers, true);
928 }
929 const std::vector<SyncBarrier> &barriers;
930};
931
John Zulaufe0757ba2022-06-10 16:51:45 -0600932struct QueueTagOffsetBarrierAction {
933 QueueTagOffsetBarrierAction(QueueId qid, ResourceUsageTag offset) : queue_id(qid), tag_offset(offset) {}
934 void operator()(ResourceAccessState *access) const {
935 access->OffsetTag(tag_offset);
936 access->SetQueueId(queue_id);
937 };
938 QueueId queue_id;
939 ResourceUsageTag tag_offset;
940};
941
John Zulauf22aefed2021-03-11 18:14:35 -0700942struct ApplyTrackbackStackAction {
943 explicit ApplyTrackbackStackAction(const std::vector<SyncBarrier> &barriers_,
944 const ResourceAccessStateFunction *previous_barrier_ = nullptr)
945 : barriers(barriers_), previous_barrier(previous_barrier_) {}
John Zulaufb02c1eb2020-10-06 16:33:36 -0600946 void operator()(ResourceAccessState *access) const {
947 assert(access);
948 assert(!access->HasPendingState());
949 access->ApplyBarriers(barriers, false);
John Zulaufee984022022-04-13 16:39:50 -0600950 // NOTE: We can use invalid tag, as these barriers do no include layout transitions (would assert in SetWrite)
951 access->ApplyPendingBarriers(kInvalidTag);
John Zulauf22aefed2021-03-11 18:14:35 -0700952 if (previous_barrier) {
953 assert(bool(*previous_barrier));
954 (*previous_barrier)(access);
955 }
John Zulaufb02c1eb2020-10-06 16:33:36 -0600956 }
957 const std::vector<SyncBarrier> &barriers;
John Zulauf22aefed2021-03-11 18:14:35 -0700958 const ResourceAccessStateFunction *previous_barrier;
John Zulaufb02c1eb2020-10-06 16:33:36 -0600959};
960
961// Splits a single map entry into piece matching the entries in [first, last) the total range over [first, last) must be
962// contained with entry. Entry must be an iterator pointing to dest, first and last must be iterators pointing to a
963// *different* map from dest.
964// Returns the position past the last resolved range -- the entry covering the remainder of entry->first not included in the
965// range [first, last)
966template <typename BarrierAction>
John Zulauf355e49b2020-04-24 15:11:15 -0600967static void ResolveMapToEntry(ResourceAccessRangeMap *dest, ResourceAccessRangeMap::iterator entry,
968 ResourceAccessRangeMap::const_iterator first, ResourceAccessRangeMap::const_iterator last,
John Zulaufb02c1eb2020-10-06 16:33:36 -0600969 BarrierAction &barrier_action) {
John Zulauf355e49b2020-04-24 15:11:15 -0600970 auto at = entry;
971 for (auto pos = first; pos != last; ++pos) {
972 // Every member of the input iterator range must fit within the remaining portion of entry
973 assert(at->first.includes(pos->first));
974 assert(at != dest->end());
975 // Trim up at to the same size as the entry to resolve
976 at = sparse_container::split(at, *dest, pos->first);
John Zulaufb02c1eb2020-10-06 16:33:36 -0600977 auto access = pos->second; // intentional copy
978 barrier_action(&access);
John Zulauf355e49b2020-04-24 15:11:15 -0600979 at->second.Resolve(access);
980 ++at; // Go to the remaining unused section of entry
981 }
982}
983
John Zulaufa0a98292020-09-18 09:30:10 -0600984static SyncBarrier MergeBarriers(const std::vector<SyncBarrier> &barriers) {
985 SyncBarrier merged = {};
986 for (const auto &barrier : barriers) {
987 merged.Merge(barrier);
988 }
989 return merged;
990}
991
John Zulaufb02c1eb2020-10-06 16:33:36 -0600992template <typename BarrierAction>
John Zulauf43cc7462020-12-03 12:33:12 -0700993void AccessContext::ResolveAccessRange(AccessAddressType type, const ResourceAccessRange &range, BarrierAction &barrier_action,
John Zulauf355e49b2020-04-24 15:11:15 -0600994 ResourceAccessRangeMap *resolve_map, const ResourceAccessState *infill_state,
995 bool recur_to_infill) const {
John Zulauf3bcab5e2020-06-19 14:42:32 -0600996 if (!range.non_empty()) return;
997
John Zulauf355e49b2020-04-24 15:11:15 -0600998 ResourceRangeMergeIterator current(*resolve_map, GetAccessStateMap(type), range.begin);
999 while (current->range.non_empty() && range.includes(current->range.begin)) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001000 const auto current_range = current->range & range;
John Zulauf16adfc92020-04-08 10:28:33 -06001001 if (current->pos_B->valid) {
1002 const auto &src_pos = current->pos_B->lower_bound;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001003 auto access = src_pos->second; // intentional copy
1004 barrier_action(&access);
1005
John Zulauf16adfc92020-04-08 10:28:33 -06001006 if (current->pos_A->valid) {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001007 const auto trimmed = sparse_container::split(current->pos_A->lower_bound, *resolve_map, current_range);
1008 trimmed->second.Resolve(access);
1009 current.invalidate_A(trimmed);
John Zulauf5f13a792020-03-10 07:31:21 -06001010 } else {
John Zulauf3bcab5e2020-06-19 14:42:32 -06001011 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current_range, access));
John Zulauf355e49b2020-04-24 15:11:15 -06001012 current.invalidate_A(inserted); // Update the parallel iterator to point at the insert segment
John Zulauf5f13a792020-03-10 07:31:21 -06001013 }
John Zulauf16adfc92020-04-08 10:28:33 -06001014 } else {
1015 // we have to descend to fill this gap
1016 if (recur_to_infill) {
John Zulauf22aefed2021-03-11 18:14:35 -07001017 ResourceAccessRange recurrence_range = current_range;
1018 // The current context is empty for the current range, so recur to fill the gap.
1019 // Since we will be recurring back up the DAG, expand the gap descent to cover the full range for which B
1020 // is not valid, to minimize that recurrence
1021 if (current->pos_B.at_end()) {
1022 // Do the remainder here....
1023 recurrence_range.end = range.end;
John Zulauf355e49b2020-04-24 15:11:15 -06001024 } else {
John Zulauf22aefed2021-03-11 18:14:35 -07001025 // Recur only over the range until B becomes valid (within the limits of range).
1026 recurrence_range.end = std::min(range.end, current->pos_B->lower_bound->first.begin);
John Zulauf355e49b2020-04-24 15:11:15 -06001027 }
John Zulauf22aefed2021-03-11 18:14:35 -07001028 ResolvePreviousAccessStack(type, recurrence_range, resolve_map, infill_state, barrier_action);
1029
John Zulauf355e49b2020-04-24 15:11:15 -06001030 // Given that there could be gaps we need to seek carefully to not repeatedly search the same gaps in the next
1031 // iterator of the outer while.
1032
1033 // Set the parallel iterator to the end of this range s.t. ++ will move us to the next range whether or
1034 // not the end of the range is a gap. For the seek to work, first we need to warn the parallel iterator
1035 // we stepped on the dest map
John Zulauf22aefed2021-03-11 18:14:35 -07001036 const auto seek_to = recurrence_range.end - 1; // The subtraction is safe as range can't be empty (loop condition)
locke-lunarg88dbb542020-06-23 22:05:42 -06001037 current.invalidate_A(); // Changes current->range
John Zulauf355e49b2020-04-24 15:11:15 -06001038 current.seek(seek_to);
1039 } else if (!current->pos_A->valid && infill_state) {
1040 // If we didn't find anything in the current range, and we aren't reccuring... we infill if required
1041 auto inserted = resolve_map->insert(current->pos_A->lower_bound, std::make_pair(current->range, *infill_state));
1042 current.invalidate_A(inserted); // Update the parallel iterator to point at the correct segment after insert
John Zulauf16adfc92020-04-08 10:28:33 -06001043 }
John Zulauf5f13a792020-03-10 07:31:21 -06001044 }
ziga-lunargf0e27ad2022-03-28 00:44:12 +02001045 if (current->range.non_empty()) {
1046 ++current;
1047 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001048 }
John Zulauf1a224292020-06-30 14:52:13 -06001049
1050 // Infill if range goes passed both the current and resolve map prior contents
1051 if (recur_to_infill && (current->range.end < range.end)) {
1052 ResourceAccessRange trailing_fill_range = {current->range.end, range.end};
John Zulauf22aefed2021-03-11 18:14:35 -07001053 ResolvePreviousAccessStack<BarrierAction>(type, trailing_fill_range, resolve_map, infill_state, barrier_action);
John Zulauf1a224292020-06-30 14:52:13 -06001054 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001055}
1056
John Zulauf22aefed2021-03-11 18:14:35 -07001057template <typename BarrierAction>
1058void AccessContext::ResolvePreviousAccessStack(AccessAddressType type, const ResourceAccessRange &range,
1059 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1060 const BarrierAction &previous_barrier) const {
1061 ResourceAccessStateFunction stacked_barrier(std::ref(previous_barrier));
1062 ResolvePreviousAccess(type, range, descent_map, infill_state, &stacked_barrier);
1063}
1064
John Zulauf43cc7462020-12-03 12:33:12 -07001065void AccessContext::ResolvePreviousAccess(AccessAddressType type, const ResourceAccessRange &range,
John Zulauf22aefed2021-03-11 18:14:35 -07001066 ResourceAccessRangeMap *descent_map, const ResourceAccessState *infill_state,
1067 const ResourceAccessStateFunction *previous_barrier) const {
1068 if (prev_.size() == 0) {
John Zulauf5f13a792020-03-10 07:31:21 -06001069 if (range.non_empty() && infill_state) {
John Zulauf22aefed2021-03-11 18:14:35 -07001070 // Fill the empty poritions of descent_map with the default_state with the barrier function applied (iff present)
1071 ResourceAccessState state_copy;
1072 if (previous_barrier) {
1073 assert(bool(*previous_barrier));
1074 state_copy = *infill_state;
1075 (*previous_barrier)(&state_copy);
1076 infill_state = &state_copy;
1077 }
1078 sparse_container::update_range_value(*descent_map, range, *infill_state,
1079 sparse_container::value_precedence::prefer_dest);
John Zulauf5f13a792020-03-10 07:31:21 -06001080 }
1081 } else {
1082 // Look for something to fill the gap further along.
1083 for (const auto &prev_dep : prev_) {
John Zulauf22aefed2021-03-11 18:14:35 -07001084 const ApplyTrackbackStackAction barrier_action(prev_dep.barriers, previous_barrier);
John Zulaufbb890452021-12-14 11:30:18 -07001085 prev_dep.source_subpass->ResolveAccessRange(type, range, barrier_action, descent_map, infill_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001086 }
John Zulauf5f13a792020-03-10 07:31:21 -06001087 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06001088}
1089
John Zulauf4a6105a2020-11-17 15:11:05 -07001090// Non-lazy import of all accesses, WaitEvents needs this.
1091void AccessContext::ResolvePreviousAccesses() {
1092 ResourceAccessState default_state;
John Zulauf22aefed2021-03-11 18:14:35 -07001093 if (!prev_.size()) return; // If no previous contexts, nothing to do
1094
John Zulauf4a6105a2020-11-17 15:11:05 -07001095 for (const auto address_type : kAddressTypes) {
1096 ResolvePreviousAccess(address_type, kFullRange, &GetAccessStateMap(address_type), &default_state);
1097 }
1098}
1099
John Zulauf43cc7462020-12-03 12:33:12 -07001100AccessAddressType AccessContext::ImageAddressType(const IMAGE_STATE &image) {
1101 return (image.fragment_encoder->IsLinearImage()) ? AccessAddressType::kLinear : AccessAddressType::kIdealized;
John Zulauf16adfc92020-04-08 10:28:33 -06001102}
1103
John Zulauf1507ee42020-05-18 11:33:09 -06001104static SyncStageAccessIndex ColorLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001105 const auto stage_access = (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1106 ? SYNC_ACCESS_INDEX_NONE
1107 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_READ
1108 : SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001109 return stage_access;
1110}
1111static SyncStageAccessIndex DepthStencilLoadUsage(VkAttachmentLoadOp load_op) {
John Zulauf57261402021-08-13 11:32:06 -06001112 const auto stage_access =
1113 (load_op == VK_ATTACHMENT_LOAD_OP_NONE_EXT)
1114 ? SYNC_ACCESS_INDEX_NONE
1115 : ((load_op == VK_ATTACHMENT_LOAD_OP_LOAD) ? SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_READ
1116 : SYNC_EARLY_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE);
John Zulauf1507ee42020-05-18 11:33:09 -06001117 return stage_access;
1118}
1119
John Zulauf7635de32020-05-29 17:14:15 -06001120// Caller must manage returned pointer
1121static AccessContext *CreateStoreResolveProxyContext(const AccessContext &context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001122 uint32_t subpass, const AttachmentViewGenVector &attachment_views) {
John Zulauf7635de32020-05-29 17:14:15 -06001123 auto *proxy = new AccessContext(context);
John Zulaufee984022022-04-13 16:39:50 -06001124 proxy->UpdateAttachmentResolveAccess(rp_state, attachment_views, subpass, kInvalidTag);
1125 proxy->UpdateAttachmentStoreAccess(rp_state, attachment_views, subpass, kInvalidTag);
John Zulauf7635de32020-05-29 17:14:15 -06001126 return proxy;
1127}
1128
John Zulaufb02c1eb2020-10-06 16:33:36 -06001129template <typename BarrierAction>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001130void AccessContext::ResolveAccessRange(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1131 BarrierAction &barrier_action, ResourceAccessRangeMap *descent_map,
1132 const ResourceAccessState *infill_state) const {
1133 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1134 if (!attachment_gen) return;
1135
1136 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1137 const AccessAddressType address_type = view_gen.GetAddressType();
1138 for (; range_gen->non_empty(); ++range_gen) {
1139 ResolveAccessRange(address_type, *range_gen, barrier_action, descent_map, infill_state);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001140 }
John Zulauf62f10592020-04-03 12:20:02 -06001141}
1142
John Zulauf1d5f9c12022-05-13 14:51:08 -06001143template <typename ResolveOp>
1144void AccessContext::ResolveFromContext(ResolveOp &&resolve_op, const AccessContext &from_context,
1145 const ResourceAccessState *infill_state, bool recur_to_infill) {
1146 for (auto address_type : kAddressTypes) {
1147 from_context.ResolveAccessRange(address_type, kFullRange, resolve_op, &GetAccessStateMap(address_type), infill_state,
1148 recur_to_infill);
1149 }
1150}
1151
John Zulauf7635de32020-05-29 17:14:15 -06001152// Layout transitions are handled as if the were occuring in the beginning of the next subpass
John Zulaufbb890452021-12-14 11:30:18 -07001153bool AccessContext::ValidateLayoutTransitions(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001154 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001155 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06001156 bool skip = false;
John Zulauf7635de32020-05-29 17:14:15 -06001157 // As validation methods are const and precede the record/update phase, for any tranistions from the immediately
1158 // previous subpass, we have to validate them against a copy of the AccessContext, with resolve operations applied, as
1159 // those affects have not been recorded yet.
1160 //
1161 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
1162 // to apply and only copy then, if this proves a hot spot.
1163 std::unique_ptr<AccessContext> proxy_for_prev;
1164 TrackBack proxy_track_back;
1165
John Zulauf355e49b2020-04-24 15:11:15 -06001166 const auto &transitions = rp_state.subpass_transitions[subpass];
1167 for (const auto &transition : transitions) {
John Zulauf7635de32020-05-29 17:14:15 -06001168 const bool prev_needs_proxy = transition.prev_pass != VK_SUBPASS_EXTERNAL && (transition.prev_pass + 1 == subpass);
1169
1170 const auto *track_back = GetTrackBackFromSubpass(transition.prev_pass);
John Zulauf22aefed2021-03-11 18:14:35 -07001171 assert(track_back);
John Zulauf7635de32020-05-29 17:14:15 -06001172 if (prev_needs_proxy) {
1173 if (!proxy_for_prev) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001174 proxy_for_prev.reset(
John Zulaufbb890452021-12-14 11:30:18 -07001175 CreateStoreResolveProxyContext(*track_back->source_subpass, rp_state, transition.prev_pass, attachment_views));
John Zulauf7635de32020-05-29 17:14:15 -06001176 proxy_track_back = *track_back;
John Zulaufbb890452021-12-14 11:30:18 -07001177 proxy_track_back.source_subpass = proxy_for_prev.get();
John Zulauf7635de32020-05-29 17:14:15 -06001178 }
1179 track_back = &proxy_track_back;
1180 }
1181 auto hazard = DetectSubpassTransitionHazard(*track_back, attachment_views[transition.attachment]);
John Zulauf355e49b2020-04-24 15:11:15 -06001182 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001183 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06001184 if (hazard.tag == kInvalidTag) {
John Zulaufbb890452021-12-14 11:30:18 -07001185 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001186 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1187 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1188 " image layout transition (old_layout: %s, new_layout: %s) after store/resolve operation in subpass %" PRIu32,
1189 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1190 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout), transition.prev_pass);
1191 } else {
John Zulaufbb890452021-12-14 11:30:18 -07001192 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06001193 rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1194 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1195 " image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
1196 func_name, string_SyncHazard(hazard.hazard), subpass, transition.attachment,
1197 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06001198 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06001199 }
John Zulauf355e49b2020-04-24 15:11:15 -06001200 }
1201 }
1202 return skip;
1203}
1204
John Zulaufbb890452021-12-14 11:30:18 -07001205bool AccessContext::ValidateLoadOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulauf7635de32020-05-29 17:14:15 -06001206 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001207 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulauf1507ee42020-05-18 11:33:09 -06001208 bool skip = false;
1209 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufa0a98292020-09-18 09:30:10 -06001210
John Zulauf1507ee42020-05-18 11:33:09 -06001211 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1212 if (subpass == rp_state.attachment_first_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001213 const auto &view_gen = attachment_views[i];
1214 if (!view_gen.IsValid()) continue;
John Zulauf1507ee42020-05-18 11:33:09 -06001215 const auto &ci = attachment_ci[i];
John Zulauf1507ee42020-05-18 11:33:09 -06001216
1217 // Need check in the following way
1218 // 1) if the usage bit isn't in the dest_access_scope, and there is layout traniition for initial use, report hazard
1219 // vs. transition
1220 // 2) if there isn't a layout transition, we need to look at the external context with a "detect hazard" operation
1221 // for each aspect loaded.
1222
1223 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06001224 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06001225 const bool is_color = !(has_depth || has_stencil);
1226
1227 const SyncStageAccessIndex load_index = has_depth ? DepthStencilLoadUsage(ci.loadOp) : ColorLoadUsage(ci.loadOp);
John Zulauf1507ee42020-05-18 11:33:09 -06001228 const SyncStageAccessIndex stencil_load_index = has_stencil ? DepthStencilLoadUsage(ci.stencilLoadOp) : load_index;
John Zulauf1507ee42020-05-18 11:33:09 -06001229
John Zulaufaff20662020-06-01 14:07:58 -06001230 HazardResult hazard;
John Zulauf1507ee42020-05-18 11:33:09 -06001231 const char *aspect = nullptr;
John Zulauf1507ee42020-05-18 11:33:09 -06001232
John Zulaufb02c1eb2020-10-06 16:33:36 -06001233 bool checked_stencil = false;
John Zulauf57261402021-08-13 11:32:06 -06001234 if (is_color && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001235 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea, load_index, SyncOrdering::kColorAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001236 aspect = "color";
1237 } else {
John Zulauf57261402021-08-13 11:32:06 -06001238 if (has_depth && (load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001239 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_index,
1240 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001241 aspect = "depth";
1242 }
John Zulauf57261402021-08-13 11:32:06 -06001243 if (!hazard.hazard && has_stencil && (stencil_load_index != SYNC_ACCESS_INDEX_NONE)) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001244 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, stencil_load_index,
1245 SyncOrdering::kDepthStencilAttachment);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001246 aspect = "stencil";
1247 checked_stencil = true;
1248 }
1249 }
1250
1251 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09001252 const char *func_name = CommandTypeString(cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001253 auto load_op_string = string_VkAttachmentLoadOp(checked_stencil ? ci.stencilLoadOp : ci.loadOp);
John Zulaufbb890452021-12-14 11:30:18 -07001254 const auto &sync_state = exec_context.GetSyncState();
John Zulaufee984022022-04-13 16:39:50 -06001255 if (hazard.tag == kInvalidTag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001256 // Hazard vs. ILT
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001257 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulaufb02c1eb2020-10-06 16:33:36 -06001258 "%s: Hazard %s vs. layout transition in subpass %" PRIu32 " for attachment %" PRIu32
1259 " aspect %s during load with loadOp %s.",
1260 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string);
1261 } else {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06001262 skip |= sync_state.LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
John Zulauf1507ee42020-05-18 11:33:09 -06001263 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
John Zulauf59e25072020-07-17 10:55:21 -06001264 " aspect %s during load with loadOp %s. Access info %s.",
locke-lunarg88dbb542020-06-23 22:05:42 -06001265 func_name, string_SyncHazard(hazard.hazard), subpass, i, aspect, load_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001266 exec_context.FormatHazard(hazard).c_str());
John Zulauf1507ee42020-05-18 11:33:09 -06001267 }
1268 }
1269 }
1270 }
1271 return skip;
1272}
1273
John Zulaufaff20662020-06-01 14:07:58 -06001274// Store operation validation can ignore resolve (before it) and layout tranistions after it. The first is ignored
1275// because of the ordering guarantees w.r.t. sample access and that the resolve validation hasn't altered the state, because
1276// store is part of the same Next/End operation.
1277// The latter is handled in layout transistion validation directly
John Zulaufbb890452021-12-14 11:30:18 -07001278bool AccessContext::ValidateStoreOperation(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufaff20662020-06-01 14:07:58 -06001279 const VkRect2D &render_area, uint32_t subpass,
sjfricke0bea06e2022-06-05 09:22:26 +09001280 const AttachmentViewGenVector &attachment_views, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06001281 bool skip = false;
1282 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001283
1284 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1285 if (subpass == rp_state.attachment_last_subpass[i]) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001286 const AttachmentViewGen &view_gen = attachment_views[i];
1287 if (!view_gen.IsValid()) continue;
John Zulaufaff20662020-06-01 14:07:58 -06001288 const auto &ci = attachment_ci[i];
1289
1290 // The spec states that "don't care" is an operation with VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
1291 // so we assume that an implementation is *free* to write in that case, meaning that for correctness
1292 // sake, we treat DONT_CARE as writing.
1293 const bool has_depth = FormatHasDepth(ci.format);
1294 const bool has_stencil = FormatHasStencil(ci.format);
1295 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001296 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001297 if (!has_stencil && !store_op_stores) continue;
1298
1299 HazardResult hazard;
1300 const char *aspect = nullptr;
1301 bool checked_stencil = false;
1302 if (is_color) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001303 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
1304 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001305 aspect = "color";
1306 } else {
John Zulauf57261402021-08-13 11:32:06 -06001307 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001308 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001309 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1310 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001311 aspect = "depth";
1312 }
1313 if (!hazard.hazard && has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001314 hazard = DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1315 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster);
John Zulaufaff20662020-06-01 14:07:58 -06001316 aspect = "stencil";
1317 checked_stencil = true;
1318 }
1319 }
1320
1321 if (hazard.hazard) {
1322 const char *const op_type_string = checked_stencil ? "stencilStoreOp" : "storeOp";
1323 const char *const store_op_string = string_VkAttachmentStoreOp(checked_stencil ? ci.stencilStoreOp : ci.storeOp);
John Zulauf397e68b2022-04-19 11:44:07 -06001324 skip |= exec_context.GetSyncState().LogError(rp_state.renderPass(), string_SyncHazardVUID(hazard.hazard),
1325 "%s: Hazard %s in subpass %" PRIu32 " for attachment %" PRIu32
1326 " %s aspect during store with %s %s. Access info %s",
sjfricke0bea06e2022-06-05 09:22:26 +09001327 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard), subpass,
1328 i, aspect, op_type_string, store_op_string,
John Zulauf397e68b2022-04-19 11:44:07 -06001329 exec_context.FormatHazard(hazard).c_str());
John Zulaufaff20662020-06-01 14:07:58 -06001330 }
1331 }
1332 }
1333 return skip;
1334}
1335
John Zulaufbb890452021-12-14 11:30:18 -07001336bool AccessContext::ValidateResolveOperations(const CommandExecutionContext &exec_context, const RENDER_PASS_STATE &rp_state,
John Zulaufd0ec59f2021-03-13 14:25:08 -07001337 const VkRect2D &render_area, const AttachmentViewGenVector &attachment_views,
sjfricke0bea06e2022-06-05 09:22:26 +09001338 CMD_TYPE cmd_type, uint32_t subpass) const {
1339 ValidateResolveAction validate_action(rp_state.renderPass(), subpass, *this, exec_context, cmd_type);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001340 ResolveOperation(validate_action, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001341 return validate_action.GetSkip();
John Zulaufb027cdb2020-05-21 14:25:22 -06001342}
1343
John Zulauf06f6f1e2022-04-19 15:28:11 -06001344void AccessContext::AddAsyncContext(const AccessContext *context) { async_.emplace_back(context); }
1345
John Zulauf3d84f1b2020-03-09 13:33:25 -06001346class HazardDetector {
1347 SyncStageAccessIndex usage_index_;
1348
1349 public:
John Zulauf5f13a792020-03-10 07:31:21 -06001350 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const { return pos->second.DetectHazard(usage_index_); }
John Zulauf14940722021-04-12 15:19:02 -06001351 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001352 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001353 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001354 explicit HazardDetector(SyncStageAccessIndex usage) : usage_index_(usage) {}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001355};
1356
John Zulauf69133422020-05-20 14:55:53 -06001357class HazardDetectorWithOrdering {
1358 const SyncStageAccessIndex usage_index_;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001359 const SyncOrdering ordering_rule_;
John Zulauf69133422020-05-20 14:55:53 -06001360
1361 public:
1362 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001363 return pos->second.DetectHazard(usage_index_, ordering_rule_, QueueSyncState::kQueueIdInvalid);
John Zulauf69133422020-05-20 14:55:53 -06001364 }
John Zulauf14940722021-04-12 15:19:02 -06001365 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001366 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf69133422020-05-20 14:55:53 -06001367 }
John Zulauf8e3c3e92021-01-06 11:19:36 -07001368 HazardDetectorWithOrdering(SyncStageAccessIndex usage, SyncOrdering ordering) : usage_index_(usage), ordering_rule_(ordering) {}
John Zulauf69133422020-05-20 14:55:53 -06001369};
1370
John Zulauf16adfc92020-04-08 10:28:33 -06001371HazardResult AccessContext::DetectHazard(const BUFFER_STATE &buffer, SyncStageAccessIndex usage_index,
John Zulauf355e49b2020-04-24 15:11:15 -06001372 const ResourceAccessRange &range) const {
John Zulauf16adfc92020-04-08 10:28:33 -06001373 if (!SimpleBinding(buffer)) return HazardResult();
John Zulauf150e5332020-12-03 08:52:52 -07001374 const auto base_address = ResourceBaseAddress(buffer);
1375 HazardDetector detector(usage_index);
1376 return DetectHazard(AccessAddressType::kLinear, detector, (range + base_address), DetectOptions::kDetectAll);
John Zulaufe5da6e52020-03-18 15:32:18 -06001377}
1378
John Zulauf69133422020-05-20 14:55:53 -06001379template <typename Detector>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001380HazardResult AccessContext::DetectHazard(Detector &detector, const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1381 DetectOptions options) const {
1382 const auto *attachment_gen = view_gen.GetRangeGen(gen_type);
1383 if (!attachment_gen) return HazardResult();
1384
1385 subresource_adapter::ImageRangeGenerator range_gen(*attachment_gen);
1386 const auto address_type = view_gen.GetAddressType();
1387 for (; range_gen->non_empty(); ++range_gen) {
1388 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1389 if (hazard.hazard) return hazard;
1390 }
1391
1392 return HazardResult();
1393}
1394
1395template <typename Detector>
John Zulauf69133422020-05-20 14:55:53 -06001396HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
1397 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001398 const VkExtent3D &extent, bool is_depth_sliced, DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001399 if (!SimpleBinding(image)) return HazardResult();
John Zulauf69133422020-05-20 14:55:53 -06001400 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001401 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001402 base_address, is_depth_sliced);
John Zulauf150e5332020-12-03 08:52:52 -07001403 const auto address_type = ImageAddressType(image);
John Zulauf69133422020-05-20 14:55:53 -06001404 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf150e5332020-12-03 08:52:52 -07001405 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
John Zulauf69133422020-05-20 14:55:53 -06001406 if (hazard.hazard) return hazard;
1407 }
1408 return HazardResult();
1409}
John Zulauf110413c2021-03-20 05:38:38 -06001410template <typename Detector>
1411HazardResult AccessContext::DetectHazard(Detector &detector, const IMAGE_STATE &image,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001412 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced,
1413 DetectOptions options) const {
John Zulauf110413c2021-03-20 05:38:38 -06001414 if (!SimpleBinding(image)) return HazardResult();
1415 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001416 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
1417 is_depth_sliced);
John Zulauf110413c2021-03-20 05:38:38 -06001418 const auto address_type = ImageAddressType(image);
1419 for (; range_gen->non_empty(); ++range_gen) {
John Zulauf110413c2021-03-20 05:38:38 -06001420 HazardResult hazard = DetectHazard(address_type, detector, *range_gen, options);
1421 if (hazard.hazard) return hazard;
1422 }
1423 return HazardResult();
1424}
John Zulauf69133422020-05-20 14:55:53 -06001425
John Zulauf540266b2020-04-06 18:54:53 -06001426HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
1427 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001428 const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001429 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1430 subresource.layerCount};
John Zulauf110413c2021-03-20 05:38:38 -06001431 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001432 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf1507ee42020-05-18 11:33:09 -06001433}
1434
1435HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001436 const VkImageSubresourceRange &subresource_range, bool is_depth_sliced) const {
John Zulauf69133422020-05-20 14:55:53 -06001437 HazardDetector detector(current_usage);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001438 return DetectHazard(detector, image, subresource_range, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf69133422020-05-20 14:55:53 -06001439}
1440
John Zulaufd0ec59f2021-03-13 14:25:08 -07001441HazardResult AccessContext::DetectHazard(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
1442 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule) const {
1443 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
1444 return DetectHazard(detector, view_gen, gen_type, DetectOptions::kDetectAll);
1445}
1446
John Zulauf69133422020-05-20 14:55:53 -06001447HazardResult AccessContext::DetectHazard(const IMAGE_STATE &image, SyncStageAccessIndex current_usage,
John Zulauf8e3c3e92021-01-06 11:19:36 -07001448 const VkImageSubresourceRange &subresource_range, SyncOrdering ordering_rule,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001449 const VkOffset3D &offset, const VkExtent3D &extent, bool is_depth_sliced) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001450 HazardDetectorWithOrdering detector(current_usage, ordering_rule);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001451 return DetectHazard(detector, image, subresource_range, offset, extent, is_depth_sliced, DetectOptions::kDetectAll);
John Zulauf9cb530d2019-09-30 14:14:10 -06001452}
1453
John Zulauf3d84f1b2020-03-09 13:33:25 -06001454class BarrierHazardDetector {
1455 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001456 BarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulauf3d84f1b2020-03-09 13:33:25 -06001457 SyncStageAccessFlags src_access_scope)
1458 : usage_index_(usage_index), src_exec_scope_(src_exec_scope), src_access_scope_(src_access_scope) {}
1459
John Zulauf5f13a792020-03-10 07:31:21 -06001460 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06001461 return pos->second.DetectBarrierHazard(usage_index_, QueueSyncState::kQueueIdInvalid, src_exec_scope_, src_access_scope_);
John Zulauf0cb5be22020-01-23 12:18:22 -07001462 }
John Zulauf14940722021-04-12 15:19:02 -06001463 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf3d84f1b2020-03-09 13:33:25 -06001464 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07001465 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001466 }
1467
1468 private:
1469 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001470 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf3d84f1b2020-03-09 13:33:25 -06001471 SyncStageAccessFlags src_access_scope_;
1472};
1473
John Zulauf4a6105a2020-11-17 15:11:05 -07001474class EventBarrierHazardDetector {
1475 public:
Jeremy Gebben40a22942020-12-22 14:22:06 -07001476 EventBarrierHazardDetector(SyncStageAccessIndex usage_index, VkPipelineStageFlags2KHR src_exec_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001477 SyncStageAccessFlags src_access_scope, const SyncEventState::ScopeMap &event_scope, QueueId queue_id,
John Zulauf14940722021-04-12 15:19:02 -06001478 ResourceUsageTag scope_tag)
John Zulauf4a6105a2020-11-17 15:11:05 -07001479 : usage_index_(usage_index),
1480 src_exec_scope_(src_exec_scope),
1481 src_access_scope_(src_access_scope),
1482 event_scope_(event_scope),
John Zulaufe0757ba2022-06-10 16:51:45 -06001483 scope_queue_id_(queue_id),
1484 scope_tag_(scope_tag),
John Zulauf4a6105a2020-11-17 15:11:05 -07001485 scope_pos_(event_scope.cbegin()),
John Zulaufe0757ba2022-06-10 16:51:45 -06001486 scope_end_(event_scope.cend()) {}
John Zulauf4a6105a2020-11-17 15:11:05 -07001487
John Zulaufe0757ba2022-06-10 16:51:45 -06001488 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) {
1489 // Need to piece together coverage of pos->first range:
1490 // Copy the range as we'll be chopping it up as needed
1491 ResourceAccessRange range = pos->first;
1492 const ResourceAccessState &access = pos->second;
1493 HazardResult hazard;
1494
1495 bool in_scope = AdvanceScope(range);
1496 bool unscoped_tested = false;
1497 while (in_scope && !hazard.IsHazard()) {
1498 if (range.begin < ScopeBegin()) {
1499 if (!unscoped_tested) {
1500 unscoped_tested = true;
1501 hazard = access.DetectHazard(usage_index_);
1502 }
1503 // Note: don't need to check for in_scope as AdvanceScope true means range and ScopeRange intersect.
1504 // Thus a [ ScopeBegin, range.end ) will be non-empty.
1505 range.begin = ScopeBegin();
1506 } else { // in_scope implied that ScopeRange and range intersect
1507 hazard = access.DetectBarrierHazard(usage_index_, ScopeState(), src_exec_scope_, src_access_scope_, scope_queue_id_,
1508 scope_tag_);
1509 if (!hazard.IsHazard()) {
1510 range.begin = ScopeEnd();
1511 in_scope = AdvanceScope(range); // contains a non_empty check
1512 }
1513 }
John Zulauf4a6105a2020-11-17 15:11:05 -07001514 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001515 if (range.non_empty() && !hazard.IsHazard() && !unscoped_tested) {
1516 hazard = access.DetectHazard(usage_index_);
1517 }
1518 return hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07001519 }
John Zulaufe0757ba2022-06-10 16:51:45 -06001520
John Zulauf14940722021-04-12 15:19:02 -06001521 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001522 // Async barrier hazard detection can use the same path as the usage index is not IsRead, but is IsWrite
1523 return pos->second.DetectAsyncHazard(usage_index_, start_tag);
1524 }
1525
1526 private:
John Zulaufe0757ba2022-06-10 16:51:45 -06001527 bool ScopeInvalid() const { return scope_pos_ == scope_end_; }
1528 bool ScopeValid() const { return !ScopeInvalid(); }
1529 void ScopeSeek(const ResourceAccessRange &range) { scope_pos_ = event_scope_.lower_bound(range); }
1530
1531 // Hiding away the std::pair grunge...
1532 ResourceAddress ScopeBegin() const { return scope_pos_->first.begin; }
1533 ResourceAddress ScopeEnd() const { return scope_pos_->first.end; }
1534 const ResourceAccessRange &ScopeRange() const { return scope_pos_->first; }
1535 const ResourceAccessState &ScopeState() const { return scope_pos_->second; }
1536
1537 bool AdvanceScope(const ResourceAccessRange &range) {
1538 // Note: non_empty is (valid && !empty), so don't change !non_empty to empty...
1539 if (!range.non_empty()) return false;
1540 if (ScopeInvalid()) return false;
1541
1542 if (ScopeRange().strictly_less(range)) {
1543 ScopeSeek(range);
1544 }
1545
1546 return ScopeValid() && ScopeRange().intersects(range);
1547 }
1548
John Zulauf4a6105a2020-11-17 15:11:05 -07001549 SyncStageAccessIndex usage_index_;
Jeremy Gebben40a22942020-12-22 14:22:06 -07001550 VkPipelineStageFlags2KHR src_exec_scope_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001551 SyncStageAccessFlags src_access_scope_;
1552 const SyncEventState::ScopeMap &event_scope_;
John Zulaufe0757ba2022-06-10 16:51:45 -06001553 QueueId scope_queue_id_;
1554 const ResourceUsageTag scope_tag_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001555 SyncEventState::ScopeMap::const_iterator scope_pos_;
1556 SyncEventState::ScopeMap::const_iterator scope_end_;
John Zulauf4a6105a2020-11-17 15:11:05 -07001557};
1558
John Zulaufe0757ba2022-06-10 16:51:45 -06001559HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range,
1560 VkPipelineStageFlags2KHR src_exec_scope,
1561 const SyncStageAccessFlags &src_access_scope, QueueId queue_id,
1562 const SyncEventState &sync_event, AccessContext::DetectOptions options) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07001563 // It's not particularly DRY to get the address type in this function as well as lower down, but we have to select the
1564 // first access scope map to use, and there's no easy way to plumb it in below.
1565 const auto address_type = ImageAddressType(image);
1566 const auto &event_scope = sync_event.FirstScope(address_type);
1567
1568 EventBarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope,
John Zulaufe0757ba2022-06-10 16:51:45 -06001569 event_scope, queue_id, sync_event.first_scope_tag);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001570 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf4a6105a2020-11-17 15:11:05 -07001571}
1572
John Zulaufd0ec59f2021-03-13 14:25:08 -07001573HazardResult AccessContext::DetectImageBarrierHazard(const AttachmentViewGen &view_gen, const SyncBarrier &barrier,
1574 DetectOptions options) const {
1575 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, barrier.src_exec_scope.exec_scope,
1576 barrier.src_access_scope);
1577 return DetectHazard(detector, view_gen, AttachmentViewGen::Gen::kViewSubresource, options);
1578}
1579
Jeremy Gebben40a22942020-12-22 14:22:06 -07001580HazardResult AccessContext::DetectImageBarrierHazard(const IMAGE_STATE &image, VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07001581 const SyncStageAccessFlags &src_access_scope,
John Zulauf355e49b2020-04-24 15:11:15 -06001582 const VkImageSubresourceRange &subresource_range,
John Zulauf43cc7462020-12-03 12:33:12 -07001583 const DetectOptions options) const {
John Zulauf69133422020-05-20 14:55:53 -06001584 BarrierHazardDetector detector(SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION, src_exec_scope, src_access_scope);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001585 return DetectHazard(detector, image, subresource_range, false, options);
John Zulauf0cb5be22020-01-23 12:18:22 -07001586}
1587
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001588HazardResult AccessContext::DetectImageBarrierHazard(const SyncImageMemoryBarrier &image_barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07001589 return DetectImageBarrierHazard(*image_barrier.image.get(), image_barrier.barrier.src_exec_scope.exec_scope,
John Zulauf110413c2021-03-20 05:38:38 -06001590 image_barrier.barrier.src_access_scope, image_barrier.range, kDetectAll);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07001591}
John Zulauf355e49b2020-04-24 15:11:15 -06001592
John Zulauf9cb530d2019-09-30 14:14:10 -06001593template <typename Flags, typename Map>
1594SyncStageAccessFlags AccessScopeImpl(Flags flag_mask, const Map &map) {
1595 SyncStageAccessFlags scope = 0;
1596 for (const auto &bit_scope : map) {
1597 if (flag_mask < bit_scope.first) break;
1598
1599 if (flag_mask & bit_scope.first) {
1600 scope |= bit_scope.second;
1601 }
1602 }
1603 return scope;
1604}
1605
Jeremy Gebben40a22942020-12-22 14:22:06 -07001606SyncStageAccessFlags SyncStageAccess::AccessScopeByStage(VkPipelineStageFlags2KHR stages) {
John Zulauf9cb530d2019-09-30 14:14:10 -06001607 return AccessScopeImpl(stages, syncStageAccessMaskByStageBit);
1608}
1609
Jeremy Gebben40a22942020-12-22 14:22:06 -07001610SyncStageAccessFlags SyncStageAccess::AccessScopeByAccess(VkAccessFlags2KHR accesses) {
1611 return AccessScopeImpl(sync_utils::ExpandAccessFlags(accesses), syncStageAccessMaskByAccessBit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001612}
1613
Jeremy Gebben40a22942020-12-22 14:22:06 -07001614// Getting from stage mask and access mask to stage/access masks is something we need to be good at...
1615SyncStageAccessFlags SyncStageAccess::AccessScope(VkPipelineStageFlags2KHR stages, VkAccessFlags2KHR accesses) {
John Zulauf5f13a792020-03-10 07:31:21 -06001616 // The access scope is the intersection of all stage/access types possible for the enabled stages and the enables
1617 // accesses (after doing a couple factoring of common terms the union of stage/access intersections is the intersections
1618 // of the union of all stage/access types for all the stages and the same unions for the access mask...
John Zulauf9cb530d2019-09-30 14:14:10 -06001619 return AccessScopeByStage(stages) & AccessScopeByAccess(accesses);
1620}
1621
1622template <typename Action>
John Zulauf5c5e88d2019-12-26 11:22:02 -07001623void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const ResourceAccessRange &range, const Action &action) {
John Zulauf7635de32020-05-29 17:14:15 -06001624 // TODO: Optimization for operations that do a pure overwrite (i.e. WRITE usages which rewrite the state, vs READ usages
1625 // that do incrementalupdates
John Zulauf4a6105a2020-11-17 15:11:05 -07001626 assert(accesses);
John Zulauf9cb530d2019-09-30 14:14:10 -06001627 auto pos = accesses->lower_bound(range);
1628 if (pos == accesses->end() || !pos->first.intersects(range)) {
1629 // The range is empty, fill it with a default value.
1630 pos = action.Infill(accesses, pos, range);
1631 } else if (range.begin < pos->first.begin) {
1632 // Leading empty space, infill
John Zulauf5c5e88d2019-12-26 11:22:02 -07001633 pos = action.Infill(accesses, pos, ResourceAccessRange(range.begin, pos->first.begin));
John Zulauf9cb530d2019-09-30 14:14:10 -06001634 } else if (pos->first.begin < range.begin) {
1635 // Trim the beginning if needed
1636 pos = accesses->split(pos, range.begin, sparse_container::split_op_keep_both());
1637 ++pos;
1638 }
1639
1640 const auto the_end = accesses->end();
1641 while ((pos != the_end) && pos->first.intersects(range)) {
1642 if (pos->first.end > range.end) {
1643 pos = accesses->split(pos, range.end, sparse_container::split_op_keep_both());
1644 }
1645
1646 pos = action(accesses, pos);
1647 if (pos == the_end) break;
1648
1649 auto next = pos;
1650 ++next;
1651 if ((pos->first.end < range.end) && (next != the_end) && !next->first.is_subsequent_to(pos->first)) {
1652 // Need to infill if next is disjoint
1653 VkDeviceSize limit = (next == the_end) ? range.end : std::min(range.end, next->first.begin);
John Zulauf5c5e88d2019-12-26 11:22:02 -07001654 ResourceAccessRange new_range(pos->first.end, limit);
John Zulauf9cb530d2019-09-30 14:14:10 -06001655 next = action.Infill(accesses, next, new_range);
1656 }
1657 pos = next;
1658 }
1659}
John Zulaufd5115702021-01-18 12:34:33 -07001660
1661// Give a comparable interface for range generators and ranges
1662template <typename Action>
John Zulaufcb7e1672022-05-04 13:46:08 -06001663void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, ResourceAccessRange *range) {
John Zulaufd5115702021-01-18 12:34:33 -07001664 assert(range);
1665 UpdateMemoryAccessState(accesses, *range, action);
1666}
1667
John Zulauf4a6105a2020-11-17 15:11:05 -07001668template <typename Action, typename RangeGen>
1669void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, RangeGen *range_gen_arg) {
1670 assert(range_gen_arg);
John Zulaufd5115702021-01-18 12:34:33 -07001671 RangeGen &range_gen = *range_gen_arg; // Non-const references must be * by style requirement but deref-ing * iterator is a pain
John Zulauf4a6105a2020-11-17 15:11:05 -07001672 for (; range_gen->non_empty(); ++range_gen) {
1673 UpdateMemoryAccessState(accesses, *range_gen, action);
1674 }
1675}
John Zulauf9cb530d2019-09-30 14:14:10 -06001676
John Zulaufd0ec59f2021-03-13 14:25:08 -07001677template <typename Action, typename RangeGen>
1678void UpdateMemoryAccessState(ResourceAccessRangeMap *accesses, const Action &action, const RangeGen &range_gen_prebuilt) {
1679 RangeGen range_gen(range_gen_prebuilt); // RangeGenerators can be expensive to create from scratch... initialize from built
1680 for (; range_gen->non_empty(); ++range_gen) {
1681 UpdateMemoryAccessState(accesses, *range_gen, action);
1682 }
1683}
John Zulauf9cb530d2019-09-30 14:14:10 -06001684struct UpdateMemoryAccessStateFunctor {
John Zulauf5c5e88d2019-12-26 11:22:02 -07001685 using Iterator = ResourceAccessRangeMap::iterator;
1686 Iterator Infill(ResourceAccessRangeMap *accesses, Iterator pos, ResourceAccessRange range) const {
John Zulauf5f13a792020-03-10 07:31:21 -06001687 // this is only called on gaps, and never returns a gap.
1688 ResourceAccessState default_state;
John Zulauf16adfc92020-04-08 10:28:33 -06001689 context.ResolvePreviousAccess(type, range, accesses, &default_state);
John Zulauf5f13a792020-03-10 07:31:21 -06001690 return accesses->lower_bound(range);
John Zulauf9cb530d2019-09-30 14:14:10 -06001691 }
John Zulauf5f13a792020-03-10 07:31:21 -06001692
John Zulauf5c5e88d2019-12-26 11:22:02 -07001693 Iterator operator()(ResourceAccessRangeMap *accesses, Iterator pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001694 auto &access_state = pos->second;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001695 access_state.Update(usage, ordering_rule, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06001696 return pos;
1697 }
1698
John Zulauf43cc7462020-12-03 12:33:12 -07001699 UpdateMemoryAccessStateFunctor(AccessAddressType type_, const AccessContext &context_, SyncStageAccessIndex usage_,
John Zulauf14940722021-04-12 15:19:02 -06001700 SyncOrdering ordering_rule_, ResourceUsageTag tag_)
John Zulauf8e3c3e92021-01-06 11:19:36 -07001701 : type(type_), context(context_), usage(usage_), ordering_rule(ordering_rule_), tag(tag_) {}
John Zulauf43cc7462020-12-03 12:33:12 -07001702 const AccessAddressType type;
John Zulauf540266b2020-04-06 18:54:53 -06001703 const AccessContext &context;
John Zulauf16adfc92020-04-08 10:28:33 -06001704 const SyncStageAccessIndex usage;
John Zulauf8e3c3e92021-01-06 11:19:36 -07001705 const SyncOrdering ordering_rule;
John Zulauf14940722021-04-12 15:19:02 -06001706 const ResourceUsageTag tag;
John Zulauf9cb530d2019-09-30 14:14:10 -06001707};
1708
John Zulauf4a6105a2020-11-17 15:11:05 -07001709// The barrier operation for pipeline and subpass dependencies`
John Zulauf1e331ec2020-12-04 18:29:38 -07001710struct PipelineBarrierOp {
1711 SyncBarrier barrier;
1712 bool layout_transition;
John Zulauf00119522022-05-23 19:07:42 -06001713 ResourceAccessState::QueueScopeOps scope;
1714 PipelineBarrierOp(QueueId queue_id, const SyncBarrier &barrier_, bool layout_transition_)
1715 : barrier(barrier_), layout_transition(layout_transition_), scope(queue_id) {}
John Zulaufd5115702021-01-18 12:34:33 -07001716 PipelineBarrierOp(const PipelineBarrierOp &) = default;
John Zulauf00119522022-05-23 19:07:42 -06001717 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope, barrier, layout_transition); }
John Zulauf1e331ec2020-12-04 18:29:38 -07001718};
John Zulauf00119522022-05-23 19:07:42 -06001719
John Zulaufecf4ac52022-06-06 10:08:42 -06001720// Batch barrier ops don't modify in place, and thus don't need to hold pending state, and also are *never* layout transitions.
1721struct BatchBarrierOp : public PipelineBarrierOp {
1722 void operator()(ResourceAccessState *access_state) const {
1723 access_state->ApplyBarrier(scope, barrier, layout_transition);
1724 access_state->ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
1725 }
1726 BatchBarrierOp(QueueId queue_id, const SyncBarrier &barrier_) : PipelineBarrierOp(queue_id, barrier_, false) {}
1727};
1728
John Zulauf4a6105a2020-11-17 15:11:05 -07001729// The barrier operation for wait events
1730struct WaitEventBarrierOp {
John Zulaufb7578302022-05-19 13:50:18 -06001731 ResourceAccessState::EventScopeOps scope_ops;
John Zulauf4a6105a2020-11-17 15:11:05 -07001732 SyncBarrier barrier;
1733 bool layout_transition;
John Zulaufe0757ba2022-06-10 16:51:45 -06001734
1735 WaitEventBarrierOp(const QueueId scope_queue_, const ResourceUsageTag scope_tag_, const SyncBarrier &barrier_,
John Zulauf00119522022-05-23 19:07:42 -06001736 bool layout_transition_)
John Zulaufe0757ba2022-06-10 16:51:45 -06001737 : scope_ops(scope_queue_, scope_tag_), barrier(barrier_), layout_transition(layout_transition_) {}
John Zulaufb7578302022-05-19 13:50:18 -06001738 void operator()(ResourceAccessState *access_state) const { access_state->ApplyBarrier(scope_ops, barrier, layout_transition); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001739};
John Zulauf1e331ec2020-12-04 18:29:38 -07001740
John Zulauf4a6105a2020-11-17 15:11:05 -07001741// This functor applies a collection of barriers, updating the "pending state" in each touched memory range, and optionally
1742// resolves the pending state. Suitable for processing Global memory barriers, or Subpass Barriers when the "final" barrier
1743// of a collection is known/present.
John Zulauf5c628d02021-05-04 15:46:36 -06001744template <typename BarrierOp, typename OpVector = std::vector<BarrierOp>>
John Zulauf89311b42020-09-29 16:28:47 -06001745class ApplyBarrierOpsFunctor {
1746 public:
John Zulauf5c5e88d2019-12-26 11:22:02 -07001747 using Iterator = ResourceAccessRangeMap::iterator;
John Zulauf5c628d02021-05-04 15:46:36 -06001748 // Only called with a gap, and pos at the lower_bound(range)
1749 inline Iterator Infill(ResourceAccessRangeMap *accesses, const Iterator &pos, const ResourceAccessRange &range) const {
1750 if (!infill_default_) {
1751 return pos;
1752 }
1753 ResourceAccessState default_state;
1754 auto inserted = accesses->insert(pos, std::make_pair(range, default_state));
1755 return inserted;
1756 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001757
John Zulauf5c628d02021-05-04 15:46:36 -06001758 Iterator operator()(ResourceAccessRangeMap *accesses, const Iterator &pos) const {
John Zulauf9cb530d2019-09-30 14:14:10 -06001759 auto &access_state = pos->second;
John Zulauf1e331ec2020-12-04 18:29:38 -07001760 for (const auto &op : barrier_ops_) {
1761 op(&access_state);
John Zulauf89311b42020-09-29 16:28:47 -06001762 }
John Zulauf9cb530d2019-09-30 14:14:10 -06001763
John Zulauf89311b42020-09-29 16:28:47 -06001764 if (resolve_) {
1765 // If this is the last (or only) batch, we can do the pending resolve as the last step in this operation to avoid
1766 // another walk
1767 access_state.ApplyPendingBarriers(tag_);
John Zulauf9cb530d2019-09-30 14:14:10 -06001768 }
1769 return pos;
1770 }
1771
John Zulauf89311b42020-09-29 16:28:47 -06001772 // A valid tag is required IFF layout_transition is true, as transitions are write ops
John Zulauf5c628d02021-05-04 15:46:36 -06001773 ApplyBarrierOpsFunctor(bool resolve, typename OpVector::size_type size_hint, ResourceUsageTag tag)
1774 : resolve_(resolve), infill_default_(false), barrier_ops_(), tag_(tag) {
John Zulaufd5115702021-01-18 12:34:33 -07001775 barrier_ops_.reserve(size_hint);
1776 }
John Zulauf5c628d02021-05-04 15:46:36 -06001777 void EmplaceBack(const BarrierOp &op) {
1778 barrier_ops_.emplace_back(op);
1779 infill_default_ |= op.layout_transition;
1780 }
John Zulauf89311b42020-09-29 16:28:47 -06001781
1782 private:
1783 bool resolve_;
John Zulauf5c628d02021-05-04 15:46:36 -06001784 bool infill_default_;
1785 OpVector barrier_ops_;
John Zulauf14940722021-04-12 15:19:02 -06001786 const ResourceUsageTag tag_;
John Zulauf1e331ec2020-12-04 18:29:38 -07001787};
1788
John Zulauf4a6105a2020-11-17 15:11:05 -07001789// This functor applies a single barrier, updating the "pending state" in each touched memory range, but does not
1790// resolve the pendinging state. Suitable for processing Image and Buffer barriers from PipelineBarriers or Events
1791template <typename BarrierOp>
John Zulauf5c628d02021-05-04 15:46:36 -06001792class ApplyBarrierFunctor : public ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>> {
1793 using Base = ApplyBarrierOpsFunctor<BarrierOp, small_vector<BarrierOp, 1>>;
1794
John Zulauf4a6105a2020-11-17 15:11:05 -07001795 public:
John Zulaufee984022022-04-13 16:39:50 -06001796 ApplyBarrierFunctor(const BarrierOp &barrier_op) : Base(false, 1, kInvalidTag) { Base::EmplaceBack(barrier_op); }
John Zulauf4a6105a2020-11-17 15:11:05 -07001797};
1798
John Zulauf1e331ec2020-12-04 18:29:38 -07001799// This functor resolves the pendinging state.
John Zulauf5c628d02021-05-04 15:46:36 -06001800class ResolvePendingBarrierFunctor : public ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>> {
1801 using Base = ApplyBarrierOpsFunctor<NoopBarrierAction, small_vector<NoopBarrierAction, 1>>;
1802
John Zulauf1e331ec2020-12-04 18:29:38 -07001803 public:
John Zulauf5c628d02021-05-04 15:46:36 -06001804 ResolvePendingBarrierFunctor(ResourceUsageTag tag) : Base(true, 0, tag) {}
John Zulauf9cb530d2019-09-30 14:14:10 -06001805};
1806
John Zulauf8e3c3e92021-01-06 11:19:36 -07001807void AccessContext::UpdateAccessState(AccessAddressType type, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001808 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf8e3c3e92021-01-06 11:19:36 -07001809 UpdateMemoryAccessStateFunctor action(type, *this, current_usage, ordering_rule, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001810 UpdateMemoryAccessState(&GetAccessStateMap(type), range, action);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001811}
1812
John Zulauf8e3c3e92021-01-06 11:19:36 -07001813void AccessContext::UpdateAccessState(const BUFFER_STATE &buffer, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf14940722021-04-12 15:19:02 -06001814 const ResourceAccessRange &range, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001815 if (!SimpleBinding(buffer)) return;
1816 const auto base_address = ResourceBaseAddress(buffer);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001817 UpdateAccessState(AccessAddressType::kLinear, current_usage, ordering_rule, range + base_address, tag);
John Zulauf16adfc92020-04-08 10:28:33 -06001818}
John Zulauf355e49b2020-04-24 15:11:15 -06001819
John Zulauf8e3c3e92021-01-06 11:19:36 -07001820void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf110413c2021-03-20 05:38:38 -06001821 const VkImageSubresourceRange &subresource_range, const ResourceUsageTag &tag) {
1822 if (!SimpleBinding(image)) return;
1823 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001824 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulauf110413c2021-03-20 05:38:38 -06001825 const auto address_type = ImageAddressType(image);
1826 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1827 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
1828}
1829void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001830 const VkImageSubresourceRange &subresource_range, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001831 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf16adfc92020-04-08 10:28:33 -06001832 if (!SimpleBinding(image)) return;
John Zulauf16adfc92020-04-08 10:28:33 -06001833 const auto base_address = ResourceBaseAddress(image);
John Zulauf150e5332020-12-03 08:52:52 -07001834 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, offset, extent,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02001835 base_address, false);
John Zulauf150e5332020-12-03 08:52:52 -07001836 const auto address_type = ImageAddressType(image);
John Zulauf8e3c3e92021-01-06 11:19:36 -07001837 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
John Zulauf110413c2021-03-20 05:38:38 -06001838 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, &range_gen);
John Zulauf3d84f1b2020-03-09 13:33:25 -06001839}
John Zulaufd0ec59f2021-03-13 14:25:08 -07001840
1841void AccessContext::UpdateAccessState(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type,
John Zulauf14940722021-04-12 15:19:02 -06001842 SyncStageAccessIndex current_usage, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001843 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1844 if (!gen) return;
1845 subresource_adapter::ImageRangeGenerator range_gen(*gen);
1846 const auto address_type = view_gen.GetAddressType();
1847 UpdateMemoryAccessStateFunctor action(address_type, *this, current_usage, ordering_rule, tag);
1848 ApplyUpdateAction(address_type, action, &range_gen);
John Zulauf7635de32020-05-29 17:14:15 -06001849}
John Zulauf3d84f1b2020-03-09 13:33:25 -06001850
John Zulauf8e3c3e92021-01-06 11:19:36 -07001851void AccessContext::UpdateAccessState(const IMAGE_STATE &image, SyncStageAccessIndex current_usage, SyncOrdering ordering_rule,
John Zulauf355e49b2020-04-24 15:11:15 -06001852 const VkImageSubresourceLayers &subresource, const VkOffset3D &offset,
John Zulauf14940722021-04-12 15:19:02 -06001853 const VkExtent3D &extent, const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06001854 VkImageSubresourceRange subresource_range = {subresource.aspectMask, subresource.mipLevel, 1, subresource.baseArrayLayer,
1855 subresource.layerCount};
John Zulauf8e3c3e92021-01-06 11:19:36 -07001856 UpdateAccessState(image, current_usage, ordering_rule, subresource_range, offset, extent, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06001857}
1858
John Zulaufd0ec59f2021-03-13 14:25:08 -07001859template <typename Action, typename RangeGen>
1860void AccessContext::ApplyUpdateAction(AccessAddressType address_type, const Action &action, RangeGen *range_gen_arg) {
1861 assert(range_gen_arg); // Old Google C++ styleguide require non-const object pass by * not &, but this isn't an optional arg.
1862 UpdateMemoryAccessState(&GetAccessStateMap(address_type), action, range_gen_arg);
John Zulauf540266b2020-04-06 18:54:53 -06001863}
1864
1865template <typename Action>
John Zulaufd0ec59f2021-03-13 14:25:08 -07001866void AccessContext::ApplyUpdateAction(const AttachmentViewGen &view_gen, AttachmentViewGen::Gen gen_type, const Action &action) {
1867 const ImageRangeGen *gen = view_gen.GetRangeGen(gen_type);
1868 if (!gen) return;
1869 UpdateMemoryAccessState(&GetAccessStateMap(view_gen.GetAddressType()), action, *gen);
John Zulauf540266b2020-04-06 18:54:53 -06001870}
1871
John Zulaufd0ec59f2021-03-13 14:25:08 -07001872void AccessContext::UpdateAttachmentResolveAccess(const RENDER_PASS_STATE &rp_state,
1873 const AttachmentViewGenVector &attachment_views, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001874 const ResourceUsageTag tag) {
John Zulauf7635de32020-05-29 17:14:15 -06001875 UpdateStateResolveAction update(*this, tag);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001876 ResolveOperation(update, rp_state, attachment_views, subpass);
John Zulauf7635de32020-05-29 17:14:15 -06001877}
1878
John Zulaufd0ec59f2021-03-13 14:25:08 -07001879void AccessContext::UpdateAttachmentStoreAccess(const RENDER_PASS_STATE &rp_state, const AttachmentViewGenVector &attachment_views,
John Zulauf14940722021-04-12 15:19:02 -06001880 uint32_t subpass, const ResourceUsageTag tag) {
John Zulaufaff20662020-06-01 14:07:58 -06001881 const auto *attachment_ci = rp_state.createInfo.pAttachments;
John Zulaufaff20662020-06-01 14:07:58 -06001882
1883 for (uint32_t i = 0; i < rp_state.createInfo.attachmentCount; i++) {
1884 if (rp_state.attachment_last_subpass[i] == subpass) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001885 const auto &view_gen = attachment_views[i];
1886 if (!view_gen.IsValid()) continue; // UNUSED
John Zulaufaff20662020-06-01 14:07:58 -06001887
1888 const auto &ci = attachment_ci[i];
1889 const bool has_depth = FormatHasDepth(ci.format);
1890 const bool has_stencil = FormatHasStencil(ci.format);
1891 const bool is_color = !(has_depth || has_stencil);
John Zulauf57261402021-08-13 11:32:06 -06001892 const bool store_op_stores = ci.storeOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001893
1894 if (is_color && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001895 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
1896 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001897 } else {
John Zulaufaff20662020-06-01 14:07:58 -06001898 if (has_depth && store_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001899 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
1900 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001901 }
John Zulauf57261402021-08-13 11:32:06 -06001902 const bool stencil_op_stores = ci.stencilStoreOp != VK_ATTACHMENT_STORE_OP_NONE_EXT;
John Zulaufaff20662020-06-01 14:07:58 -06001903 if (has_stencil && stencil_op_stores) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07001904 UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
1905 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE, SyncOrdering::kRaster, tag);
John Zulaufaff20662020-06-01 14:07:58 -06001906 }
1907 }
1908 }
1909 }
1910}
1911
John Zulauf540266b2020-04-06 18:54:53 -06001912template <typename Action>
John Zulaufd5115702021-01-18 12:34:33 -07001913void AccessContext::ApplyToContext(const Action &barrier_action) {
John Zulauf540266b2020-04-06 18:54:53 -06001914 // Note: Barriers do *not* cross context boundaries, applying to accessess within.... (at least for renderpass subpasses)
John Zulauf16adfc92020-04-08 10:28:33 -06001915 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001916 UpdateMemoryAccessState(&GetAccessStateMap(address_type), kFullRange, barrier_action);
John Zulauf540266b2020-04-06 18:54:53 -06001917 }
1918}
1919
1920void AccessContext::ResolveChildContexts(const std::vector<AccessContext> &contexts) {
John Zulauf540266b2020-04-06 18:54:53 -06001921 for (uint32_t subpass_index = 0; subpass_index < contexts.size(); subpass_index++) {
1922 auto &context = contexts[subpass_index];
John Zulauf22aefed2021-03-11 18:14:35 -07001923 ApplyTrackbackStackAction barrier_action(context.GetDstExternalTrackBack().barriers);
John Zulauf16adfc92020-04-08 10:28:33 -06001924 for (const auto address_type : kAddressTypes) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001925 context.ResolveAccessRange(address_type, kFullRange, barrier_action, &GetAccessStateMap(address_type), nullptr, false);
John Zulauf540266b2020-04-06 18:54:53 -06001926 }
1927 }
1928}
1929
John Zulauf4fa68462021-04-26 21:04:22 -06001930// Caller must ensure that lifespan of this is less than from
1931void AccessContext::ImportAsyncContexts(const AccessContext &from) { async_ = from.async_; }
1932
John Zulauf355e49b2020-04-24 15:11:15 -06001933// Suitable only for *subpass* access contexts
John Zulaufd0ec59f2021-03-13 14:25:08 -07001934HazardResult AccessContext::DetectSubpassTransitionHazard(const TrackBack &track_back, const AttachmentViewGen &attach_view) const {
1935 if (!attach_view.IsValid()) return HazardResult();
John Zulauf355e49b2020-04-24 15:11:15 -06001936
John Zulauf355e49b2020-04-24 15:11:15 -06001937 // We should never ask for a transition from a context we don't have
John Zulaufbb890452021-12-14 11:30:18 -07001938 assert(track_back.source_subpass);
John Zulauf355e49b2020-04-24 15:11:15 -06001939
1940 // Do the detection against the specific prior context independent of other contexts. (Synchronous only)
John Zulaufa0a98292020-09-18 09:30:10 -06001941 // Hazard detection for the transition can be against the merged of the barriers (it only uses src_...)
1942 const auto merged_barrier = MergeBarriers(track_back.barriers);
John Zulaufbb890452021-12-14 11:30:18 -07001943 HazardResult hazard = track_back.source_subpass->DetectImageBarrierHazard(attach_view, merged_barrier, kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06001944 if (!hazard.hazard) {
1945 // The Async hazard check is against the current context's async set.
John Zulaufd0ec59f2021-03-13 14:25:08 -07001946 hazard = DetectImageBarrierHazard(attach_view, merged_barrier, kDetectAsync);
John Zulauf355e49b2020-04-24 15:11:15 -06001947 }
John Zulaufa0a98292020-09-18 09:30:10 -06001948
John Zulauf355e49b2020-04-24 15:11:15 -06001949 return hazard;
1950}
1951
John Zulaufb02c1eb2020-10-06 16:33:36 -06001952void AccessContext::RecordLayoutTransitions(const RENDER_PASS_STATE &rp_state, uint32_t subpass,
John Zulauf14940722021-04-12 15:19:02 -06001953 const AttachmentViewGenVector &attachment_views, const ResourceUsageTag tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06001954 const auto &transitions = rp_state.subpass_transitions[subpass];
John Zulauf646cc292020-10-23 09:16:45 -06001955 const ResourceAccessState empty_infill;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001956 for (const auto &transition : transitions) {
1957 const auto prev_pass = transition.prev_pass;
John Zulaufd0ec59f2021-03-13 14:25:08 -07001958 const auto &view_gen = attachment_views[transition.attachment];
1959 if (!view_gen.IsValid()) continue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001960
1961 const auto *trackback = GetTrackBackFromSubpass(prev_pass);
1962 assert(trackback);
1963
1964 // Import the attachments into the current context
John Zulaufbb890452021-12-14 11:30:18 -07001965 const auto *prev_context = trackback->source_subpass;
John Zulaufb02c1eb2020-10-06 16:33:36 -06001966 assert(prev_context);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001967 const auto address_type = view_gen.GetAddressType();
John Zulaufb02c1eb2020-10-06 16:33:36 -06001968 auto &target_map = GetAccessStateMap(address_type);
1969 ApplySubpassTransitionBarriersAction barrier_action(trackback->barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07001970 prev_context->ResolveAccessRange(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action, &target_map,
1971 &empty_infill);
John Zulaufb02c1eb2020-10-06 16:33:36 -06001972 }
1973
John Zulauf86356ca2020-10-19 11:46:41 -06001974 // If there were no transitions skip this global map walk
1975 if (transitions.size()) {
John Zulauf1e331ec2020-12-04 18:29:38 -07001976 ResolvePendingBarrierFunctor apply_pending_action(tag);
John Zulaufd5115702021-01-18 12:34:33 -07001977 ApplyToContext(apply_pending_action);
John Zulauf86356ca2020-10-19 11:46:41 -06001978 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06001979}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07001980
sjfricke0bea06e2022-06-05 09:22:26 +09001981bool CommandBufferAccessContext::ValidateDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06001982 bool skip = false;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001983 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06001984 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06001985 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001986 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06001987 return skip;
1988 }
sjfricke0bea06e2022-06-05 09:22:26 +09001989 const char *caller_name = CommandTypeString(cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06001990
1991 using DescriptorClass = cvdescriptorset::DescriptorClass;
1992 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
1993 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06001994 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
1995
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07001996 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07001997 const auto raster_state = pipe->RasterizationState();
1998 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06001999 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002000 }
locke-lunarg61870c22020-06-09 14:51:50 -06002001 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002002 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002003 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2004 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002005 SyncStageAccessIndex sync_index =
2006 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2007
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002008 for (uint32_t index = 0; index < binding->count; index++) {
2009 const auto *descriptor = binding->GetDescriptor(index);
locke-lunarg61870c22020-06-09 14:51:50 -06002010 switch (descriptor->GetClass()) {
2011 case DescriptorClass::ImageSampler:
2012 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002013 if (descriptor->Invalid()) {
2014 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002015 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002016
2017 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2018 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2019 const auto *img_view_state = image_descriptor->GetImageViewState();
2020 VkImageLayout image_layout = image_descriptor->GetImageLayout();
2021
John Zulauf361fb532020-07-22 10:45:39 -06002022 HazardResult hazard;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002023 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2024 // Descriptors, so we do not have to worry about depth slicing here.
2025 // See: VUID 00343
2026 assert(!img_view_state->IsDepthSliced());
John Zulauf110413c2021-03-20 05:38:38 -06002027 const IMAGE_STATE *img_state = img_view_state->image_state.get();
John Zulauf361fb532020-07-22 10:45:39 -06002028 const auto &subresource_range = img_view_state->normalized_subresource_range;
John Zulauf110413c2021-03-20 05:38:38 -06002029
2030 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
2031 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2032 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
John Zulauf361fb532020-07-22 10:45:39 -06002033 // Input attachments are subject to raster ordering rules
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002034 hazard =
2035 current_context_->DetectHazard(*img_state, sync_index, subresource_range, SyncOrdering::kRaster,
2036 offset, extent, img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002037 } else {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02002038 hazard = current_context_->DetectHazard(*img_state, sync_index, subresource_range,
2039 img_view_state->IsDepthSliced());
John Zulauf361fb532020-07-22 10:45:39 -06002040 }
John Zulauf110413c2021-03-20 05:38:38 -06002041
John Zulauf33fc1d52020-07-17 11:01:10 -06002042 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
John Zulauf1dae9192020-06-16 15:46:44 -06002043 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002044 img_view_state->image_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002045 "%s: Hazard %s for %s, in %s, and %s, %s, type: %s, imageLayout: %s, binding #%" PRIu32
2046 ", index %" PRIu32 ". Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002047 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002048 sync_state_->report_data->FormatHandle(img_view_state->image_view()).c_str(),
2049 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2050 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002051 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
2052 string_VkDescriptorType(descriptor_type), string_VkImageLayout(image_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002053 set_binding.first.binding, index, FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002054 }
2055 break;
2056 }
2057 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002058 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2059 if (texel_descriptor->Invalid()) {
2060 continue;
2061 }
2062 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2063 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002064 const ResourceAccessRange range = MakeRange(*buf_view_state);
locke-lunarg61870c22020-06-09 14:51:50 -06002065 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf33fc1d52020-07-17 11:01:10 -06002066 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002067 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002068 buf_view_state->buffer_view(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002069 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002070 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002071 sync_state_->report_data->FormatHandle(buf_view_state->buffer_view()).c_str(),
2072 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2073 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002074 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002075 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002076 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002077 }
2078 break;
2079 }
2080 case DescriptorClass::GeneralBuffer: {
2081 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002082 if (buffer_descriptor->Invalid()) {
2083 continue;
2084 }
2085 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002086 const ResourceAccessRange range =
2087 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
locke-lunarg61870c22020-06-09 14:51:50 -06002088 auto hazard = current_context_->DetectHazard(*buf_state, sync_index, range);
John Zulauf3ac701a2020-09-07 14:34:41 -06002089 if (hazard.hazard && !sync_state_->SupressedBoundDescriptorWAW(hazard)) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002090 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002091 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002092 "%s: Hazard %s for %s in %s, %s, and %s, type: %s, binding #%d index %d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002093 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002094 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2095 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(),
2096 sync_state_->report_data->FormatHandle(pipe->pipeline()).c_str(),
locke-lunarg7cc0ead2020-07-17 14:29:16 -06002097 sync_state_->report_data->FormatHandle(descriptor_set->GetSet()).c_str(),
Jeremy Gebben7fc88a22021-08-25 13:30:45 -06002098 string_VkDescriptorType(descriptor_type), set_binding.first.binding, index,
John Zulauf397e68b2022-04-19 11:44:07 -06002099 FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002100 }
2101 break;
2102 }
2103 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2104 default:
2105 break;
2106 }
2107 }
2108 }
2109 }
2110 return skip;
2111}
2112
2113void CommandBufferAccessContext::RecordDispatchDrawDescriptorSet(VkPipelineBindPoint pipelineBindPoint,
John Zulauf14940722021-04-12 15:19:02 -06002114 const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002115 const PIPELINE_STATE *pipe = nullptr;
locke-lunarg61870c22020-06-09 14:51:50 -06002116 const std::vector<LAST_BOUND_STATE::PER_SET> *per_sets = nullptr;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002117 cb_state_->GetCurrentPipelineAndDesriptorSets(pipelineBindPoint, &pipe, &per_sets);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002118 if (!pipe || !per_sets) {
locke-lunarg61870c22020-06-09 14:51:50 -06002119 return;
2120 }
2121
2122 using DescriptorClass = cvdescriptorset::DescriptorClass;
2123 using BufferDescriptor = cvdescriptorset::BufferDescriptor;
2124 using ImageDescriptor = cvdescriptorset::ImageDescriptor;
locke-lunarg61870c22020-06-09 14:51:50 -06002125 using TexelDescriptor = cvdescriptorset::TexelDescriptor;
2126
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002127 for (const auto &stage_state : pipe->stage_state) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002128 const auto raster_state = pipe->RasterizationState();
2129 if (stage_state.stage_flag == VK_SHADER_STAGE_FRAGMENT_BIT && raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarge9f1cdf2020-06-12 12:28:57 -06002130 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002131 }
locke-lunarg61870c22020-06-09 14:51:50 -06002132 for (const auto &set_binding : stage_state.descriptor_uses) {
Jeremy Gebben4d51c552022-01-06 21:27:15 -07002133 const auto *descriptor_set = (*per_sets)[set_binding.first.set].bound_descriptor_set.get();
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002134 auto binding = descriptor_set->GetBinding(set_binding.first.binding);
2135 const auto descriptor_type = binding->type;
locke-lunarg61870c22020-06-09 14:51:50 -06002136 SyncStageAccessIndex sync_index =
2137 GetSyncStageAccessIndexsByDescriptorSet(descriptor_type, set_binding.second, stage_state.stage_flag);
2138
Jeremy Gebben1b9fdb82022-06-15 15:31:32 -06002139 for (uint32_t i = 0; i < binding->count; i++) {
2140 const auto *descriptor = binding->GetDescriptor(i);
locke-lunarg61870c22020-06-09 14:51:50 -06002141 switch (descriptor->GetClass()) {
2142 case DescriptorClass::ImageSampler:
2143 case DescriptorClass::Image: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002144 // NOTE: ImageSamplerDescriptor inherits from ImageDescriptor, so this cast works for both types.
2145 const auto *image_descriptor = static_cast<const ImageDescriptor *>(descriptor);
2146 if (image_descriptor->Invalid()) {
2147 continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002148 }
Jeremy Gebbena08da232022-02-01 15:14:52 -07002149 const auto *img_view_state = image_descriptor->GetImageViewState();
Jeremy Gebben11a68a32021-07-29 11:59:22 -06002150 // NOTE: 2D ImageViews of VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT Images are not allowed in
2151 // Descriptors, so we do not have to worry about depth slicing here.
2152 // See: VUID 00343
2153 assert(!img_view_state->IsDepthSliced());
locke-lunarg61870c22020-06-09 14:51:50 -06002154 const IMAGE_STATE *img_state = img_view_state->image_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002155 if (sync_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ) {
John Zulauf110413c2021-03-20 05:38:38 -06002156 const VkExtent3D extent = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.extent);
2157 const VkOffset3D offset = CastTo3D(cb_state_->activeRenderPassBeginInfo.renderArea.offset);
2158 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kRaster,
2159 img_view_state->normalized_subresource_range, offset, extent, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002160 } else {
John Zulauf110413c2021-03-20 05:38:38 -06002161 current_context_->UpdateAccessState(*img_state, sync_index, SyncOrdering::kNonAttachment,
2162 img_view_state->normalized_subresource_range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002163 }
locke-lunarg61870c22020-06-09 14:51:50 -06002164 break;
2165 }
2166 case DescriptorClass::TexelBuffer: {
Jeremy Gebbena08da232022-02-01 15:14:52 -07002167 const auto *texel_descriptor = static_cast<const TexelDescriptor *>(descriptor);
2168 if (texel_descriptor->Invalid()) {
2169 continue;
2170 }
2171 const auto *buf_view_state = texel_descriptor->GetBufferViewState();
2172 const auto *buf_state = buf_view_state->buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002173 const ResourceAccessRange range = MakeRange(*buf_view_state);
John Zulauf8e3c3e92021-01-06 11:19:36 -07002174 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002175 break;
2176 }
2177 case DescriptorClass::GeneralBuffer: {
2178 const auto *buffer_descriptor = static_cast<const BufferDescriptor *>(descriptor);
Jeremy Gebbena08da232022-02-01 15:14:52 -07002179 if (buffer_descriptor->Invalid()) {
2180 continue;
2181 }
2182 const auto *buf_state = buffer_descriptor->GetBufferState();
John Zulauf3e86bf02020-09-12 10:47:57 -06002183 const ResourceAccessRange range =
2184 MakeRange(*buf_state, buffer_descriptor->GetOffset(), buffer_descriptor->GetRange());
John Zulauf8e3c3e92021-01-06 11:19:36 -07002185 current_context_->UpdateAccessState(*buf_state, sync_index, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002186 break;
2187 }
2188 // TODO: INLINE_UNIFORM_BLOCK_EXT, ACCELERATION_STRUCTURE_KHR
2189 default:
2190 break;
2191 }
2192 }
2193 }
2194 }
2195}
2196
sjfricke0bea06e2022-06-05 09:22:26 +09002197bool CommandBufferAccessContext::ValidateDrawVertex(uint32_t vertexCount, uint32_t firstVertex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002198 bool skip = false;
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002199 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002200 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002201 return skip;
2202 }
2203
2204 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2205 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002206 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002207
2208 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002209 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002210 if (binding_description.binding < binding_buffers_size) {
2211 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002212 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002213
locke-lunarg1ae57d62020-11-18 10:49:19 -07002214 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002215 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2216 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002217 auto hazard = current_context_->DetectHazard(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002218 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002219 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002220 buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for vertex %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002221 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06002222 sync_state_->report_data->FormatHandle(buf_state->buffer()).c_str(),
2223 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002224 }
2225 }
2226 }
2227 return skip;
2228}
2229
John Zulauf14940722021-04-12 15:19:02 -06002230void CommandBufferAccessContext::RecordDrawVertex(uint32_t vertexCount, uint32_t firstVertex, const ResourceUsageTag tag) {
Jeremy Gebben159b3cc2021-06-03 09:09:03 -06002231 const auto *pipe = cb_state_->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002232 if (!pipe) {
locke-lunarg61870c22020-06-09 14:51:50 -06002233 return;
2234 }
2235 const auto &binding_buffers = cb_state_->current_vertex_buffer_binding_info.vertex_buffer_bindings;
2236 const auto &binding_buffers_size = binding_buffers.size();
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002237 const auto &binding_descriptions_size = pipe->vertex_input_state->binding_descriptions.size();
locke-lunarg61870c22020-06-09 14:51:50 -06002238
2239 for (size_t i = 0; i < binding_descriptions_size; ++i) {
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002240 const auto &binding_description = pipe->vertex_input_state->binding_descriptions[i];
locke-lunarg61870c22020-06-09 14:51:50 -06002241 if (binding_description.binding < binding_buffers_size) {
2242 const auto &binding_buffer = binding_buffers[binding_description.binding];
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002243 if (binding_buffer.buffer_state == nullptr || binding_buffer.buffer_state->Destroyed()) continue;
locke-lunarg61870c22020-06-09 14:51:50 -06002244
locke-lunarg1ae57d62020-11-18 10:49:19 -07002245 auto *buf_state = binding_buffer.buffer_state.get();
John Zulauf3e86bf02020-09-12 10:47:57 -06002246 const ResourceAccessRange range = GetBufferRange(binding_buffer.offset, buf_state->createInfo.size, firstVertex,
2247 vertexCount, binding_description.stride);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002248 current_context_->UpdateAccessState(*buf_state, SYNC_VERTEX_ATTRIBUTE_INPUT_VERTEX_ATTRIBUTE_READ,
2249 SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002250 }
2251 }
2252}
2253
sjfricke0bea06e2022-06-05 09:22:26 +09002254bool CommandBufferAccessContext::ValidateDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002255 bool skip = false;
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002256 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) {
locke-lunarg1ae57d62020-11-18 10:49:19 -07002257 return skip;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002258 }
locke-lunarg61870c22020-06-09 14:51:50 -06002259
locke-lunarg1ae57d62020-11-18 10:49:19 -07002260 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002261 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002262 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2263 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002264 auto hazard = current_context_->DetectHazard(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, range);
locke-lunarg61870c22020-06-09 14:51:50 -06002265 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002266 skip |= sync_state_->LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002267 index_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard), "%s: Hazard %s for index %s in %s. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002268 CommandTypeString(cmd_type), string_SyncHazard(hazard.hazard),
2269 sync_state_->report_data->FormatHandle(index_buf_state->buffer()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002270 sync_state_->report_data->FormatHandle(cb_state_->commandBuffer()).c_str(), FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002271 }
2272
2273 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2274 // We will detect more accurate range in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09002275 skip |= ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunarg61870c22020-06-09 14:51:50 -06002276 return skip;
2277}
2278
John Zulauf14940722021-04-12 15:19:02 -06002279void CommandBufferAccessContext::RecordDrawVertexIndex(uint32_t indexCount, uint32_t firstIndex, const ResourceUsageTag tag) {
Jeremy Gebben9efe1cf2021-05-15 20:05:09 -06002280 if (cb_state_->index_buffer_binding.buffer_state == nullptr || cb_state_->index_buffer_binding.buffer_state->Destroyed()) return;
locke-lunarg61870c22020-06-09 14:51:50 -06002281
locke-lunarg1ae57d62020-11-18 10:49:19 -07002282 auto *index_buf_state = cb_state_->index_buffer_binding.buffer_state.get();
locke-lunarg61870c22020-06-09 14:51:50 -06002283 const auto index_size = GetIndexAlignment(cb_state_->index_buffer_binding.index_type);
John Zulauf3e86bf02020-09-12 10:47:57 -06002284 const ResourceAccessRange range = GetBufferRange(cb_state_->index_buffer_binding.offset, index_buf_state->createInfo.size,
2285 firstIndex, indexCount, index_size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07002286 current_context_->UpdateAccessState(*index_buf_state, SYNC_INDEX_INPUT_INDEX_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002287
2288 // TODO: For now, we detect the whole vertex buffer. Index buffer could be changed until SubmitQueue.
2289 // We will detect more accurate range in the future.
2290 RecordDrawVertex(UINT32_MAX, 0, tag);
2291}
2292
sjfricke0bea06e2022-06-05 09:22:26 +09002293bool CommandBufferAccessContext::ValidateDrawSubpassAttachment(CMD_TYPE cmd_type) const {
locke-lunarg7077d502020-06-18 21:37:26 -06002294 bool skip = false;
2295 if (!current_renderpass_context_) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09002296 skip |= current_renderpass_context_->ValidateDrawSubpassAttachment(GetExecutionContext(), *cb_state_.get(), cmd_type);
locke-lunarg7077d502020-06-18 21:37:26 -06002297 return skip;
locke-lunarg61870c22020-06-09 14:51:50 -06002298}
2299
John Zulauf14940722021-04-12 15:19:02 -06002300void CommandBufferAccessContext::RecordDrawSubpassAttachment(const ResourceUsageTag tag) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002301 if (current_renderpass_context_) {
John Zulauf64ffe552021-02-06 10:25:07 -07002302 current_renderpass_context_->RecordDrawSubpassAttachment(*cb_state_.get(), tag);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002303 }
locke-lunarg61870c22020-06-09 14:51:50 -06002304}
2305
John Zulauf00119522022-05-23 19:07:42 -06002306QueueId CommandBufferAccessContext::GetQueueId() const { return QueueSyncState::kQueueIdInvalid; }
2307
sjfricke0bea06e2022-06-05 09:22:26 +09002308ResourceUsageTag CommandBufferAccessContext::RecordBeginRenderPass(CMD_TYPE cmd_type, const RENDER_PASS_STATE &rp_state,
John Zulauf41a9c7c2021-12-07 15:59:53 -07002309 const VkRect2D &render_area,
2310 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
John Zulauf355e49b2020-04-24 15:11:15 -06002311 // Create an access context the current renderpass.
sjfricke0bea06e2022-06-05 09:22:26 +09002312 const auto barrier_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2313 const auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf64ffe552021-02-06 10:25:07 -07002314 render_pass_contexts_.emplace_back(rp_state, render_area, GetQueueFlags(), attachment_views, &cb_access_context_);
John Zulauf16adfc92020-04-08 10:28:33 -06002315 current_renderpass_context_ = &render_pass_contexts_.back();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002316 current_renderpass_context_->RecordBeginRenderPass(barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002317 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002318 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002319}
2320
sjfricke0bea06e2022-06-05 09:22:26 +09002321ResourceUsageTag CommandBufferAccessContext::RecordNextSubpass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002322 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002323 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002324
sjfricke0bea06e2022-06-05 09:22:26 +09002325 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2326 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
2327 auto load_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kLoadOp);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002328
2329 current_renderpass_context_->RecordNextSubpass(store_tag, barrier_tag, load_tag);
John Zulauf16adfc92020-04-08 10:28:33 -06002330 current_context_ = &current_renderpass_context_->CurrentContext();
John Zulauf41a9c7c2021-12-07 15:59:53 -07002331 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002332}
2333
sjfricke0bea06e2022-06-05 09:22:26 +09002334ResourceUsageTag CommandBufferAccessContext::RecordEndRenderPass(const CMD_TYPE cmd_type) {
John Zulauf16adfc92020-04-08 10:28:33 -06002335 assert(current_renderpass_context_);
sjfricke0bea06e2022-06-05 09:22:26 +09002336 if (!current_renderpass_context_) return NextCommandTag(cmd_type);
John Zulauf16adfc92020-04-08 10:28:33 -06002337
sjfricke0bea06e2022-06-05 09:22:26 +09002338 auto store_tag = NextCommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kStoreOp);
2339 auto barrier_tag = NextSubcommandTag(cmd_type, ResourceUsageRecord::SubcommandType::kSubpassTransition);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002340
2341 current_renderpass_context_->RecordEndRenderPass(&cb_access_context_, store_tag, barrier_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002342 current_context_ = &cb_access_context_;
John Zulauf16adfc92020-04-08 10:28:33 -06002343 current_renderpass_context_ = nullptr;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002344 return barrier_tag;
John Zulauf16adfc92020-04-08 10:28:33 -06002345}
2346
John Zulauf4a6105a2020-11-17 15:11:05 -07002347void CommandBufferAccessContext::RecordDestroyEvent(VkEvent event) {
2348 // Erase is okay with the key not being
Jeremy Gebbenf4449392022-01-28 10:09:10 -07002349 auto event_state = sync_state_->Get<EVENT_STATE>(event);
John Zulauf669dfd52021-01-27 17:15:28 -07002350 if (event_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06002351 GetCurrentEventsContext()->Destroy(event_state.get());
John Zulaufd5115702021-01-18 12:34:33 -07002352 }
2353}
2354
John Zulaufae842002021-04-15 18:20:55 -06002355// The is the recorded cb context
John Zulauf0223f142022-07-06 09:05:39 -06002356bool CommandBufferAccessContext::ValidateFirstUse(CommandExecutionContext &exec_context, const char *func_name,
John Zulauf4fa68462021-04-26 21:04:22 -06002357 uint32_t index) const {
John Zulauf0223f142022-07-06 09:05:39 -06002358 if (!exec_context.ValidForSyncOps()) return false;
2359
2360 const QueueId queue_id = exec_context.GetQueueId();
2361 const ResourceUsageTag base_tag = exec_context.GetTagLimit();
John Zulaufae842002021-04-15 18:20:55 -06002362 bool skip = false;
2363 ResourceUsageRange tag_range = {0, 0};
2364 const AccessContext *recorded_context = GetCurrentAccessContext();
2365 assert(recorded_context);
2366 HazardResult hazard;
John Zulaufbb890452021-12-14 11:30:18 -07002367 auto log_msg = [this](const HazardResult &hazard, const CommandExecutionContext &exec_context, const char *func_name,
John Zulaufae842002021-04-15 18:20:55 -06002368 uint32_t index) {
John Zulaufbb890452021-12-14 11:30:18 -07002369 const auto handle = exec_context.Handle();
John Zulaufae842002021-04-15 18:20:55 -06002370 const auto recorded_handle = cb_state_->commandBuffer();
John Zulauf4fa68462021-04-26 21:04:22 -06002371 const auto *report_data = sync_state_->report_data;
John Zulaufbb890452021-12-14 11:30:18 -07002372 return sync_state_->LogError(handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf4fa68462021-04-26 21:04:22 -06002373 "%s: Hazard %s for entry %" PRIu32 ", %s, Recorded access info %s. Access info %s.", func_name,
2374 string_SyncHazard(hazard.hazard), index, report_data->FormatHandle(recorded_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06002375 FormatUsage(*hazard.recorded_access).c_str(), exec_context.FormatHazard(hazard).c_str());
John Zulaufae842002021-04-15 18:20:55 -06002376 };
2377 for (const auto &sync_op : sync_ops_) {
John Zulauf4fa68462021-04-26 21:04:22 -06002378 // we update the range to any include layout transition first use writes,
2379 // as they are stored along with the source scope (as effective barrier) when recorded
2380 tag_range.end = sync_op.tag + 1;
John Zulauf0223f142022-07-06 09:05:39 -06002381 skip |= sync_op.sync_op->ReplayValidate(sync_op.tag, *this, base_tag, exec_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002382
John Zulauf0223f142022-07-06 09:05:39 -06002383 // We're allowing for the ReplayRecord to modify the exec_context (e.g. for Renderpass operations), so
2384 // we need to fetch the current access context each time
2385 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *exec_context.GetCurrentAccessContext());
John Zulaufae842002021-04-15 18:20:55 -06002386 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002387 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002388 }
2389 // NOTE: Add call to replay validate here when we add support for syncop with non-trivial replay
John Zulauf4fa68462021-04-26 21:04:22 -06002390 // Record the barrier into the proxy context.
John Zulauf0223f142022-07-06 09:05:39 -06002391 sync_op.sync_op->ReplayRecord(exec_context, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002392 tag_range.begin = tag_range.end;
John Zulaufae842002021-04-15 18:20:55 -06002393 }
2394
2395 // and anything after the last syncop
John Zulaufae842002021-04-15 18:20:55 -06002396 tag_range.end = ResourceUsageRecord::kMaxIndex;
John Zulauf0223f142022-07-06 09:05:39 -06002397 hazard = recorded_context->DetectFirstUseHazard(queue_id, tag_range, *exec_context.GetCurrentAccessContext());
John Zulaufae842002021-04-15 18:20:55 -06002398 if (hazard.hazard) {
John Zulauf0223f142022-07-06 09:05:39 -06002399 skip |= log_msg(hazard, exec_context, func_name, index);
John Zulaufae842002021-04-15 18:20:55 -06002400 }
2401
2402 return skip;
2403}
2404
sjfricke0bea06e2022-06-05 09:22:26 +09002405void CommandBufferAccessContext::RecordExecutedCommandBuffer(const CommandBufferAccessContext &recorded_cb_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002406 const AccessContext *recorded_context = recorded_cb_context.GetCurrentAccessContext();
2407 assert(recorded_context);
2408
2409 // Just run through the barriers ignoring the usage from the recorded context, as Resolve will overwrite outdated state
2410 const ResourceUsageTag base_tag = GetTagLimit();
John Zulauf06f6f1e2022-04-19 15:28:11 -06002411 for (const auto &sync_op : recorded_cb_context.GetSyncOps()) {
John Zulauf4fa68462021-04-26 21:04:22 -06002412 // we update the range to any include layout transition first use writes,
2413 // as they are stored along with the source scope (as effective barrier) when recorded
John Zulauf0223f142022-07-06 09:05:39 -06002414 sync_op.sync_op->ReplayRecord(*this, base_tag + sync_op.tag);
John Zulauf4fa68462021-04-26 21:04:22 -06002415 }
2416
2417 ResourceUsageRange tag_range = ImportRecordedAccessLog(recorded_cb_context);
2418 assert(base_tag == tag_range.begin); // to ensure the to offset calculation agree
John Zulauf1d5f9c12022-05-13 14:51:08 -06002419 ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulauf4fa68462021-04-26 21:04:22 -06002420}
2421
John Zulauf1d5f9c12022-05-13 14:51:08 -06002422void CommandBufferAccessContext::ResolveExecutedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulauf4fa68462021-04-26 21:04:22 -06002423 auto tag_offset = [offset](ResourceAccessState *access) { access->OffsetTag(offset); };
John Zulauf1d5f9c12022-05-13 14:51:08 -06002424 GetCurrentAccessContext()->ResolveFromContext(tag_offset, recorded_context);
John Zulauf4fa68462021-04-26 21:04:22 -06002425}
2426
John Zulauf3c788ef2022-02-22 12:12:30 -07002427ResourceUsageRange CommandExecutionContext::ImportRecordedAccessLog(const CommandBufferAccessContext &recorded_context) {
John Zulauf4fa68462021-04-26 21:04:22 -06002428 // The execution references ensure lifespan for the referenced child CB's...
2429 ResourceUsageRange tag_range(GetTagLimit(), 0);
John Zulauf3c788ef2022-02-22 12:12:30 -07002430 InsertRecordedAccessLogEntries(recorded_context);
2431 tag_range.end = GetTagLimit();
John Zulauf4fa68462021-04-26 21:04:22 -06002432 return tag_range;
2433}
2434
John Zulauf3c788ef2022-02-22 12:12:30 -07002435void CommandBufferAccessContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &recorded_context) {
2436 cbs_referenced_.emplace(recorded_context.GetCBStateShared());
2437 access_log_.insert(access_log_.end(), recorded_context.access_log_.cbegin(), recorded_context.access_log_.end());
2438}
2439
John Zulauf41a9c7c2021-12-07 15:59:53 -07002440ResourceUsageTag CommandBufferAccessContext::NextSubcommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2441 ResourceUsageTag next = access_log_.size();
2442 access_log_.emplace_back(command, command_number_, subcommand, ++subcommand_number_, cb_state_.get(), reset_count_);
2443 return next;
2444}
2445
2446ResourceUsageTag CommandBufferAccessContext::NextCommandTag(CMD_TYPE command, ResourceUsageRecord::SubcommandType subcommand) {
2447 command_number_++;
2448 subcommand_number_ = 0;
2449 ResourceUsageTag next = access_log_.size();
2450 access_log_.emplace_back(command, command_number_, subcommand, subcommand_number_, cb_state_.get(), reset_count_);
2451 return next;
2452}
2453
2454ResourceUsageTag CommandBufferAccessContext::NextIndexedCommandTag(CMD_TYPE command, uint32_t index) {
2455 if (index == 0) {
2456 return NextCommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2457 }
2458 return NextSubcommandTag(command, ResourceUsageRecord::SubcommandType::kIndex);
2459}
2460
John Zulaufbb890452021-12-14 11:30:18 -07002461void CommandBufferAccessContext::RecordSyncOp(SyncOpPointer &&sync_op) {
2462 auto tag = sync_op->Record(this);
2463 // As renderpass operations can have side effects on the command buffer access context,
2464 // update the sync operation to record these if any.
John Zulaufbb890452021-12-14 11:30:18 -07002465 sync_ops_.emplace_back(tag, std::move(sync_op));
2466}
2467
John Zulaufae842002021-04-15 18:20:55 -06002468class HazardDetectFirstUse {
2469 public:
John Zulauf0223f142022-07-06 09:05:39 -06002470 HazardDetectFirstUse(const ResourceAccessState &recorded_use, QueueId queue_id, const ResourceUsageRange &tag_range)
2471 : recorded_use_(recorded_use), queue_id_(queue_id), tag_range_(tag_range) {}
John Zulaufae842002021-04-15 18:20:55 -06002472 HazardResult Detect(const ResourceAccessRangeMap::const_iterator &pos) const {
John Zulaufec943ec2022-06-29 07:52:56 -06002473 return pos->second.DetectHazard(recorded_use_, queue_id_, tag_range_);
John Zulaufae842002021-04-15 18:20:55 -06002474 }
2475 HazardResult DetectAsync(const ResourceAccessRangeMap::const_iterator &pos, ResourceUsageTag start_tag) const {
2476 return pos->second.DetectAsyncHazard(recorded_use_, tag_range_, start_tag);
2477 }
2478
2479 private:
2480 const ResourceAccessState &recorded_use_;
John Zulaufec943ec2022-06-29 07:52:56 -06002481 const QueueId queue_id_;
John Zulaufae842002021-04-15 18:20:55 -06002482 const ResourceUsageRange &tag_range_;
2483};
2484
2485// This is called with the *recorded* command buffers access context, with the *active* access context pass in, againsts which
2486// hazards will be detected
John Zulaufec943ec2022-06-29 07:52:56 -06002487HazardResult AccessContext::DetectFirstUseHazard(QueueId queue_id, const ResourceUsageRange &tag_range,
John Zulauf0223f142022-07-06 09:05:39 -06002488 const AccessContext &access_context) const {
John Zulaufae842002021-04-15 18:20:55 -06002489 HazardResult hazard;
2490 for (const auto address_type : kAddressTypes) {
2491 const auto &recorded_access_map = GetAccessStateMap(address_type);
2492 for (const auto &recorded_access : recorded_access_map) {
2493 // Cull any entries not in the current tag range
2494 if (!recorded_access.second.FirstAccessInTagRange(tag_range)) continue;
John Zulauf0223f142022-07-06 09:05:39 -06002495 HazardDetectFirstUse detector(recorded_access.second, queue_id, tag_range);
John Zulaufae842002021-04-15 18:20:55 -06002496 hazard = access_context.DetectHazard(address_type, detector, recorded_access.first, DetectOptions::kDetectAll);
2497 if (hazard.hazard) break;
2498 }
2499 }
2500
2501 return hazard;
2502}
2503
John Zulaufbb890452021-12-14 11:30:18 -07002504bool RenderPassAccessContext::ValidateDrawSubpassAttachment(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002505 const CMD_BUFFER_STATE &cmd_buffer, CMD_TYPE cmd_type) const {
locke-lunarg61870c22020-06-09 14:51:50 -06002506 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07002507 const auto &sync_state = exec_context.GetSyncState();
sjfricke0bea06e2022-06-05 09:22:26 +09002508 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002509 if (!pipe) {
2510 return skip;
2511 }
2512
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002513 const auto raster_state = pipe->RasterizationState();
2514 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002515 return skip;
2516 }
sjfricke0bea06e2022-06-05 09:22:26 +09002517 const char *caller_name = CommandTypeString(cmd_type);
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002518 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002519 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg37047832020-06-12 13:44:45 -06002520
John Zulauf1a224292020-06-30 14:52:13 -06002521 const auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002522 // Subpass's inputAttachment has been done in ValidateDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002523 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2524 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002525 if (location >= subpass.colorAttachmentCount ||
2526 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002527 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002528 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002529 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2530 if (!view_gen.IsValid()) continue;
2531 HazardResult hazard =
2532 current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kRenderArea,
2533 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment);
locke-lunarg96dc9632020-06-10 17:22:18 -06002534 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002535 const VkImageView view_handle = view_gen.GetViewState()->image_view();
John Zulaufd0ec59f2021-03-13 14:25:08 -07002536 skip |= sync_state.LogError(view_handle, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002537 "%s: Hazard %s for %s in %s, Subpass #%d, and pColorAttachments #%d. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002538 caller_name, string_SyncHazard(hazard.hazard),
John Zulaufd0ec59f2021-03-13 14:25:08 -07002539 sync_state.report_data->FormatHandle(view_handle).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002540 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(),
2541 cmd_buffer.activeSubpass, location, exec_context.FormatHazard(hazard).c_str());
locke-lunarg61870c22020-06-09 14:51:50 -06002542 }
2543 }
2544 }
locke-lunarg37047832020-06-12 13:44:45 -06002545
2546 // PHASE1 TODO: Add layout based read/vs. write selection.
2547 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002548 const auto ds_state = pipe->DepthStencilState();
2549 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002550
2551 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2552 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2553 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002554 bool depth_write = false, stencil_write = false;
2555
2556 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002557 if (!FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable && ds_state->depthWriteEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002558 IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
2559 depth_write = true;
2560 }
2561 // PHASE1 TODO: It needs to check if stencil is writable.
2562 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2563 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2564 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002565 if (!FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002566 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2567 stencil_write = true;
2568 }
2569
2570 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2571 if (depth_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002572 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea,
2573 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2574 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002575 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002576 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002577 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002578 "%s: Hazard %s for %s in %s, Subpass #%d, and depth part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002579 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002580 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002581 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002582 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002583 }
2584 }
2585 if (stencil_write) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002586 HazardResult hazard = current_context.DetectHazard(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea,
2587 SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2588 SyncOrdering::kDepthStencilAttachment);
locke-lunarg37047832020-06-12 13:44:45 -06002589 if (hazard.hazard) {
locke-lunarg88dbb542020-06-23 22:05:42 -06002590 skip |= sync_state.LogError(
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002591 view_state.image_view(), string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06002592 "%s: Hazard %s for %s in %s, Subpass #%d, and stencil part of pDepthStencilAttachment. Access info %s.",
sjfricke0bea06e2022-06-05 09:22:26 +09002593 caller_name, string_SyncHazard(hazard.hazard),
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06002594 sync_state.report_data->FormatHandle(view_state.image_view()).c_str(),
sjfricke0bea06e2022-06-05 09:22:26 +09002595 sync_state.report_data->FormatHandle(cmd_buffer.commandBuffer()).c_str(), cmd_buffer.activeSubpass,
John Zulauf397e68b2022-04-19 11:44:07 -06002596 exec_context.FormatHazard(hazard).c_str());
locke-lunarg37047832020-06-12 13:44:45 -06002597 }
locke-lunarg61870c22020-06-09 14:51:50 -06002598 }
2599 }
2600 return skip;
2601}
2602
sjfricke0bea06e2022-06-05 09:22:26 +09002603void RenderPassAccessContext::RecordDrawSubpassAttachment(const CMD_BUFFER_STATE &cmd_buffer, const ResourceUsageTag tag) {
2604 const auto *pipe = cmd_buffer.GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS);
Jeremy Gebben11af9792021-08-20 10:20:09 -06002605 if (!pipe) {
2606 return;
2607 }
2608
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002609 const auto *raster_state = pipe->RasterizationState();
2610 if (raster_state && raster_state->rasterizerDiscardEnable) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002611 return;
2612 }
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002613 const auto &list = pipe->fragmentShader_writable_output_location_list;
locke-lunarg61870c22020-06-09 14:51:50 -06002614 const auto &subpass = rp_state_->createInfo.pSubpasses[current_subpass_];
locke-lunarg61870c22020-06-09 14:51:50 -06002615
John Zulauf1a224292020-06-30 14:52:13 -06002616 auto &current_context = CurrentContext();
locke-lunarg44f9bb12020-06-10 14:43:57 -06002617 // Subpass's inputAttachment has been done in RecordDispatchDrawDescriptorSet
locke-lunarg96dc9632020-06-10 17:22:18 -06002618 if (subpass.pColorAttachments && subpass.colorAttachmentCount && !list.empty()) {
2619 for (const auto location : list) {
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002620 if (location >= subpass.colorAttachmentCount ||
2621 subpass.pColorAttachments[location].attachment == VK_ATTACHMENT_UNUSED) {
locke-lunarg96dc9632020-06-10 17:22:18 -06002622 continue;
Nathaniel Cesarioce9b4812020-12-17 08:55:28 -07002623 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002624 const AttachmentViewGen &view_gen = attachment_views_[subpass.pColorAttachments[location].attachment];
2625 current_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea,
2626 SYNC_COLOR_ATTACHMENT_OUTPUT_COLOR_ATTACHMENT_WRITE, SyncOrdering::kColorAttachment,
2627 tag);
locke-lunarg61870c22020-06-09 14:51:50 -06002628 }
2629 }
locke-lunarg37047832020-06-12 13:44:45 -06002630
2631 // PHASE1 TODO: Add layout based read/vs. write selection.
2632 // PHASE1 TODO: Read operations for both depth and stencil are possible in the future.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002633 const auto *ds_state = pipe->DepthStencilState();
2634 const uint32_t depth_stencil_attachment = GetSubpassDepthStencilAttachmentIndex(ds_state, subpass.pDepthStencilAttachment);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002635 if ((depth_stencil_attachment != VK_ATTACHMENT_UNUSED) && attachment_views_[depth_stencil_attachment].IsValid()) {
2636 const AttachmentViewGen &view_gen = attachment_views_[depth_stencil_attachment];
2637 const IMAGE_VIEW_STATE &view_state = *view_gen.GetViewState();
locke-lunarg37047832020-06-12 13:44:45 -06002638 bool depth_write = false, stencil_write = false;
John Zulaufd0ec59f2021-03-13 14:25:08 -07002639 const bool has_depth = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_DEPTH_BIT);
2640 const bool has_stencil = 0 != (view_state.normalized_subresource_range.aspectMask & VK_IMAGE_ASPECT_STENCIL_BIT);
locke-lunarg37047832020-06-12 13:44:45 -06002641
2642 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002643 if (has_depth && !FormatIsStencilOnly(view_state.create_info.format) && ds_state->depthTestEnable &&
2644 ds_state->depthWriteEnable && IsImageLayoutDepthWritable(subpass.pDepthStencilAttachment->layout)) {
locke-lunarg37047832020-06-12 13:44:45 -06002645 depth_write = true;
2646 }
2647 // PHASE1 TODO: It needs to check if stencil is writable.
2648 // If failOp, passOp, or depthFailOp are not KEEP, and writeMask isn't 0, it's writable.
2649 // If depth test is disable, it's considered depth test passes, and then depthFailOp doesn't run.
2650 // PHASE1 TODO: These validation should be in core_checks.
Nathaniel Cesario3fd4f762022-02-16 16:07:06 -07002651 if (has_stencil && !FormatIsDepthOnly(view_state.create_info.format) && ds_state->stencilTestEnable &&
locke-lunarg37047832020-06-12 13:44:45 -06002652 IsImageLayoutStencilWritable(subpass.pDepthStencilAttachment->layout)) {
2653 stencil_write = true;
2654 }
2655
John Zulaufd0ec59f2021-03-13 14:25:08 -07002656 if (depth_write || stencil_write) {
2657 const auto ds_gentype = view_gen.GetDepthStencilRenderAreaGenType(depth_write, stencil_write);
2658 // PHASE1 TODO: Add EARLY stage detection based on ExecutionMode.
2659 current_context.UpdateAccessState(view_gen, ds_gentype, SYNC_LATE_FRAGMENT_TESTS_DEPTH_STENCIL_ATTACHMENT_WRITE,
2660 SyncOrdering::kDepthStencilAttachment, tag);
locke-lunarg37047832020-06-12 13:44:45 -06002661 }
locke-lunarg61870c22020-06-09 14:51:50 -06002662 }
2663}
2664
sjfricke0bea06e2022-06-05 09:22:26 +09002665bool RenderPassAccessContext::ValidateNextSubpass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002666 // PHASE1 TODO: Add Validate Preserve attachments
John Zulauf355e49b2020-04-24 15:11:15 -06002667 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002668 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulaufb027cdb2020-05-21 14:25:22 -06002669 current_subpass_);
John Zulaufbb890452021-12-14 11:30:18 -07002670 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
sjfricke0bea06e2022-06-05 09:22:26 +09002671 cmd_type);
John Zulaufaff20662020-06-01 14:07:58 -06002672
John Zulauf355e49b2020-04-24 15:11:15 -06002673 const auto next_subpass = current_subpass_ + 1;
ziga-lunarg31a3e772022-03-22 11:48:46 +01002674 if (next_subpass >= subpass_contexts_.size()) {
2675 return skip;
2676 }
John Zulauf1507ee42020-05-18 11:33:09 -06002677 const auto &next_context = subpass_contexts_[next_subpass];
John Zulauf64ffe552021-02-06 10:25:07 -07002678 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002679 next_context.ValidateLayoutTransitions(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002680 if (!skip) {
2681 // To avoid complex (and buggy) duplication of the affect of layout transitions on load operations, we'll record them
2682 // on a copy of the (empty) next context.
2683 // Note: The resource access map should be empty so hopefully this copy isn't too horrible from a perf POV.
2684 AccessContext temp_context(next_context);
John Zulaufee984022022-04-13 16:39:50 -06002685 temp_context.RecordLayoutTransitions(*rp_state_, next_subpass, attachment_views_, kInvalidTag);
John Zulauf64ffe552021-02-06 10:25:07 -07002686 skip |=
sjfricke0bea06e2022-06-05 09:22:26 +09002687 temp_context.ValidateLoadOperation(exec_context, *rp_state_, render_area_, next_subpass, attachment_views_, cmd_type);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002688 }
John Zulauf7635de32020-05-29 17:14:15 -06002689 return skip;
2690}
sjfricke0bea06e2022-06-05 09:22:26 +09002691bool RenderPassAccessContext::ValidateEndRenderPass(const CommandExecutionContext &exec_context, CMD_TYPE cmd_type) const {
John Zulaufaff20662020-06-01 14:07:58 -06002692 // PHASE1 TODO: Validate Preserve
John Zulauf7635de32020-05-29 17:14:15 -06002693 bool skip = false;
sjfricke0bea06e2022-06-05 09:22:26 +09002694 skip |= CurrentContext().ValidateResolveOperations(exec_context, *rp_state_, render_area_, attachment_views_, cmd_type,
John Zulauf7635de32020-05-29 17:14:15 -06002695 current_subpass_);
sjfricke0bea06e2022-06-05 09:22:26 +09002696 skip |= CurrentContext().ValidateStoreOperation(exec_context, *rp_state_, render_area_, current_subpass_, attachment_views_,
2697 cmd_type);
2698 skip |= ValidateFinalSubpassLayoutTransitions(exec_context, cmd_type);
John Zulauf355e49b2020-04-24 15:11:15 -06002699 return skip;
2700}
2701
John Zulauf64ffe552021-02-06 10:25:07 -07002702AccessContext *RenderPassAccessContext::CreateStoreResolveProxy() const {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002703 return CreateStoreResolveProxyContext(CurrentContext(), *rp_state_, current_subpass_, attachment_views_);
John Zulauf7635de32020-05-29 17:14:15 -06002704}
2705
John Zulaufbb890452021-12-14 11:30:18 -07002706bool RenderPassAccessContext::ValidateFinalSubpassLayoutTransitions(const CommandExecutionContext &exec_context,
sjfricke0bea06e2022-06-05 09:22:26 +09002707 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06002708 bool skip = false;
2709
John Zulauf7635de32020-05-29 17:14:15 -06002710 // As validation methods are const and precede the record/update phase, for any tranistions from the current (last)
2711 // subpass, we have to validate them against a copy of the current AccessContext, with resolve operations applied.
2712 // Note: we could be more efficient by tracking whether or not we actually *have* any changes (e.g. attachment resolve)
2713 // to apply and only copy then, if this proves a hot spot.
2714 std::unique_ptr<AccessContext> proxy_for_current;
2715
John Zulauf355e49b2020-04-24 15:11:15 -06002716 // Validate the "finalLayout" transitions to external
2717 // Get them from where there we're hidding in the extra entry.
2718 const auto &final_transitions = rp_state_->subpass_transitions.back();
2719 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002720 const auto &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002721 const auto &trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002722 assert(trackback.source_subpass); // Transitions are given implicit transitions if the StateTracker is working correctly
2723 auto *context = trackback.source_subpass;
John Zulauf7635de32020-05-29 17:14:15 -06002724
2725 if (transition.prev_pass == current_subpass_) {
2726 if (!proxy_for_current) {
2727 // We haven't recorded resolve ofor the current_subpass, so we need to copy current and update it *as if*
John Zulauf64ffe552021-02-06 10:25:07 -07002728 proxy_for_current.reset(CreateStoreResolveProxy());
John Zulauf7635de32020-05-29 17:14:15 -06002729 }
2730 context = proxy_for_current.get();
2731 }
2732
John Zulaufa0a98292020-09-18 09:30:10 -06002733 // Use the merged barrier for the hazard check (safe since it just considers the src (first) scope.
2734 const auto merged_barrier = MergeBarriers(trackback.barriers);
John Zulaufd0ec59f2021-03-13 14:25:08 -07002735 auto hazard = context->DetectImageBarrierHazard(view_gen, merged_barrier, AccessContext::DetectOptions::kDetectPrevious);
John Zulauf355e49b2020-04-24 15:11:15 -06002736 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09002737 const char *func_name = CommandTypeString(cmd_type);
John Zulaufee984022022-04-13 16:39:50 -06002738 if (hazard.tag == kInvalidTag) {
2739 // Hazard vs. ILT
John Zulaufbb890452021-12-14 11:30:18 -07002740 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002741 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2742 "%s: Hazard %s vs. store/resolve operations in subpass %" PRIu32 " for attachment %" PRIu32
2743 " final image layout transition (old_layout: %s, new_layout: %s).",
2744 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2745 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout));
2746 } else {
John Zulaufbb890452021-12-14 11:30:18 -07002747 skip |= exec_context.GetSyncState().LogError(
John Zulaufee984022022-04-13 16:39:50 -06002748 rp_state_->renderPass(), string_SyncHazardVUID(hazard.hazard),
2749 "%s: Hazard %s with last use subpass %" PRIu32 " for attachment %" PRIu32
2750 " final image layout transition (old_layout: %s, new_layout: %s). Access info %s.",
2751 func_name, string_SyncHazard(hazard.hazard), transition.prev_pass, transition.attachment,
2752 string_VkImageLayout(transition.old_layout), string_VkImageLayout(transition.new_layout),
John Zulauf397e68b2022-04-19 11:44:07 -06002753 exec_context.FormatHazard(hazard).c_str());
John Zulaufee984022022-04-13 16:39:50 -06002754 }
John Zulauf355e49b2020-04-24 15:11:15 -06002755 }
2756 }
2757 return skip;
2758}
2759
John Zulauf14940722021-04-12 15:19:02 -06002760void RenderPassAccessContext::RecordLayoutTransitions(const ResourceUsageTag tag) {
John Zulauf355e49b2020-04-24 15:11:15 -06002761 // Add layout transitions...
John Zulaufb02c1eb2020-10-06 16:33:36 -06002762 subpass_contexts_[current_subpass_].RecordLayoutTransitions(*rp_state_, current_subpass_, attachment_views_, tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002763}
2764
John Zulauf14940722021-04-12 15:19:02 -06002765void RenderPassAccessContext::RecordLoadOperations(const ResourceUsageTag tag) {
John Zulauf1507ee42020-05-18 11:33:09 -06002766 const auto *attachment_ci = rp_state_->createInfo.pAttachments;
2767 auto &subpass_context = subpass_contexts_[current_subpass_];
John Zulauf1507ee42020-05-18 11:33:09 -06002768
2769 for (uint32_t i = 0; i < rp_state_->createInfo.attachmentCount; i++) {
2770 if (rp_state_->attachment_first_subpass[i] == current_subpass_) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002771 const AttachmentViewGen &view_gen = attachment_views_[i];
2772 if (!view_gen.IsValid()) continue; // UNUSED
John Zulauf1507ee42020-05-18 11:33:09 -06002773
2774 const auto &ci = attachment_ci[i];
2775 const bool has_depth = FormatHasDepth(ci.format);
John Zulaufb027cdb2020-05-21 14:25:22 -06002776 const bool has_stencil = FormatHasStencil(ci.format);
John Zulauf1507ee42020-05-18 11:33:09 -06002777 const bool is_color = !(has_depth || has_stencil);
2778
2779 if (is_color) {
John Zulauf57261402021-08-13 11:32:06 -06002780 const SyncStageAccessIndex load_op = ColorLoadUsage(ci.loadOp);
2781 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2782 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kRenderArea, load_op,
2783 SyncOrdering::kColorAttachment, tag);
2784 }
John Zulauf1507ee42020-05-18 11:33:09 -06002785 } else {
John Zulauf1507ee42020-05-18 11:33:09 -06002786 if (has_depth) {
John Zulauf57261402021-08-13 11:32:06 -06002787 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.loadOp);
2788 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2789 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kDepthOnlyRenderArea, load_op,
2790 SyncOrdering::kDepthStencilAttachment, tag);
2791 }
John Zulauf1507ee42020-05-18 11:33:09 -06002792 }
2793 if (has_stencil) {
John Zulauf57261402021-08-13 11:32:06 -06002794 const SyncStageAccessIndex load_op = DepthStencilLoadUsage(ci.stencilLoadOp);
2795 if (load_op != SYNC_ACCESS_INDEX_NONE) {
2796 subpass_context.UpdateAccessState(view_gen, AttachmentViewGen::Gen::kStencilOnlyRenderArea, load_op,
2797 SyncOrdering::kDepthStencilAttachment, tag);
2798 }
John Zulauf1507ee42020-05-18 11:33:09 -06002799 }
2800 }
2801 }
2802 }
2803}
John Zulaufd0ec59f2021-03-13 14:25:08 -07002804AttachmentViewGenVector RenderPassAccessContext::CreateAttachmentViewGen(
2805 const VkRect2D &render_area, const std::vector<const IMAGE_VIEW_STATE *> &attachment_views) {
2806 AttachmentViewGenVector view_gens;
2807 VkExtent3D extent = CastTo3D(render_area.extent);
2808 VkOffset3D offset = CastTo3D(render_area.offset);
2809 view_gens.reserve(attachment_views.size());
2810 for (const auto *view : attachment_views) {
2811 view_gens.emplace_back(view, offset, extent);
2812 }
2813 return view_gens;
2814}
John Zulauf64ffe552021-02-06 10:25:07 -07002815RenderPassAccessContext::RenderPassAccessContext(const RENDER_PASS_STATE &rp_state, const VkRect2D &render_area,
2816 VkQueueFlags queue_flags,
2817 const std::vector<const IMAGE_VIEW_STATE *> &attachment_views,
2818 const AccessContext *external_context)
John Zulaufd0ec59f2021-03-13 14:25:08 -07002819 : rp_state_(&rp_state), render_area_(render_area), current_subpass_(0U), attachment_views_() {
John Zulauf355e49b2020-04-24 15:11:15 -06002820 // Add this for all subpasses here so that they exsist during next subpass validation
John Zulauf64ffe552021-02-06 10:25:07 -07002821 subpass_contexts_.reserve(rp_state_->createInfo.subpassCount);
John Zulauf355e49b2020-04-24 15:11:15 -06002822 for (uint32_t pass = 0; pass < rp_state_->createInfo.subpassCount; pass++) {
John Zulauf1a224292020-06-30 14:52:13 -06002823 subpass_contexts_.emplace_back(pass, queue_flags, rp_state_->subpass_dependencies, subpass_contexts_, external_context);
John Zulauf355e49b2020-04-24 15:11:15 -06002824 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002825 attachment_views_ = CreateAttachmentViewGen(render_area, attachment_views);
John Zulauf64ffe552021-02-06 10:25:07 -07002826}
John Zulauf41a9c7c2021-12-07 15:59:53 -07002827void RenderPassAccessContext::RecordBeginRenderPass(const ResourceUsageTag barrier_tag, const ResourceUsageTag load_tag) {
John Zulauf64ffe552021-02-06 10:25:07 -07002828 assert(0 == current_subpass_);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002829 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2830 RecordLayoutTransitions(barrier_tag);
2831 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002832}
John Zulauf1507ee42020-05-18 11:33:09 -06002833
John Zulauf41a9c7c2021-12-07 15:59:53 -07002834void RenderPassAccessContext::RecordNextSubpass(const ResourceUsageTag store_tag, const ResourceUsageTag barrier_tag,
2835 const ResourceUsageTag load_tag) {
John Zulauf7635de32020-05-29 17:14:15 -06002836 // Resolves are against *prior* subpass context and thus *before* the subpass increment
John Zulauf41a9c7c2021-12-07 15:59:53 -07002837 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2838 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002839
ziga-lunarg31a3e772022-03-22 11:48:46 +01002840 if (current_subpass_ + 1 >= subpass_contexts_.size()) {
2841 return;
2842 }
Jeremy Gebben6ea9d9e2020-12-11 09:41:01 -07002843 // Move to the next sub-command for the new subpass. The resolve and store are logically part of the previous
2844 // subpass, so their tag needs to be different from the layout and load operations below.
John Zulauf355e49b2020-04-24 15:11:15 -06002845 current_subpass_++;
John Zulauf41a9c7c2021-12-07 15:59:53 -07002846 subpass_contexts_[current_subpass_].SetStartTag(barrier_tag);
2847 RecordLayoutTransitions(barrier_tag);
2848 RecordLoadOperations(load_tag);
John Zulauf355e49b2020-04-24 15:11:15 -06002849}
2850
John Zulauf41a9c7c2021-12-07 15:59:53 -07002851void RenderPassAccessContext::RecordEndRenderPass(AccessContext *external_context, const ResourceUsageTag store_tag,
2852 const ResourceUsageTag barrier_tag) {
John Zulaufaff20662020-06-01 14:07:58 -06002853 // Add the resolve and store accesses
John Zulauf41a9c7c2021-12-07 15:59:53 -07002854 CurrentContext().UpdateAttachmentResolveAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
2855 CurrentContext().UpdateAttachmentStoreAccess(*rp_state_, attachment_views_, current_subpass_, store_tag);
John Zulauf7635de32020-05-29 17:14:15 -06002856
John Zulauf355e49b2020-04-24 15:11:15 -06002857 // Export the accesses from the renderpass...
John Zulauf1a224292020-06-30 14:52:13 -06002858 external_context->ResolveChildContexts(subpass_contexts_);
John Zulauf355e49b2020-04-24 15:11:15 -06002859
2860 // Add the "finalLayout" transitions to external
2861 // Get them from where there we're hidding in the extra entry.
John Zulauf89311b42020-09-29 16:28:47 -06002862 // Not that since *final* always comes from *one* subpass per view, we don't have to accumulate the barriers
2863 // TODO Aliasing we may need to reconsider barrier accumulation... though I don't know that it would be valid for aliasing
2864 // that had mulitple final layout transistions from mulitple final subpasses.
John Zulauf355e49b2020-04-24 15:11:15 -06002865 const auto &final_transitions = rp_state_->subpass_transitions.back();
2866 for (const auto &transition : final_transitions) {
John Zulaufd0ec59f2021-03-13 14:25:08 -07002867 const AttachmentViewGen &view_gen = attachment_views_[transition.attachment];
John Zulauf355e49b2020-04-24 15:11:15 -06002868 const auto &last_trackback = subpass_contexts_[transition.prev_pass].GetDstExternalTrackBack();
John Zulaufbb890452021-12-14 11:30:18 -07002869 assert(&subpass_contexts_[transition.prev_pass] == last_trackback.source_subpass);
John Zulauf41a9c7c2021-12-07 15:59:53 -07002870 ApplyBarrierOpsFunctor<PipelineBarrierOp> barrier_action(true /* resolve */, last_trackback.barriers.size(), barrier_tag);
John Zulauf1e331ec2020-12-04 18:29:38 -07002871 for (const auto &barrier : last_trackback.barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002872 barrier_action.EmplaceBack(PipelineBarrierOp(QueueSyncState::kQueueIdInvalid, barrier, true));
John Zulauf1e331ec2020-12-04 18:29:38 -07002873 }
John Zulaufd0ec59f2021-03-13 14:25:08 -07002874 external_context->ApplyUpdateAction(view_gen, AttachmentViewGen::Gen::kViewSubresource, barrier_action);
John Zulauf355e49b2020-04-24 15:11:15 -06002875 }
2876}
2877
John Zulauf06f6f1e2022-04-19 15:28:11 -06002878SyncExecScope SyncExecScope::MakeSrc(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param,
2879 const VkPipelineStageFlags2KHR disabled_feature_mask) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002880 SyncExecScope result;
2881 result.mask_param = mask_param;
John Zulauf06f6f1e2022-04-19 15:28:11 -06002882 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags, disabled_feature_mask);
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002883 result.exec_scope = sync_utils::WithEarlierPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002884 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002885 return result;
2886}
2887
Jeremy Gebben40a22942020-12-22 14:22:06 -07002888SyncExecScope SyncExecScope::MakeDst(VkQueueFlags queue_flags, VkPipelineStageFlags2KHR mask_param) {
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002889 SyncExecScope result;
2890 result.mask_param = mask_param;
Jeremy Gebben5f585ae2021-02-02 09:03:06 -07002891 result.expanded_mask = sync_utils::ExpandPipelineStages(mask_param, queue_flags);
2892 result.exec_scope = sync_utils::WithLaterPipelineStages(result.expanded_mask);
Jeremy Gebben87fd0422022-06-08 15:43:47 -06002893 result.valid_accesses = SyncStageAccess::AccessScopeByStage(result.expanded_mask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002894 return result;
2895}
2896
John Zulaufecf4ac52022-06-06 10:08:42 -06002897SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst)
2898 : src_exec_scope(src), src_access_scope(0), dst_exec_scope(dst), dst_access_scope(0) {}
2899
2900SyncBarrier::SyncBarrier(const SyncExecScope &src, const SyncExecScope &dst, const SyncBarrier::AllAccess &)
2901 : src_exec_scope(src), src_access_scope(src.valid_accesses), dst_exec_scope(dst), dst_access_scope(src.valid_accesses) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002902
2903template <typename Barrier>
John Zulaufecf4ac52022-06-06 10:08:42 -06002904SyncBarrier::SyncBarrier(const Barrier &barrier, const SyncExecScope &src, const SyncExecScope &dst)
2905 : src_exec_scope(src),
2906 src_access_scope(SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask)),
2907 dst_exec_scope(dst),
2908 dst_access_scope(SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask)) {}
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002909
2910SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const VkSubpassDependency2 &subpass) {
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002911 const auto barrier = lvl_find_in_chain<VkMemoryBarrier2KHR>(subpass.pNext);
2912 if (barrier) {
2913 auto src = SyncExecScope::MakeSrc(queue_flags, barrier->srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002914 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002915 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier->srcAccessMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002916
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002917 auto dst = SyncExecScope::MakeDst(queue_flags, barrier->dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002918 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002919 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier->dstAccessMask);
2920
2921 } else {
2922 auto src = SyncExecScope::MakeSrc(queue_flags, subpass.srcStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002923 src_exec_scope = src;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002924 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, subpass.srcAccessMask);
2925
2926 auto dst = SyncExecScope::MakeDst(queue_flags, subpass.dstStageMask);
John Zulaufc523bf62021-02-16 08:20:34 -07002927 dst_exec_scope = dst;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002928 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, subpass.dstAccessMask);
2929 }
2930}
2931
2932template <typename Barrier>
2933SyncBarrier::SyncBarrier(VkQueueFlags queue_flags, const Barrier &barrier) {
2934 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
2935 src_exec_scope = src.exec_scope;
2936 src_access_scope = SyncStageAccess::AccessScope(src.valid_accesses, barrier.srcAccessMask);
2937
2938 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9893daf2021-01-04 10:40:50 -07002939 dst_exec_scope = dst.exec_scope;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07002940 dst_access_scope = SyncStageAccess::AccessScope(dst.valid_accesses, barrier.dstAccessMask);
John Zulauf3d84f1b2020-03-09 13:33:25 -06002941}
2942
John Zulaufb02c1eb2020-10-06 16:33:36 -06002943// Apply a list of barriers, without resolving pending state, useful for subpass layout transitions
2944void ResourceAccessState::ApplyBarriers(const std::vector<SyncBarrier> &barriers, bool layout_transition) {
John Zulauf00119522022-05-23 19:07:42 -06002945 const UntaggedScopeOps scope;
John Zulaufb02c1eb2020-10-06 16:33:36 -06002946 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002947 ApplyBarrier(scope, barrier, layout_transition);
John Zulaufb02c1eb2020-10-06 16:33:36 -06002948 }
2949}
2950
John Zulauf89311b42020-09-29 16:28:47 -06002951// ApplyBarriers is design for *fully* inclusive barrier lists without layout tranistions. Designed use was for
2952// inter-subpass barriers for lazy-evaluation of parent context memory ranges. Subpass layout transistions are *not* done
2953// lazily, s.t. no previous access reports should need layout transitions.
John Zulaufbb890452021-12-14 11:30:18 -07002954void ResourceAccessState::ApplyBarriersImmediate(const std::vector<SyncBarrier> &barriers) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06002955 assert(!pending_layout_transition); // This should never be call in the middle of another barrier application
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002956 assert(pending_write_barriers.none());
John Zulaufb02c1eb2020-10-06 16:33:36 -06002957 assert(!pending_write_dep_chain);
John Zulauf00119522022-05-23 19:07:42 -06002958 const UntaggedScopeOps scope;
John Zulaufa0a98292020-09-18 09:30:10 -06002959 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06002960 ApplyBarrier(scope, barrier, false);
John Zulaufa0a98292020-09-18 09:30:10 -06002961 }
John Zulaufbb890452021-12-14 11:30:18 -07002962 ApplyPendingBarriers(kInvalidTag); // There can't be any need for this tag
John Zulauf3d84f1b2020-03-09 13:33:25 -06002963}
John Zulauf9cb530d2019-09-30 14:14:10 -06002964HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index) const {
2965 HazardResult hazard;
2966 auto usage = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06002967 const auto usage_stage = PipelineStageBit(usage_index);
John Zulauf9cb530d2019-09-30 14:14:10 -06002968 if (IsRead(usage)) {
John Zulauf4285ee92020-09-23 10:20:52 -06002969 if (IsRAWHazard(usage_stage, usage)) {
John Zulauf59e25072020-07-17 10:55:21 -06002970 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002971 }
2972 } else {
John Zulauf361fb532020-07-22 10:45:39 -06002973 // Write operation:
2974 // Check for read operations more recent than last_write (as setting last_write clears reads, that would be *any*
2975 // If reads exists -- test only against them because either:
2976 // * the reads were hazards, and we've reported the hazard, so just test the current write vs. the read operations
2977 // * the read weren't hazards, and thus if the write is safe w.r.t. the reads, no hazard vs. last_write is possible if
2978 // the current write happens after the reads, so just test the write against the reades
2979 // Otherwise test against last_write
2980 //
2981 // Look for casus belli for WAR
John Zulaufab7756b2020-12-29 16:10:16 -07002982 if (last_reads.size()) {
2983 for (const auto &read_access : last_reads) {
John Zulauf361fb532020-07-22 10:45:39 -06002984 if (IsReadHazard(usage_stage, read_access)) {
2985 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
2986 break;
2987 }
2988 }
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07002989 } else if (last_write.any() && IsWriteHazard(usage)) {
John Zulauf361fb532020-07-22 10:45:39 -06002990 // Write-After-Write check -- if we have a previous write to test against
2991 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06002992 }
2993 }
2994 return hazard;
2995}
2996
John Zulaufec943ec2022-06-29 07:52:56 -06002997HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const SyncOrdering ordering_rule,
2998 QueueId queue_id) const {
John Zulauf8e3c3e92021-01-06 11:19:36 -07002999 const auto &ordering = GetOrderingRules(ordering_rule);
John Zulaufec943ec2022-06-29 07:52:56 -06003000 return DetectHazard(usage_index, ordering, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003001}
3002
John Zulaufec943ec2022-06-29 07:52:56 -06003003HazardResult ResourceAccessState::DetectHazard(SyncStageAccessIndex usage_index, const OrderingBarrier &ordering,
3004 QueueId queue_id) const {
John Zulauf69133422020-05-20 14:55:53 -06003005 // The ordering guarantees act as barriers to the last accesses, independent of synchronization operations
3006 HazardResult hazard;
John Zulauf4285ee92020-09-23 10:20:52 -06003007 const auto usage_bit = FlagBit(usage_index);
John Zulauf361fb532020-07-22 10:45:39 -06003008 const auto usage_stage = PipelineStageBit(usage_index);
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003009 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulaufec943ec2022-06-29 07:52:56 -06003010 const bool last_write_is_ordered = (last_write & ordering.access_scope).any() && (write_queue == queue_id);
John Zulauf4285ee92020-09-23 10:20:52 -06003011 if (IsRead(usage_bit)) {
3012 // Exclude RAW if no write, or write not most "most recent" operation w.r.t. usage;
3013 bool is_raw_hazard = IsRAWHazard(usage_stage, usage_bit);
3014 if (is_raw_hazard) {
3015 // NOTE: we know last_write is non-zero
3016 // See if the ordering rules save us from the simple RAW check above
3017 // First check to see if the current usage is covered by the ordering rules
3018 const bool usage_is_input_attachment = (usage_index == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ);
3019 const bool usage_is_ordered =
3020 (input_attachment_ordering && usage_is_input_attachment) || (0 != (usage_stage & ordering.exec_scope));
3021 if (usage_is_ordered) {
3022 // Now see of the most recent write (or a subsequent read) are ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003023 const bool most_recent_is_ordered = last_write_is_ordered || (0 != GetOrderedStages(queue_id, ordering));
John Zulauf4285ee92020-09-23 10:20:52 -06003024 is_raw_hazard = !most_recent_is_ordered;
John Zulauf361fb532020-07-22 10:45:39 -06003025 }
3026 }
John Zulauf4285ee92020-09-23 10:20:52 -06003027 if (is_raw_hazard) {
3028 hazard.Set(this, usage_index, READ_AFTER_WRITE, last_write, write_tag);
3029 }
John Zulauf5c628d02021-05-04 15:46:36 -06003030 } else if (usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3031 // For Image layout transitions, the barrier represents the first synchronization/access scope of the layout transition
John Zulaufec943ec2022-06-29 07:52:56 -06003032 return DetectBarrierHazard(usage_index, queue_id, ordering.exec_scope, ordering.access_scope);
John Zulauf361fb532020-07-22 10:45:39 -06003033 } else {
3034 // Only check for WAW if there are no reads since last_write
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003035 bool usage_write_is_ordered = (usage_bit & ordering.access_scope).any();
John Zulaufab7756b2020-12-29 16:10:16 -07003036 if (last_reads.size()) {
John Zulauf361fb532020-07-22 10:45:39 -06003037 // Look for any WAR hazards outside the ordered set of stages
Jeremy Gebben40a22942020-12-22 14:22:06 -07003038 VkPipelineStageFlags2KHR ordered_stages = 0;
John Zulauf4285ee92020-09-23 10:20:52 -06003039 if (usage_write_is_ordered) {
3040 // If the usage is ordered, we can ignore all ordered read stages w.r.t. WAR)
John Zulaufec943ec2022-06-29 07:52:56 -06003041 ordered_stages = GetOrderedStages(queue_id, ordering);
John Zulauf4285ee92020-09-23 10:20:52 -06003042 }
3043 // If we're tracking any reads that aren't ordered against the current write, got to check 'em all.
3044 if ((ordered_stages & last_read_stages) != last_read_stages) {
John Zulaufab7756b2020-12-29 16:10:16 -07003045 for (const auto &read_access : last_reads) {
John Zulauf4285ee92020-09-23 10:20:52 -06003046 if (read_access.stage & ordered_stages) continue; // but we can skip the ordered ones
3047 if (IsReadHazard(usage_stage, read_access)) {
3048 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
3049 break;
3050 }
John Zulaufd14743a2020-07-03 09:42:39 -06003051 }
3052 }
John Zulauf2a344ca2021-09-09 17:07:19 -06003053 } else if (last_write.any() && !(last_write_is_ordered && usage_write_is_ordered)) {
3054 bool ilt_ilt_hazard = false;
3055 if ((usage_index == SYNC_IMAGE_LAYOUT_TRANSITION) && (usage_bit == last_write)) {
3056 // ILT after ILT is a special case where we check the 2nd access scope of the first ILT against the first access
3057 // scope of the second ILT, which has been passed (smuggled?) in the ordering barrier
3058 ilt_ilt_hazard = !(write_barriers & ordering.access_scope).any();
3059 }
3060 if (ilt_ilt_hazard || IsWriteHazard(usage_bit)) {
John Zulauf4285ee92020-09-23 10:20:52 -06003061 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
John Zulauf361fb532020-07-22 10:45:39 -06003062 }
John Zulauf69133422020-05-20 14:55:53 -06003063 }
3064 }
3065 return hazard;
3066}
3067
John Zulaufec943ec2022-06-29 07:52:56 -06003068HazardResult ResourceAccessState::DetectHazard(const ResourceAccessState &recorded_use, QueueId queue_id,
3069 const ResourceUsageRange &tag_range) const {
John Zulaufae842002021-04-15 18:20:55 -06003070 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003071 using Size = FirstAccesses::size_type;
3072 const auto &recorded_accesses = recorded_use.first_accesses_;
3073 Size count = recorded_accesses.size();
3074 if (count) {
3075 const auto &last_access = recorded_accesses.back();
3076 bool do_write_last = IsWrite(last_access.usage_index);
3077 if (do_write_last) --count;
John Zulaufae842002021-04-15 18:20:55 -06003078
John Zulauf4fa68462021-04-26 21:04:22 -06003079 for (Size i = 0; i < count; ++count) {
3080 const auto &first = recorded_accesses[i];
3081 // Skip and quit logic
3082 if (first.tag < tag_range.begin) continue;
3083 if (first.tag >= tag_range.end) {
3084 do_write_last = false; // ignore last since we know it can't be in tag_range
3085 break;
3086 }
3087
John Zulaufec943ec2022-06-29 07:52:56 -06003088 hazard = DetectHazard(first.usage_index, first.ordering_rule, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003089 if (hazard.hazard) {
3090 hazard.AddRecordedAccess(first);
3091 break;
3092 }
3093 }
3094
3095 if (do_write_last && tag_range.includes(last_access.tag)) {
3096 // Writes are a bit special... both for the "most recent" access logic, and layout transition specific logic
3097 OrderingBarrier barrier = GetOrderingRules(last_access.ordering_rule);
3098 if (last_access.usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION) {
3099 // Or in the layout first access scope as a barrier... IFF the usage is an ILT
3100 // this was saved off in the "apply barriers" logic to simplify ILT access checks as they straddle
3101 // the barrier that applies them
3102 barrier |= recorded_use.first_write_layout_ordering_;
3103 }
3104 // Any read stages present in the recorded context (this) are most recent to the write, and thus mask those stages in
3105 // the active context
3106 if (recorded_use.first_read_stages_) {
3107 // we need to ignore the first use read stage in the active context (so we add them to the ordering rule),
3108 // reads in the active context are not "most recent" as all recorded context operations are *after* them
3109 // This supresses only RAW checks for stages present in the recorded context, but not those only present in the
3110 // active context.
3111 barrier.exec_scope |= recorded_use.first_read_stages_;
3112 // if there are any first use reads, we suppress WAW by injecting the active context write in the ordering rule
3113 barrier.access_scope |= FlagBit(last_access.usage_index);
3114 }
John Zulaufec943ec2022-06-29 07:52:56 -06003115 hazard = DetectHazard(last_access.usage_index, barrier, queue_id);
John Zulauf4fa68462021-04-26 21:04:22 -06003116 if (hazard.hazard) {
3117 hazard.AddRecordedAccess(last_access);
3118 }
3119 }
John Zulaufae842002021-04-15 18:20:55 -06003120 }
3121 return hazard;
3122}
3123
John Zulauf2f952d22020-02-10 11:34:51 -07003124// Asynchronous Hazards occur between subpasses with no connection through the DAG
John Zulauf14940722021-04-12 15:19:02 -06003125HazardResult ResourceAccessState::DetectAsyncHazard(SyncStageAccessIndex usage_index, const ResourceUsageTag start_tag) const {
John Zulauf2f952d22020-02-10 11:34:51 -07003126 HazardResult hazard;
3127 auto usage = FlagBit(usage_index);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003128 // Async checks need to not go back further than the start of the subpass, as we only want to find hazards between the async
3129 // subpasses. Anything older than that should have been checked at the start of each subpass, taking into account all of
3130 // the raster ordering rules.
John Zulauf2f952d22020-02-10 11:34:51 -07003131 if (IsRead(usage)) {
John Zulauf14940722021-04-12 15:19:02 -06003132 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003133 hazard.Set(this, usage_index, READ_RACING_WRITE, last_write, write_tag);
John Zulauf2f952d22020-02-10 11:34:51 -07003134 }
3135 } else {
John Zulauf14940722021-04-12 15:19:02 -06003136 if (last_write.any() && (write_tag >= start_tag)) {
John Zulauf59e25072020-07-17 10:55:21 -06003137 hazard.Set(this, usage_index, WRITE_RACING_WRITE, last_write, write_tag);
John Zulaufab7756b2020-12-29 16:10:16 -07003138 } else if (last_reads.size() > 0) {
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003139 // Any reads during the other subpass will conflict with this write, so we need to check them all.
John Zulaufab7756b2020-12-29 16:10:16 -07003140 for (const auto &read_access : last_reads) {
John Zulauf14940722021-04-12 15:19:02 -06003141 if (read_access.tag >= start_tag) {
John Zulaufab7756b2020-12-29 16:10:16 -07003142 hazard.Set(this, usage_index, WRITE_RACING_READ, read_access.access, read_access.tag);
Jeremy Gebbenc4b78c52020-12-11 09:39:47 -07003143 break;
3144 }
3145 }
John Zulauf2f952d22020-02-10 11:34:51 -07003146 }
3147 }
3148 return hazard;
3149}
3150
John Zulaufae842002021-04-15 18:20:55 -06003151HazardResult ResourceAccessState::DetectAsyncHazard(const ResourceAccessState &recorded_use, const ResourceUsageRange &tag_range,
3152 ResourceUsageTag start_tag) const {
3153 HazardResult hazard;
John Zulauf4fa68462021-04-26 21:04:22 -06003154 for (const auto &first : recorded_use.first_accesses_) {
John Zulaufae842002021-04-15 18:20:55 -06003155 // Skip and quit logic
3156 if (first.tag < tag_range.begin) continue;
3157 if (first.tag >= tag_range.end) break;
John Zulaufae842002021-04-15 18:20:55 -06003158
3159 hazard = DetectAsyncHazard(first.usage_index, start_tag);
John Zulauf4fa68462021-04-26 21:04:22 -06003160 if (hazard.hazard) {
3161 hazard.AddRecordedAccess(first);
3162 break;
3163 }
John Zulaufae842002021-04-15 18:20:55 -06003164 }
3165 return hazard;
3166}
3167
John Zulaufec943ec2022-06-29 07:52:56 -06003168HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, QueueId queue_id,
3169 VkPipelineStageFlags2KHR src_exec_scope,
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003170 const SyncStageAccessFlags &src_access_scope) const {
John Zulauf0cb5be22020-01-23 12:18:22 -07003171 // Only supporting image layout transitions for now
3172 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3173 HazardResult hazard;
John Zulauf361fb532020-07-22 10:45:39 -06003174 // only test for WAW if there no intervening read operations.
3175 // See DetectHazard(SyncStagetAccessIndex) above for more details.
John Zulaufab7756b2020-12-29 16:10:16 -07003176 if (last_reads.size()) {
John Zulauf355e49b2020-04-24 15:11:15 -06003177 // Look at the reads if any
John Zulaufab7756b2020-12-29 16:10:16 -07003178 for (const auto &read_access : last_reads) {
John Zulaufec943ec2022-06-29 07:52:56 -06003179 if (read_access.IsReadBarrierHazard(queue_id, src_exec_scope)) {
John Zulauf59e25072020-07-17 10:55:21 -06003180 hazard.Set(this, usage_index, WRITE_AFTER_READ, read_access.access, read_access.tag);
John Zulauf0cb5be22020-01-23 12:18:22 -07003181 break;
3182 }
3183 }
John Zulaufec943ec2022-06-29 07:52:56 -06003184 } else if (last_write.any() && IsWriteBarrierHazard(queue_id, src_exec_scope, src_access_scope)) {
John Zulauf4a6105a2020-11-17 15:11:05 -07003185 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3186 }
3187
3188 return hazard;
3189}
3190
John Zulaufe0757ba2022-06-10 16:51:45 -06003191HazardResult ResourceAccessState::DetectBarrierHazard(SyncStageAccessIndex usage_index, const ResourceAccessState &scope_state,
3192 VkPipelineStageFlags2KHR src_exec_scope,
3193 const SyncStageAccessFlags &src_access_scope, QueueId event_queue,
3194 ResourceUsageTag event_tag) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07003195 // Only supporting image layout transitions for now
3196 assert(usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
3197 HazardResult hazard;
John Zulauf4a6105a2020-11-17 15:11:05 -07003198
John Zulaufe0757ba2022-06-10 16:51:45 -06003199 if ((write_tag >= event_tag) && last_write.any()) {
3200 // Any write after the event precludes the possibility of being in the first access scope for the layout transition
3201 hazard.Set(this, usage_index, WRITE_AFTER_WRITE, last_write, write_tag);
3202 } else {
3203 // only test for WAW if there no intervening read operations.
3204 // See DetectHazard(SyncStagetAccessIndex) above for more details.
3205 if (last_reads.size()) {
3206 // Look at the reads if any... if reads exist, they are either the reason the access is in the event
3207 // first scope, or they are a hazard.
3208 const ReadStates &scope_reads = scope_state.last_reads;
3209 const ReadStates::size_type scope_read_count = scope_reads.size();
3210 // Since the hasn't been a write:
3211 // * The current read state is a superset of the scoped one
3212 // * The stage order is the same.
3213 assert(last_reads.size() >= scope_read_count);
3214 for (ReadStates::size_type read_idx = 0; read_idx < scope_read_count; ++read_idx) {
3215 const ReadState &scope_read = scope_reads[read_idx];
3216 const ReadState &current_read = last_reads[read_idx];
3217 assert(scope_read.stage == current_read.stage);
3218 if (current_read.tag > event_tag) {
3219 // The read is more recent than the set event scope, thus no barrier from the wait/ILT.
3220 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3221 } else {
3222 // The read is in the events first synchronization scope, so we use a barrier hazard check
3223 // If the read stage is not in the src sync scope
3224 // *AND* not execution chained with an existing sync barrier (that's the or)
3225 // then the barrier access is unsafe (R/W after R)
3226 if (scope_read.IsReadBarrierHazard(event_queue, src_exec_scope)) {
3227 hazard.Set(this, usage_index, WRITE_AFTER_READ, scope_read.access, scope_read.tag);
3228 break;
3229 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003230 }
John Zulauf4a6105a2020-11-17 15:11:05 -07003231 }
John Zulaufe0757ba2022-06-10 16:51:45 -06003232 if (!hazard.IsHazard() && (last_reads.size() > scope_read_count)) {
3233 const ReadState &current_read = last_reads[scope_read_count];
3234 hazard.Set(this, usage_index, WRITE_AFTER_READ, current_read.access, current_read.tag);
3235 }
3236 } else if (last_write.any()) {
3237 // if there are no reads, the write is either the reason the access is in the event scope... they are a hazard
John Zulauf4a6105a2020-11-17 15:11:05 -07003238 // The write is in the first sync scope of the event (sync their aren't any reads to be the reason)
3239 // So do a normal barrier hazard check
John Zulaufe0757ba2022-06-10 16:51:45 -06003240 if (scope_state.IsWriteBarrierHazard(src_exec_scope, src_access_scope)) {
3241 hazard.Set(&scope_state, usage_index, WRITE_AFTER_WRITE, scope_state.last_write, scope_state.write_tag);
John Zulauf4a6105a2020-11-17 15:11:05 -07003242 }
John Zulauf361fb532020-07-22 10:45:39 -06003243 }
John Zulaufd14743a2020-07-03 09:42:39 -06003244 }
John Zulauf361fb532020-07-22 10:45:39 -06003245
John Zulauf0cb5be22020-01-23 12:18:22 -07003246 return hazard;
3247}
3248
John Zulauf5f13a792020-03-10 07:31:21 -06003249// The logic behind resolves is the same as update, we assume that earlier hazards have be reported, and that no
3250// tranistive hazard can exists with a hazard between the earlier operations. Yes, an early hazard can mask that another
3251// exists, but if you fix *that* hazard it either fixes or unmasks the subsequent ones.
3252void ResourceAccessState::Resolve(const ResourceAccessState &other) {
John Zulauf14940722021-04-12 15:19:02 -06003253 if (write_tag < other.write_tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003254 // If this is a later write, we've reported any exsiting hazard, and we can just overwrite as the more recent
3255 // operation
John Zulauf5f13a792020-03-10 07:31:21 -06003256 *this = other;
John Zulauf14940722021-04-12 15:19:02 -06003257 } else if (other.write_tag == write_tag) {
3258 // In the *equals* case for write operations, we merged the write barriers and the read state (but without the
John Zulauf5f13a792020-03-10 07:31:21 -06003259 // dependency chaining logic or any stage expansion)
3260 write_barriers |= other.write_barriers;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003261 pending_write_barriers |= other.pending_write_barriers;
3262 pending_layout_transition |= other.pending_layout_transition;
3263 pending_write_dep_chain |= other.pending_write_dep_chain;
John Zulauf4fa68462021-04-26 21:04:22 -06003264 pending_layout_ordering_ |= other.pending_layout_ordering_;
John Zulauf5f13a792020-03-10 07:31:21 -06003265
John Zulaufd14743a2020-07-03 09:42:39 -06003266 // Merge the read states
John Zulaufab7756b2020-12-29 16:10:16 -07003267 const auto pre_merge_count = last_reads.size();
John Zulauf4285ee92020-09-23 10:20:52 -06003268 const auto pre_merge_stages = last_read_stages;
John Zulaufab7756b2020-12-29 16:10:16 -07003269 for (uint32_t other_read_index = 0; other_read_index < other.last_reads.size(); other_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003270 auto &other_read = other.last_reads[other_read_index];
John Zulauf4285ee92020-09-23 10:20:52 -06003271 if (pre_merge_stages & other_read.stage) {
John Zulauf5f13a792020-03-10 07:31:21 -06003272 // Merge in the barriers for read stages that exist in *both* this and other
John Zulauf4285ee92020-09-23 10:20:52 -06003273 // TODO: This is N^2 with stages... perhaps the ReadStates should be sorted by stage index.
3274 // but we should wait on profiling data for that.
3275 for (uint32_t my_read_index = 0; my_read_index < pre_merge_count; my_read_index++) {
John Zulauf5f13a792020-03-10 07:31:21 -06003276 auto &my_read = last_reads[my_read_index];
3277 if (other_read.stage == my_read.stage) {
John Zulauf14940722021-04-12 15:19:02 -06003278 if (my_read.tag < other_read.tag) {
John Zulauf4285ee92020-09-23 10:20:52 -06003279 // Other is more recent, copy in the state
John Zulauf37ceaed2020-07-03 16:18:15 -06003280 my_read.access = other_read.access;
John Zulauf4285ee92020-09-23 10:20:52 -06003281 my_read.tag = other_read.tag;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003282 my_read.queue = other_read.queue;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003283 my_read.pending_dep_chain = other_read.pending_dep_chain;
3284 // TODO: Phase 2 -- review the state merge logic to avoid false positive from overwriting the barriers
3285 // May require tracking more than one access per stage.
3286 my_read.barriers = other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003287 my_read.sync_stages = other_read.sync_stages;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003288 if (my_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauf4285ee92020-09-23 10:20:52 -06003289 // Since I'm overwriting the fragement stage read, also update the input attachment info
3290 // as this is the only stage that affects it.
John Zulauff51fbb62020-10-02 14:43:24 -06003291 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003292 }
John Zulauf14940722021-04-12 15:19:02 -06003293 } else if (other_read.tag == my_read.tag) {
John Zulaufb02c1eb2020-10-06 16:33:36 -06003294 // The read tags match so merge the barriers
3295 my_read.barriers |= other_read.barriers;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003296 my_read.sync_stages |= other_read.sync_stages;
John Zulaufb02c1eb2020-10-06 16:33:36 -06003297 my_read.pending_dep_chain |= other_read.pending_dep_chain;
John Zulauf5f13a792020-03-10 07:31:21 -06003298 }
John Zulaufb02c1eb2020-10-06 16:33:36 -06003299
John Zulauf5f13a792020-03-10 07:31:21 -06003300 break;
3301 }
3302 }
3303 } else {
3304 // The other read stage doesn't exist in this, so add it.
John Zulaufab7756b2020-12-29 16:10:16 -07003305 last_reads.emplace_back(other_read);
John Zulauf5f13a792020-03-10 07:31:21 -06003306 last_read_stages |= other_read.stage;
Jeremy Gebben40a22942020-12-22 14:22:06 -07003307 if (other_read.stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003308 input_attachment_read = other.input_attachment_read;
John Zulauf4285ee92020-09-23 10:20:52 -06003309 }
John Zulauf5f13a792020-03-10 07:31:21 -06003310 }
3311 }
John Zulauf361fb532020-07-22 10:45:39 -06003312 read_execution_barriers |= other.read_execution_barriers;
John Zulauf4285ee92020-09-23 10:20:52 -06003313 } // the else clause would be that other write is before this write... in which case we supercede the other state and
3314 // ignore it.
John Zulauffaea0ee2021-01-14 14:01:32 -07003315
3316 // Merge first access information by making a copy of this first_access and reconstructing with a shuffle
3317 // of the copy and other into this using the update first logic.
3318 // NOTE: All sorts of additional cleverness could be put into short circuts. (for example back is write and is before front
3319 // of the other first_accesses... )
3320 if (!(first_accesses_ == other.first_accesses_) && !other.first_accesses_.empty()) {
3321 FirstAccesses firsts(std::move(first_accesses_));
3322 first_accesses_.clear();
3323 first_read_stages_ = 0U;
3324 auto a = firsts.begin();
3325 auto a_end = firsts.end();
3326 for (auto &b : other.first_accesses_) {
John Zulauf14940722021-04-12 15:19:02 -06003327 // TODO: Determine whether some tag offset will be needed for PHASE II
3328 while ((a != a_end) && (a->tag < b.tag)) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003329 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3330 ++a;
3331 }
3332 UpdateFirst(b.tag, b.usage_index, b.ordering_rule);
3333 }
3334 for (; a != a_end; ++a) {
3335 UpdateFirst(a->tag, a->usage_index, a->ordering_rule);
3336 }
3337 }
John Zulauf5f13a792020-03-10 07:31:21 -06003338}
3339
John Zulauf14940722021-04-12 15:19:02 -06003340void ResourceAccessState::Update(SyncStageAccessIndex usage_index, SyncOrdering ordering_rule, const ResourceUsageTag tag) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003341 // Move this logic in the ResourceStateTracker as methods, thereof (or we'll repeat it for every flavor of resource...
3342 const auto usage_bit = FlagBit(usage_index);
John Zulauf4285ee92020-09-23 10:20:52 -06003343 if (IsRead(usage_index)) {
John Zulauf9cb530d2019-09-30 14:14:10 -06003344 // Mulitple outstanding reads may be of interest and do dependency chains independently
3345 // However, for purposes of barrier tracking, only one read per pipeline stage matters
3346 const auto usage_stage = PipelineStageBit(usage_index);
3347 if (usage_stage & last_read_stages) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003348 const auto not_usage_stage = ~usage_stage;
John Zulaufab7756b2020-12-29 16:10:16 -07003349 for (auto &read_access : last_reads) {
3350 if (read_access.stage == usage_stage) {
3351 read_access.Set(usage_stage, usage_bit, 0, tag);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003352 } else if (read_access.barriers & usage_stage) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003353 // If the current access is barriered to this stage, mark it as "known to happen after"
John Zulauf1d5f9c12022-05-13 14:51:08 -06003354 read_access.sync_stages |= usage_stage;
John Zulaufecf4ac52022-06-06 10:08:42 -06003355 } else {
3356 // If the current access is *NOT* barriered to this stage it needs to be cleared.
3357 // Note: this is possible because semaphores can *clear* effective barriers, so the assumption
3358 // that sync_stages is a subset of barriers may not apply.
3359 read_access.sync_stages &= not_usage_stage;
John Zulauf9cb530d2019-09-30 14:14:10 -06003360 }
3361 }
3362 } else {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003363 for (auto &read_access : last_reads) {
3364 if (read_access.barriers & usage_stage) {
3365 read_access.sync_stages |= usage_stage;
3366 }
3367 }
John Zulaufab7756b2020-12-29 16:10:16 -07003368 last_reads.emplace_back(usage_stage, usage_bit, 0, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003369 last_read_stages |= usage_stage;
3370 }
John Zulauf4285ee92020-09-23 10:20:52 -06003371
3372 // Fragment shader reads come in two flavors, and we need to track if the one we're tracking is the special one.
Jeremy Gebben40a22942020-12-22 14:22:06 -07003373 if (usage_stage == VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR) {
John Zulauff51fbb62020-10-02 14:43:24 -06003374 // TODO Revisit re: multiple reads for a given stage
3375 input_attachment_read = (usage_bit == SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT);
John Zulauf4285ee92020-09-23 10:20:52 -06003376 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003377 } else {
3378 // Assume write
3379 // TODO determine what to do with READ-WRITE operations if any
John Zulauf89311b42020-09-29 16:28:47 -06003380 SetWrite(usage_bit, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003381 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003382 UpdateFirst(tag, usage_index, ordering_rule);
John Zulauf9cb530d2019-09-30 14:14:10 -06003383}
John Zulauf5f13a792020-03-10 07:31:21 -06003384
John Zulauf89311b42020-09-29 16:28:47 -06003385// Clobber last read and all barriers... because all we have is DANGER, DANGER, WILL ROBINSON!!!
3386// if the last_reads/last_write were unsafe, we've reported them, in either case the prior access is irrelevant.
3387// We can overwrite them as *this* write is now after them.
3388//
3389// Note: intentionally ignore pending barriers and chains (i.e. don't apply or clear them), let ApplyPendingBarriers handle them.
John Zulauf14940722021-04-12 15:19:02 -06003390void ResourceAccessState::SetWrite(const SyncStageAccessFlags &usage_bit, const ResourceUsageTag tag) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003391 ClearRead();
3392 ClearWrite();
John Zulauf89311b42020-09-29 16:28:47 -06003393 write_tag = tag;
3394 last_write = usage_bit;
John Zulauf9cb530d2019-09-30 14:14:10 -06003395}
3396
John Zulauf1d5f9c12022-05-13 14:51:08 -06003397void ResourceAccessState::ClearWrite() {
3398 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3399 input_attachment_read = false; // Denotes no outstanding input attachment read after the last write.
3400 write_barriers.reset();
3401 write_dependency_chain = VK_PIPELINE_STAGE_2_NONE;
3402 last_write.reset();
3403
3404 write_tag = 0;
3405 write_queue = QueueSyncState::kQueueIdInvalid;
3406}
3407
3408void ResourceAccessState::ClearRead() {
3409 last_reads.clear();
3410 last_read_stages = VK_PIPELINE_STAGE_2_NONE;
3411}
3412
John Zulauf89311b42020-09-29 16:28:47 -06003413// Apply the memory barrier without updating the existing barriers. The execution barrier
3414// changes the "chaining" state, but to keep barriers independent, we defer this until all barriers
3415// of the batch have been processed. Also, depending on whether layout transition happens, we'll either
3416// replace the current write barriers or add to them, so accumulate to pending as well.
John Zulaufb7578302022-05-19 13:50:18 -06003417template <typename ScopeOps>
3418void ResourceAccessState::ApplyBarrier(ScopeOps &&scope, const SyncBarrier &barrier, bool layout_transition) {
John Zulauf89311b42020-09-29 16:28:47 -06003419 // For independent barriers we need to track what the new barriers and dependency chain *will* be when we're done
3420 // applying the memory barriers
John Zulauf86356ca2020-10-19 11:46:41 -06003421 // NOTE: We update the write barrier if the write is in the first access scope or if there is a layout
John Zulaufb7578302022-05-19 13:50:18 -06003422 // transistion, under the theory of "most recent access". If the resource acces *isn't* safe
John Zulauf86356ca2020-10-19 11:46:41 -06003423 // vs. this layout transition DetectBarrierHazard should report it. We treat the layout
3424 // transistion *as* a write and in scope with the barrier (it's before visibility).
John Zulaufb7578302022-05-19 13:50:18 -06003425 if (layout_transition || scope.WriteInScope(barrier, *this)) {
John Zulauf89311b42020-09-29 16:28:47 -06003426 pending_write_barriers |= barrier.dst_access_scope;
John Zulaufc523bf62021-02-16 08:20:34 -07003427 pending_write_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulauf4fa68462021-04-26 21:04:22 -06003428 if (layout_transition) {
3429 pending_layout_ordering_ |= OrderingBarrier(barrier.src_exec_scope.exec_scope, barrier.src_access_scope);
3430 }
John Zulaufa0a98292020-09-18 09:30:10 -06003431 }
John Zulauf89311b42020-09-29 16:28:47 -06003432 // Track layout transistion as pending as we can't modify last_write until all barriers processed
3433 pending_layout_transition |= layout_transition;
John Zulaufa0a98292020-09-18 09:30:10 -06003434
John Zulauf89311b42020-09-29 16:28:47 -06003435 if (!pending_layout_transition) {
John Zulaufb7578302022-05-19 13:50:18 -06003436 // Once we're dealing with a layout transition (which is modelled as a *write*) then the last reads/chains
3437 // don't need to be tracked as we're just going to clear them.
John Zulauf434c4e62022-05-19 16:03:56 -06003438 VkPipelineStageFlags2 stages_in_scope = VK_PIPELINE_STAGE_2_NONE;
3439
John Zulaufab7756b2020-12-29 16:10:16 -07003440 for (auto &read_access : last_reads) {
John Zulauf89311b42020-09-29 16:28:47 -06003441 // The | implements the "dependency chain" logic for this access, as the barriers field stores the second sync scope
John Zulaufb7578302022-05-19 13:50:18 -06003442 if (scope.ReadInScope(barrier, read_access)) {
John Zulauf434c4e62022-05-19 16:03:56 -06003443 // We'll apply the barrier in the next loop, because it's DRY'r to do it one place.
3444 stages_in_scope |= read_access.stage;
3445 }
3446 }
3447
3448 for (auto &read_access : last_reads) {
3449 if (0 != ((read_access.stage | read_access.sync_stages) & stages_in_scope)) {
3450 // If this stage, or any stage known to be synchronized after it are in scope, apply the barrier to this read
3451 // NOTE: Forwarding barriers to known prior stages changes the sync_stages from shallow to deep, because the
3452 // barriers used to determine sync_stages have been propagated to all known earlier stages
John Zulaufc523bf62021-02-16 08:20:34 -07003453 read_access.pending_dep_chain |= barrier.dst_exec_scope.exec_scope;
John Zulaufa0a98292020-09-18 09:30:10 -06003454 }
3455 }
John Zulaufa0a98292020-09-18 09:30:10 -06003456 }
John Zulaufa0a98292020-09-18 09:30:10 -06003457}
3458
John Zulauf14940722021-04-12 15:19:02 -06003459void ResourceAccessState::ApplyPendingBarriers(const ResourceUsageTag tag) {
John Zulauf89311b42020-09-29 16:28:47 -06003460 if (pending_layout_transition) {
John Zulauf4fa68462021-04-26 21:04:22 -06003461 // SetWrite clobbers the last_reads array, and thus we don't have to clear the read_state out.
John Zulauf89311b42020-09-29 16:28:47 -06003462 SetWrite(SYNC_IMAGE_LAYOUT_TRANSITION_BIT, tag); // Side effect notes below
John Zulauffaea0ee2021-01-14 14:01:32 -07003463 UpdateFirst(tag, SYNC_IMAGE_LAYOUT_TRANSITION, SyncOrdering::kNonAttachment);
John Zulauf4fa68462021-04-26 21:04:22 -06003464 TouchupFirstForLayoutTransition(tag, pending_layout_ordering_);
3465 pending_layout_ordering_ = OrderingBarrier();
John Zulauf89311b42020-09-29 16:28:47 -06003466 pending_layout_transition = false;
John Zulauf9cb530d2019-09-30 14:14:10 -06003467 }
John Zulauf89311b42020-09-29 16:28:47 -06003468
3469 // Apply the accumulate execution barriers (and thus update chaining information)
John Zulauf4fa68462021-04-26 21:04:22 -06003470 // for layout transition, last_reads is reset by SetWrite, so this will be skipped.
John Zulaufab7756b2020-12-29 16:10:16 -07003471 for (auto &read_access : last_reads) {
3472 read_access.barriers |= read_access.pending_dep_chain;
3473 read_execution_barriers |= read_access.barriers;
3474 read_access.pending_dep_chain = 0;
John Zulauf89311b42020-09-29 16:28:47 -06003475 }
3476
3477 // We OR in the accumulated write chain and barriers even in the case of a layout transition as SetWrite zeros them.
3478 write_dependency_chain |= pending_write_dep_chain;
3479 write_barriers |= pending_write_barriers;
3480 pending_write_dep_chain = 0;
3481 pending_write_barriers = 0;
John Zulauf9cb530d2019-09-30 14:14:10 -06003482}
3483
John Zulaufecf4ac52022-06-06 10:08:42 -06003484// Assumes signal queue != wait queue
3485void ResourceAccessState::ApplySemaphore(const SemaphoreScope &signal, const SemaphoreScope wait) {
3486 // Semaphores only guarantee the first scope of the signal is before the second scope of the wait.
3487 // If any access isn't in the first scope, there are no guarantees, thus those barriers are cleared
3488 assert(signal.queue != wait.queue);
3489 for (auto &read_access : last_reads) {
3490 if (read_access.ReadInQueueScopeOrChain(signal.queue, signal.exec_scope)) {
3491 // Deflects WAR on wait queue
3492 read_access.barriers = wait.exec_scope;
3493 } else {
3494 // Leave sync stages alone. Update method will clear unsynchronized stages on subsequent reads as needed.
3495 read_access.barriers = VK_PIPELINE_STAGE_2_NONE;
3496 }
3497 }
3498 if (WriteInQueueSourceScopeOrChain(signal.queue, signal.exec_scope, signal.valid_accesses)) {
3499 // Will deflect RAW wait queue, WAW needs a chained barrier on wait queue
3500 read_execution_barriers = wait.exec_scope;
3501 write_barriers = wait.valid_accesses;
3502 } else {
3503 read_execution_barriers = VK_PIPELINE_STAGE_2_NONE;
3504 write_barriers.reset();
3505 }
3506 write_dependency_chain = read_execution_barriers;
3507}
3508
John Zulauf1d5f9c12022-05-13 14:51:08 -06003509bool ResourceAccessState::QueueTagPredicate::operator()(QueueId usage_queue, ResourceUsageTag usage_tag) {
3510 return (queue == usage_queue) && (tag <= usage_tag);
3511}
3512
3513bool ResourceAccessState::QueuePredicate::operator()(QueueId usage_queue, ResourceUsageTag) { return queue == usage_queue; }
3514
3515bool ResourceAccessState::TagPredicate::operator()(QueueId, ResourceUsageTag usage_tag) { return tag <= usage_tag; }
3516
3517// Return if the resulting state is "empty"
3518template <typename Pred>
3519bool ResourceAccessState::ApplyQueueTagWait(Pred &&queue_tag_test) {
3520 VkPipelineStageFlags2KHR sync_reads = VK_PIPELINE_STAGE_2_NONE;
3521
3522 // Use the predicate to build a mask of the read stages we are synchronizing
3523 // Use the sync_stages to also detect reads known to be before any synchronized reads (first pass)
John Zulauf1d5f9c12022-05-13 14:51:08 -06003524 for (auto &read_access : last_reads) {
John Zulauf434c4e62022-05-19 16:03:56 -06003525 if (queue_tag_test(read_access.queue, read_access.tag)) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003526 // If we know this stage is before any stage we syncing, or if the predicate tells us that we are waited for..
3527 sync_reads |= read_access.stage;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003528 }
3529 }
3530
John Zulauf434c4e62022-05-19 16:03:56 -06003531 // Now that we know the reads directly in scopejust need to go over the list again to pick up the "known earlier" stages.
3532 // NOTE: sync_stages is "deep" catching all stages synchronized after it because we forward barriers
3533 uint32_t unsync_count = 0;
3534 for (auto &read_access : last_reads) {
3535 if (0 != ((read_access.stage | read_access.sync_stages) & sync_reads)) {
3536 // This is redundant in the "stage" case, but avoids a second branch to get an accurate count
3537 sync_reads |= read_access.stage;
3538 } else {
3539 ++unsync_count;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003540 }
3541 }
3542
3543 if (unsync_count) {
3544 if (sync_reads) {
3545 // When have some remaining unsynchronized reads, we have to rewrite the last_reads array.
3546 ReadStates unsync_reads;
3547 unsync_reads.reserve(unsync_count);
3548 VkPipelineStageFlags2KHR unsync_read_stages = VK_PIPELINE_STAGE_2_NONE;
3549 for (auto &read_access : last_reads) {
3550 if (0 == (read_access.stage & sync_reads)) {
3551 unsync_reads.emplace_back(read_access);
3552 unsync_read_stages |= read_access.stage;
3553 }
3554 }
3555 last_read_stages = unsync_read_stages;
3556 last_reads = std::move(unsync_reads);
3557 }
3558 } else {
3559 // Nothing remains (or it was empty to begin with)
3560 ClearRead();
3561 }
3562
3563 bool all_clear = last_reads.size() == 0;
3564 if (last_write.any()) {
3565 if (queue_tag_test(write_queue, write_tag) || sync_reads) {
3566 // Clear any predicated write, or any the write from any any access with synchronized reads.
3567 // This could drop RAW detection, but only if the synchronized reads were RAW hazards, and given
3568 // MRR approach to reporting, this is consistent with other drops, especially since fixing the
3569 // RAW wit the sync_reads stages would preclude a subsequent RAW.
3570 ClearWrite();
3571 } else {
3572 all_clear = false;
3573 }
3574 }
3575 return all_clear;
3576}
3577
John Zulaufae842002021-04-15 18:20:55 -06003578bool ResourceAccessState::FirstAccessInTagRange(const ResourceUsageRange &tag_range) const {
3579 if (!first_accesses_.size()) return false;
3580 const ResourceUsageRange first_access_range = {first_accesses_.front().tag, first_accesses_.back().tag + 1};
3581 return tag_range.intersects(first_access_range);
3582}
3583
John Zulauf1d5f9c12022-05-13 14:51:08 -06003584void ResourceAccessState::OffsetTag(ResourceUsageTag offset) {
3585 if (last_write.any()) write_tag += offset;
3586 for (auto &read_access : last_reads) {
3587 read_access.tag += offset;
3588 }
3589 for (auto &first : first_accesses_) {
3590 first.tag += offset;
3591 }
3592}
3593
3594ResourceAccessState::ResourceAccessState()
3595 : write_barriers(~SyncStageAccessFlags(0)),
3596 write_dependency_chain(0),
3597 write_tag(),
3598 write_queue(QueueSyncState::kQueueIdInvalid),
3599 last_write(0),
3600 input_attachment_read(false),
3601 last_read_stages(0),
3602 read_execution_barriers(0),
3603 pending_write_dep_chain(0),
3604 pending_layout_transition(false),
3605 pending_write_barriers(0),
3606 pending_layout_ordering_(),
3607 first_accesses_(),
3608 first_read_stages_(0U),
3609 first_write_layout_ordering_() {}
3610
John Zulauf59e25072020-07-17 10:55:21 -06003611// This should be just Bits or Index, but we don't have an invalid state for Index
Jeremy Gebben40a22942020-12-22 14:22:06 -07003612VkPipelineStageFlags2KHR ResourceAccessState::GetReadBarriers(const SyncStageAccessFlags &usage_bit) const {
3613 VkPipelineStageFlags2KHR barriers = 0U;
John Zulauf4285ee92020-09-23 10:20:52 -06003614
John Zulaufab7756b2020-12-29 16:10:16 -07003615 for (const auto &read_access : last_reads) {
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003616 if ((read_access.access & usage_bit).any()) {
John Zulauf4285ee92020-09-23 10:20:52 -06003617 barriers = read_access.barriers;
3618 break;
John Zulauf59e25072020-07-17 10:55:21 -06003619 }
3620 }
John Zulauf4285ee92020-09-23 10:20:52 -06003621
John Zulauf59e25072020-07-17 10:55:21 -06003622 return barriers;
3623}
3624
John Zulauf1d5f9c12022-05-13 14:51:08 -06003625void ResourceAccessState::SetQueueId(QueueId id) {
3626 for (auto &read_access : last_reads) {
3627 if (read_access.queue == QueueSyncState::kQueueIdInvalid) {
3628 read_access.queue = id;
3629 }
3630 }
3631 if (last_write.any() && (write_queue == QueueSyncState::kQueueIdInvalid)) {
3632 write_queue = id;
3633 }
3634}
3635
John Zulauf00119522022-05-23 19:07:42 -06003636bool ResourceAccessState::WriteInChain(VkPipelineStageFlags2KHR src_exec_scope) const {
3637 return 0 != (write_dependency_chain & src_exec_scope);
3638}
3639
3640bool ResourceAccessState::WriteInScope(const SyncStageAccessFlags &src_access_scope) const {
3641 return (src_access_scope & last_write).any();
3642}
3643
John Zulaufec943ec2022-06-29 07:52:56 -06003644bool ResourceAccessState::WriteBarrierInScope(const SyncStageAccessFlags &src_access_scope) const {
3645 return (write_barriers & src_access_scope).any();
3646}
3647
John Zulaufb7578302022-05-19 13:50:18 -06003648bool ResourceAccessState::WriteInSourceScopeOrChain(VkPipelineStageFlags2KHR src_exec_scope,
3649 SyncStageAccessFlags src_access_scope) const {
John Zulauf00119522022-05-23 19:07:42 -06003650 return WriteInChain(src_exec_scope) || WriteInScope(src_access_scope);
3651}
3652
3653bool ResourceAccessState::WriteInQueueSourceScopeOrChain(QueueId queue, VkPipelineStageFlags2KHR src_exec_scope,
3654 SyncStageAccessFlags src_access_scope) const {
3655 return WriteInChain(src_exec_scope) || ((queue == write_queue) && WriteInScope(src_access_scope));
John Zulaufb7578302022-05-19 13:50:18 -06003656}
3657
John Zulaufe0757ba2022-06-10 16:51:45 -06003658bool ResourceAccessState::WriteInEventScope(VkPipelineStageFlags2KHR src_exec_scope, const SyncStageAccessFlags &src_access_scope,
3659 QueueId scope_queue, ResourceUsageTag scope_tag) const {
John Zulaufb7578302022-05-19 13:50:18 -06003660 // The scope logic for events is, if we're asking, the resource usage was flagged as "in the first execution scope" at
3661 // the time of the SetEvent, thus all we need check is whether the access is the same one (i.e. before the scope tag
3662 // in order to know if it's in the excecution scope
John Zulaufe0757ba2022-06-10 16:51:45 -06003663 return (write_tag < scope_tag) && WriteInQueueSourceScopeOrChain(scope_queue, src_exec_scope, src_access_scope);
John Zulaufb7578302022-05-19 13:50:18 -06003664}
3665
John Zulaufec943ec2022-06-29 07:52:56 -06003666bool ResourceAccessState::WriteInChainedScope(VkPipelineStageFlags2KHR src_exec_scope,
3667 const SyncStageAccessFlags &src_access_scope) const {
3668 return WriteInChain(src_exec_scope) && WriteBarrierInScope(src_access_scope);
3669}
3670
John Zulaufcb7e1672022-05-04 13:46:08 -06003671bool ResourceAccessState::IsRAWHazard(VkPipelineStageFlags2KHR usage_stage, const SyncStageAccessFlags &usage) const {
John Zulauf4285ee92020-09-23 10:20:52 -06003672 assert(IsRead(usage));
3673 // Only RAW vs. last_write if it doesn't happen-after any other read because either:
3674 // * the previous reads are not hazards, and thus last_write must be visible and available to
3675 // any reads that happen after.
3676 // * the previous reads *are* hazards to last_write, have been reported, and if that hazard is fixed
3677 // the current read will be also not be a hazard, thus reporting a hazard here adds no needed information.
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003678 return last_write.any() && (0 == (read_execution_barriers & usage_stage)) && IsWriteHazard(usage);
John Zulauf4285ee92020-09-23 10:20:52 -06003679}
3680
John Zulaufec943ec2022-06-29 07:52:56 -06003681VkPipelineStageFlags2 ResourceAccessState::GetOrderedStages(QueueId queue_id, const OrderingBarrier &ordering) const {
3682 // At apply queue submission order limits on the effect of ordering
3683 VkPipelineStageFlags2 non_qso_stages = VK_PIPELINE_STAGE_2_NONE;
3684 if (queue_id != QueueSyncState::kQueueIdInvalid) {
3685 for (const auto &read_access : last_reads) {
3686 if (read_access.queue != queue_id) {
3687 non_qso_stages |= read_access.stage;
3688 }
3689 }
3690 }
John Zulauf4285ee92020-09-23 10:20:52 -06003691 // Whether the stage are in the ordering scope only matters if the current write is ordered
John Zulaufec943ec2022-06-29 07:52:56 -06003692 const VkPipelineStageFlags2 read_stages_in_qso = last_read_stages & ~non_qso_stages;
3693 VkPipelineStageFlags2 ordered_stages = read_stages_in_qso & ordering.exec_scope;
John Zulauf4285ee92020-09-23 10:20:52 -06003694 // Special input attachment handling as always (not encoded in exec_scop)
Jeremy Gebbend0de1f82020-11-09 08:21:07 -07003695 const bool input_attachment_ordering = (ordering.access_scope & SYNC_FRAGMENT_SHADER_INPUT_ATTACHMENT_READ_BIT).any();
John Zulauff51fbb62020-10-02 14:43:24 -06003696 if (input_attachment_ordering && input_attachment_read) {
John Zulauf4285ee92020-09-23 10:20:52 -06003697 // If we have an input attachment in last_reads and input attachments are ordered we all that stage
Jeremy Gebben40a22942020-12-22 14:22:06 -07003698 ordered_stages |= VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT_KHR;
John Zulauf4285ee92020-09-23 10:20:52 -06003699 }
3700
3701 return ordered_stages;
3702}
3703
John Zulauf14940722021-04-12 15:19:02 -06003704void ResourceAccessState::UpdateFirst(const ResourceUsageTag tag, SyncStageAccessIndex usage_index, SyncOrdering ordering_rule) {
John Zulauffaea0ee2021-01-14 14:01:32 -07003705 // Only record until we record a write.
3706 if (first_accesses_.empty() || IsRead(first_accesses_.back().usage_index)) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07003707 const VkPipelineStageFlags2KHR usage_stage = IsRead(usage_index) ? PipelineStageBit(usage_index) : 0U;
John Zulauffaea0ee2021-01-14 14:01:32 -07003708 if (0 == (usage_stage & first_read_stages_)) {
3709 // If this is a read we haven't seen or a write, record.
John Zulauf4fa68462021-04-26 21:04:22 -06003710 // We always need to know what stages were found prior to write
John Zulauffaea0ee2021-01-14 14:01:32 -07003711 first_read_stages_ |= usage_stage;
John Zulauf4fa68462021-04-26 21:04:22 -06003712 if (0 == (read_execution_barriers & usage_stage)) {
3713 // If this stage isn't masked then we add it (since writes map to usage_stage 0, this also records writes)
3714 first_accesses_.emplace_back(tag, usage_index, ordering_rule);
3715 }
John Zulauffaea0ee2021-01-14 14:01:32 -07003716 }
3717 }
3718}
3719
John Zulauf4fa68462021-04-26 21:04:22 -06003720void ResourceAccessState::TouchupFirstForLayoutTransition(ResourceUsageTag tag, const OrderingBarrier &layout_ordering) {
3721 // Only call this after recording an image layout transition
3722 assert(first_accesses_.size());
3723 if (first_accesses_.back().tag == tag) {
3724 // If this layout transition is the the first write, add the additional ordering rules that guard the ILT
Samuel Iglesias Gonsálvez9b4660b2021-10-21 08:50:39 +02003725 assert(first_accesses_.back().usage_index == SyncStageAccessIndex::SYNC_IMAGE_LAYOUT_TRANSITION);
John Zulauf4fa68462021-04-26 21:04:22 -06003726 first_write_layout_ordering_ = layout_ordering;
3727 }
3728}
3729
John Zulauf1d5f9c12022-05-13 14:51:08 -06003730ResourceAccessState::ReadState::ReadState(VkPipelineStageFlags2KHR stage_, SyncStageAccessFlags access_,
3731 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_)
3732 : stage(stage_),
3733 access(access_),
3734 barriers(barriers_),
3735 sync_stages(VK_PIPELINE_STAGE_2_NONE),
3736 tag(tag_),
3737 queue(QueueSyncState::kQueueIdInvalid),
3738 pending_dep_chain(VK_PIPELINE_STAGE_2_NONE) {}
3739
John Zulaufee984022022-04-13 16:39:50 -06003740void ResourceAccessState::ReadState::Set(VkPipelineStageFlags2KHR stage_, const SyncStageAccessFlags &access_,
3741 VkPipelineStageFlags2KHR barriers_, ResourceUsageTag tag_) {
3742 stage = stage_;
3743 access = access_;
3744 barriers = barriers_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003745 sync_stages = VK_PIPELINE_STAGE_2_NONE;
John Zulaufee984022022-04-13 16:39:50 -06003746 tag = tag_;
John Zulauf1d5f9c12022-05-13 14:51:08 -06003747 pending_dep_chain = VK_PIPELINE_STAGE_2_NONE; // If this is a new read, we aren't applying a barrier set.
John Zulaufee984022022-04-13 16:39:50 -06003748}
3749
John Zulauf00119522022-05-23 19:07:42 -06003750// Scope test including "queue submission order" effects. Specifically, accesses from a different queue are not
3751// considered to be in "queue submission order" with barriers, events, or semaphore signalling, but any barriers
3752// that have bee applied (via semaphore) to those accesses can be chained off of.
3753bool ResourceAccessState::ReadState::ReadInQueueScopeOrChain(QueueId scope_queue, VkPipelineStageFlags2 exec_scope) const {
3754 VkPipelineStageFlags2 effective_stages = barriers | ((scope_queue == queue) ? stage : VK_PIPELINE_STAGE_2_NONE);
3755 return (exec_scope & effective_stages) != 0;
3756}
3757
John Zulauf697c0e12022-04-19 16:31:12 -06003758ResourceUsageRange SyncValidator::ReserveGlobalTagRange(size_t tag_count) const {
3759 ResourceUsageRange reserve;
3760 reserve.begin = tag_limit_.fetch_add(tag_count);
3761 reserve.end = reserve.begin + tag_count;
3762 return reserve;
3763}
3764
John Zulaufbbda4572022-04-19 16:20:45 -06003765const QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) const {
3766 return GetMappedPlainFromShared(queue_sync_states_, queue);
3767}
3768
3769QueueSyncState *SyncValidator::GetQueueSyncState(VkQueue queue) { return GetMappedPlainFromShared(queue_sync_states_, queue); }
3770
3771std::shared_ptr<const QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) const {
3772 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3773}
3774
3775std::shared_ptr<QueueSyncState> SyncValidator::GetQueueSyncStateShared(VkQueue queue) {
3776 return GetMapped(queue_sync_states_, queue, []() { return std::shared_ptr<QueueSyncState>(); });
3777}
3778
John Zulaufe0757ba2022-06-10 16:51:45 -06003779template <typename T>
3780struct GetBatchTraits {};
3781template <>
3782struct GetBatchTraits<std::shared_ptr<QueueSyncState>> {
3783 using Batch = std::shared_ptr<QueueBatchContext>;
3784 static Batch Get(const std::shared_ptr<QueueSyncState> &qss) { return qss ? qss->LastBatch() : Batch(); }
3785};
3786
3787template <>
3788struct GetBatchTraits<std::shared_ptr<SignaledSemaphores::Signal>> {
3789 using Batch = std::shared_ptr<QueueBatchContext>;
3790 static Batch Get(const std::shared_ptr<SignaledSemaphores::Signal> &sig) { return sig ? sig->batch : Batch(); }
3791};
3792
3793template <typename BatchSet, typename Map, typename Predicate>
3794static BatchSet GetQueueBatchSnapshotImpl(const Map &map, Predicate &&pred) {
John Zulauf1d5f9c12022-05-13 14:51:08 -06003795 BatchSet snapshot;
John Zulaufe0757ba2022-06-10 16:51:45 -06003796 for (auto &entry : map) {
3797 // Intentional copy
3798 auto batch = GetBatchTraits<typename Map::mapped_type>::Get(entry.second);
John Zulauf1d5f9c12022-05-13 14:51:08 -06003799 if (batch && pred(batch)) snapshot.emplace(std::move(batch));
John Zulauf697c0e12022-04-19 16:31:12 -06003800 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06003801 return snapshot;
3802}
3803
3804template <typename Predicate>
3805QueueBatchContext::ConstBatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06003806 return GetQueueBatchSnapshotImpl<QueueBatchContext::ConstBatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
John Zulauf1d5f9c12022-05-13 14:51:08 -06003807}
3808
3809template <typename Predicate>
3810QueueBatchContext::BatchSet SyncValidator::GetQueueLastBatchSnapshot(Predicate &&pred) {
John Zulaufe0757ba2022-06-10 16:51:45 -06003811 return GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(queue_sync_states_, std::forward<Predicate>(pred));
3812}
3813
3814QueueBatchContext::BatchSet SyncValidator::GetQueueBatchSnapshot() {
3815 QueueBatchContext::BatchSet snapshot = GetQueueLastBatchSnapshot();
3816 auto append = [&snapshot](const std::shared_ptr<QueueBatchContext> batch) {
3817 if (batch && !layer_data::Contains(snapshot, batch)) {
3818 snapshot.emplace(batch);
3819 }
3820 return false;
3821 };
3822 GetQueueBatchSnapshotImpl<QueueBatchContext::BatchSet>(signaled_semaphores_, append);
3823 return snapshot;
John Zulauf697c0e12022-04-19 16:31:12 -06003824}
3825
John Zulaufcb7e1672022-05-04 13:46:08 -06003826bool SignaledSemaphores::SignalSemaphore(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state,
3827 const std::shared_ptr<QueueBatchContext> &batch,
3828 const VkSemaphoreSubmitInfo &signal_info) {
John Zulaufecf4ac52022-06-06 10:08:42 -06003829 assert(batch);
John Zulaufcb7e1672022-05-04 13:46:08 -06003830 const SyncExecScope exec_scope =
3831 SyncExecScope::MakeSrc(batch->GetQueueFlags(), signal_info.stageMask, VK_PIPELINE_STAGE_2_HOST_BIT);
3832 const VkSemaphore sem = sem_state->semaphore();
3833 auto signal_it = signaled_.find(sem);
3834 std::shared_ptr<Signal> insert_signal;
3835 if (signal_it == signaled_.end()) {
3836 if (prev_) {
3837 auto prev_sig = GetMapped(prev_->signaled_, sem_state->semaphore(), []() { return std::shared_ptr<Signal>(); });
3838 if (prev_sig) {
3839 // The is an invalid signal, as this semaphore is already signaled... copy the prev state (as prev_ is const)
3840 insert_signal = std::make_shared<Signal>(*prev_sig);
3841 }
3842 }
3843 auto insert_pair = signaled_.emplace(sem, std::move(insert_signal));
3844 signal_it = insert_pair.first;
John Zulauf697c0e12022-04-19 16:31:12 -06003845 }
John Zulaufcb7e1672022-05-04 13:46:08 -06003846
3847 bool success = false;
3848 if (!signal_it->second) {
3849 signal_it->second = std::make_shared<Signal>(sem_state, batch, exec_scope);
3850 success = true;
3851 }
3852
3853 return success;
3854}
3855
John Zulaufecf4ac52022-06-06 10:08:42 -06003856std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::Unsignal(VkSemaphore sem) {
3857 std::shared_ptr<const Signal> unsignaled;
John Zulaufcb7e1672022-05-04 13:46:08 -06003858 const auto found_it = signaled_.find(sem);
3859 if (found_it != signaled_.end()) {
3860 // Move the unsignaled singal out from the signaled list, but keep the shared_ptr as the caller needs the contents for
3861 // a bit.
3862 unsignaled = std::move(found_it->second);
3863 if (!prev_) {
3864 // No parent, not need to keep the entry
3865 // IFF (prev_) leave the entry in the leaf table as we use it to export unsignal to prev_ during record phase
3866 signaled_.erase(found_it);
3867 }
3868 } else if (prev_) {
3869 // We can't unsignal prev_ because it's const * by design.
3870 // We put in an empty placeholder
3871 signaled_.emplace(sem, std::shared_ptr<Signal>());
3872 unsignaled = GetPrev(sem);
3873 }
3874 // NOTE: No else clause. Because if we didn't find it, and there's no previous, this indicates an error,
3875 // but CoreChecks should have reported it
3876
3877 // If unsignaled is null, there was a missing pending semaphore, and that's also issue CoreChecks reports
John Zulauf697c0e12022-04-19 16:31:12 -06003878 return unsignaled;
3879}
3880
John Zulaufcb7e1672022-05-04 13:46:08 -06003881void SignaledSemaphores::Import(VkSemaphore sem, std::shared_ptr<Signal> &&from) {
3882 // Overwrite the s tate with the last state from this
3883 if (from) {
3884 assert(sem == from->sem_state->semaphore());
3885 signaled_[sem] = std::move(from);
3886 } else {
3887 signaled_.erase(sem);
3888 }
3889}
3890
3891void SignaledSemaphores::Reset() {
3892 signaled_.clear();
3893 prev_ = nullptr;
3894}
3895
John Zulaufea943c52022-02-22 11:05:17 -07003896std::shared_ptr<CommandBufferAccessContext> SyncValidator::AccessContextFactory(VkCommandBuffer command_buffer) {
3897 // If we don't have one, make it.
3898 auto cb_state = Get<CMD_BUFFER_STATE>(command_buffer);
3899 assert(cb_state.get());
3900 auto queue_flags = cb_state->GetQueueFlags();
3901 return std::make_shared<CommandBufferAccessContext>(*this, cb_state, queue_flags);
3902}
3903
John Zulaufcb7e1672022-05-04 13:46:08 -06003904std::shared_ptr<CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) {
John Zulaufea943c52022-02-22 11:05:17 -07003905 return GetMappedInsert(cb_access_state, command_buffer,
3906 [this, command_buffer]() { return AccessContextFactory(command_buffer); });
3907}
3908
3909std::shared_ptr<const CommandBufferAccessContext> SyncValidator::GetAccessContextShared(VkCommandBuffer command_buffer) const {
3910 return GetMapped(cb_access_state, command_buffer, []() { return std::shared_ptr<CommandBufferAccessContext>(); });
3911}
3912
3913const CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) const {
3914 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3915}
3916
3917CommandBufferAccessContext *SyncValidator::GetAccessContext(VkCommandBuffer command_buffer) {
3918 return GetAccessContextShared(command_buffer).get();
3919}
3920
3921CommandBufferAccessContext *SyncValidator::GetAccessContextNoInsert(VkCommandBuffer command_buffer) {
3922 return GetMappedPlainFromShared(cb_access_state, command_buffer);
3923}
3924
John Zulaufd1f85d42020-04-15 12:23:15 -06003925void SyncValidator::ResetCommandBufferCallback(VkCommandBuffer command_buffer) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003926 auto *access_context = GetAccessContextNoInsert(command_buffer);
3927 if (access_context) {
3928 access_context->Reset();
John Zulauf9cb530d2019-09-30 14:14:10 -06003929 }
3930}
3931
John Zulaufd1f85d42020-04-15 12:23:15 -06003932void SyncValidator::FreeCommandBufferCallback(VkCommandBuffer command_buffer) {
3933 auto access_found = cb_access_state.find(command_buffer);
3934 if (access_found != cb_access_state.end()) {
3935 access_found->second->Reset();
John Zulauf4fa68462021-04-26 21:04:22 -06003936 access_found->second->MarkDestroyed();
John Zulaufd1f85d42020-04-15 12:23:15 -06003937 cb_access_state.erase(access_found);
3938 }
3939}
3940
John Zulauf9cb530d2019-09-30 14:14:10 -06003941bool SyncValidator::PreCallValidateCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3942 uint32_t regionCount, const VkBufferCopy *pRegions) const {
3943 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06003944 const auto *cb_context = GetAccessContext(commandBuffer);
3945 assert(cb_context);
3946 if (!cb_context) return skip;
3947 const auto *context = cb_context->GetCurrentAccessContext();
John Zulauf9cb530d2019-09-30 14:14:10 -06003948
John Zulauf3d84f1b2020-03-09 13:33:25 -06003949 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003950 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3951 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003952
3953 for (uint32_t region = 0; region < regionCount; region++) {
3954 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003955 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003956 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003957 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003958 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003959 skip |= LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003960 "vkCmdCopyBuffer: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003961 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003962 cb_context->FormatHazard(hazard).c_str());
John Zulauf9cb530d2019-09-30 14:14:10 -06003963 }
John Zulauf9cb530d2019-09-30 14:14:10 -06003964 }
John Zulauf16adfc92020-04-08 10:28:33 -06003965 if (dst_buffer && !skip) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003966 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003967 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003968 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06003969 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06003970 "vkCmdCopyBuffer: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06003971 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06003972 cb_context->FormatHazard(hazard).c_str());
John Zulauf3d84f1b2020-03-09 13:33:25 -06003973 }
3974 }
3975 if (skip) break;
John Zulauf9cb530d2019-09-30 14:14:10 -06003976 }
3977 return skip;
3978}
3979
3980void SyncValidator::PreCallRecordCmdCopyBuffer(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkBuffer dstBuffer,
3981 uint32_t regionCount, const VkBufferCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06003982 auto *cb_context = GetAccessContext(commandBuffer);
3983 assert(cb_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06003984 const auto tag = cb_context->NextCommandTag(CMD_COPYBUFFER);
John Zulauf3d84f1b2020-03-09 13:33:25 -06003985 auto *context = cb_context->GetCurrentAccessContext();
3986
Jeremy Gebbenf4449392022-01-28 10:09:10 -07003987 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
3988 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
John Zulauf9cb530d2019-09-30 14:14:10 -06003989
3990 for (uint32_t region = 0; region < regionCount; region++) {
3991 const auto &copy_region = pRegions[region];
John Zulauf16adfc92020-04-08 10:28:33 -06003992 if (src_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003993 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003994 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06003995 }
John Zulauf16adfc92020-04-08 10:28:33 -06003996 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06003997 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07003998 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07003999 }
4000 }
4001}
4002
John Zulauf4a6105a2020-11-17 15:11:05 -07004003void SyncValidator::PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) {
4004 // Clear out events from the command buffer contexts
4005 for (auto &cb_context : cb_access_state) {
4006 cb_context.second->RecordDestroyEvent(event);
4007 }
4008}
4009
Tony-LunarGef035472021-11-02 10:23:33 -06004010bool SyncValidator::ValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos,
4011 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004012 bool skip = false;
4013 const auto *cb_context = GetAccessContext(commandBuffer);
4014 assert(cb_context);
4015 if (!cb_context) return skip;
4016 const auto *context = cb_context->GetCurrentAccessContext();
4017
4018 // If we have no previous accesses, we have no hazards
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004019 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4020 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004021
4022 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4023 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4024 if (src_buffer) {
4025 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004026 auto hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004027 if (hazard.hazard) {
4028 // TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004029 skip |=
4030 LogError(pCopyBufferInfos->srcBuffer, string_SyncHazardVUID(hazard.hazard),
4031 "%s(): Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4032 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->srcBuffer).c_str(),
4033 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004034 }
4035 }
4036 if (dst_buffer && !skip) {
4037 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004038 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
Jeff Leger178b1e52020-10-05 12:22:23 -04004039 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004040 skip |=
4041 LogError(pCopyBufferInfos->dstBuffer, string_SyncHazardVUID(hazard.hazard),
4042 "%s(): Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4043 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyBufferInfos->dstBuffer).c_str(),
4044 region, cb_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004045 }
4046 }
4047 if (skip) break;
4048 }
4049 return skip;
4050}
4051
Tony-LunarGef035472021-11-02 10:23:33 -06004052bool SyncValidator::PreCallValidateCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer,
4053 const VkCopyBufferInfo2KHR *pCopyBufferInfos) const {
4054 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4055}
4056
4057bool SyncValidator::PreCallValidateCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) const {
4058 return ValidateCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4059}
4060
4061void SyncValidator::RecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004062 auto *cb_context = GetAccessContext(commandBuffer);
4063 assert(cb_context);
Tony-LunarGef035472021-11-02 10:23:33 -06004064 const auto tag = cb_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004065 auto *context = cb_context->GetCurrentAccessContext();
4066
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004067 auto src_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->srcBuffer);
4068 auto dst_buffer = Get<BUFFER_STATE>(pCopyBufferInfos->dstBuffer);
Jeff Leger178b1e52020-10-05 12:22:23 -04004069
4070 for (uint32_t region = 0; region < pCopyBufferInfos->regionCount; region++) {
4071 const auto &copy_region = pCopyBufferInfos->pRegions[region];
4072 if (src_buffer) {
4073 const ResourceAccessRange src_range = MakeRange(*src_buffer, copy_region.srcOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004074 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004075 }
4076 if (dst_buffer) {
4077 const ResourceAccessRange dst_range = MakeRange(*dst_buffer, copy_region.dstOffset, copy_region.size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07004078 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004079 }
4080 }
4081}
4082
Tony-LunarGef035472021-11-02 10:23:33 -06004083void SyncValidator::PreCallRecordCmdCopyBuffer2KHR(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2KHR *pCopyBufferInfos) {
4084 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2KHR);
4085}
4086
4087void SyncValidator::PreCallRecordCmdCopyBuffer2(VkCommandBuffer commandBuffer, const VkCopyBufferInfo2 *pCopyBufferInfos) {
4088 RecordCmdCopyBuffer2(commandBuffer, pCopyBufferInfos, CMD_COPYBUFFER2);
4089}
4090
John Zulauf5c5e88d2019-12-26 11:22:02 -07004091bool SyncValidator::PreCallValidateCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4092 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4093 const VkImageCopy *pRegions) const {
4094 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004095 const auto *cb_access_context = GetAccessContext(commandBuffer);
4096 assert(cb_access_context);
4097 if (!cb_access_context) return skip;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004098
John Zulauf3d84f1b2020-03-09 13:33:25 -06004099 const auto *context = cb_access_context->GetCurrentAccessContext();
4100 assert(context);
4101 if (!context) return skip;
4102
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004103 auto src_image = Get<IMAGE_STATE>(srcImage);
4104 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004105 for (uint32_t region = 0; region < regionCount; region++) {
4106 const auto &copy_region = pRegions[region];
4107 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004108 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004109 copy_region.srcOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004110 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004111 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004112 "vkCmdCopyImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004113 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004114 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004115 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004116 }
4117
4118 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004119 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004120 copy_region.dstOffset, copy_region.extent, false);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004121 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004122 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06004123 "vkCmdCopyImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06004124 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004125 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf5c5e88d2019-12-26 11:22:02 -07004126 }
locke-lunarg1dbbb9e2020-02-28 22:43:53 -07004127 if (skip) break;
John Zulauf5c5e88d2019-12-26 11:22:02 -07004128 }
4129 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004130
John Zulauf5c5e88d2019-12-26 11:22:02 -07004131 return skip;
4132}
4133
4134void SyncValidator::PreCallRecordCmdCopyImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4135 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4136 const VkImageCopy *pRegions) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004137 auto *cb_access_context = GetAccessContext(commandBuffer);
4138 assert(cb_access_context);
John Zulauf2b151bf2020-04-24 15:37:44 -06004139 const auto tag = cb_access_context->NextCommandTag(CMD_COPYIMAGE);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004140 auto *context = cb_access_context->GetCurrentAccessContext();
4141 assert(context);
4142
Jeremy Gebben9f537102021-10-05 16:37:12 -06004143 auto src_image = Get<IMAGE_STATE>(srcImage);
4144 auto dst_image = Get<IMAGE_STATE>(dstImage);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004145
4146 for (uint32_t region = 0; region < regionCount; region++) {
4147 const auto &copy_region = pRegions[region];
John Zulauf3d84f1b2020-03-09 13:33:25 -06004148 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004149 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004150 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
John Zulauf5c5e88d2019-12-26 11:22:02 -07004151 }
John Zulauf3d84f1b2020-03-09 13:33:25 -06004152 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004153 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004154 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
John Zulauf9cb530d2019-09-30 14:14:10 -06004155 }
4156 }
4157}
4158
Tony-LunarGb61514a2021-11-02 12:36:51 -06004159bool SyncValidator::ValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo,
4160 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04004161 bool skip = false;
4162 const auto *cb_access_context = GetAccessContext(commandBuffer);
4163 assert(cb_access_context);
4164 if (!cb_access_context) return skip;
4165
4166 const auto *context = cb_access_context->GetCurrentAccessContext();
4167 assert(context);
4168 if (!context) return skip;
4169
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004170 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4171 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004172
Jeff Leger178b1e52020-10-05 12:22:23 -04004173 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4174 const auto &copy_region = pCopyImageInfo->pRegions[region];
4175 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004176 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004177 copy_region.srcOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004178 if (hazard.hazard) {
4179 skip |= LogError(pCopyImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004180 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004181 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004182 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004183 }
4184 }
4185
4186 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004187 auto hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004188 copy_region.dstOffset, copy_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04004189 if (hazard.hazard) {
4190 skip |= LogError(pCopyImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004191 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04004192 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pCopyImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004193 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04004194 }
4195 if (skip) break;
4196 }
4197 }
4198
4199 return skip;
4200}
4201
Tony-LunarGb61514a2021-11-02 12:36:51 -06004202bool SyncValidator::PreCallValidateCmdCopyImage2KHR(VkCommandBuffer commandBuffer,
4203 const VkCopyImageInfo2KHR *pCopyImageInfo) const {
4204 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4205}
4206
4207bool SyncValidator::PreCallValidateCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) const {
4208 return ValidateCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4209}
4210
4211void SyncValidator::RecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo, CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04004212 auto *cb_access_context = GetAccessContext(commandBuffer);
4213 assert(cb_access_context);
Tony-LunarGb61514a2021-11-02 12:36:51 -06004214 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04004215 auto *context = cb_access_context->GetCurrentAccessContext();
4216 assert(context);
4217
Jeremy Gebben9f537102021-10-05 16:37:12 -06004218 auto src_image = Get<IMAGE_STATE>(pCopyImageInfo->srcImage);
4219 auto dst_image = Get<IMAGE_STATE>(pCopyImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04004220
4221 for (uint32_t region = 0; region < pCopyImageInfo->regionCount; region++) {
4222 const auto &copy_region = pCopyImageInfo->pRegions[region];
4223 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004224 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004225 copy_region.srcSubresource, copy_region.srcOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004226 }
4227 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004228 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
ziga-lunarg73746512022-03-23 23:08:17 +01004229 copy_region.dstSubresource, copy_region.dstOffset, copy_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04004230 }
4231 }
4232}
4233
Tony-LunarGb61514a2021-11-02 12:36:51 -06004234void SyncValidator::PreCallRecordCmdCopyImage2KHR(VkCommandBuffer commandBuffer, const VkCopyImageInfo2KHR *pCopyImageInfo) {
4235 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2KHR);
4236}
4237
4238void SyncValidator::PreCallRecordCmdCopyImage2(VkCommandBuffer commandBuffer, const VkCopyImageInfo2 *pCopyImageInfo) {
4239 RecordCmdCopyImage2(commandBuffer, pCopyImageInfo, CMD_COPYIMAGE2);
4240}
4241
John Zulauf9cb530d2019-09-30 14:14:10 -06004242bool SyncValidator::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4243 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4244 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4245 uint32_t bufferMemoryBarrierCount,
4246 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4247 uint32_t imageMemoryBarrierCount,
4248 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
4249 bool skip = false;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004250 const auto *cb_access_context = GetAccessContext(commandBuffer);
4251 assert(cb_access_context);
4252 if (!cb_access_context) return skip;
John Zulauf0cb5be22020-01-23 12:18:22 -07004253
John Zulauf36ef9282021-02-02 11:47:24 -07004254 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(), srcStageMask,
4255 dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers,
4256 bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
4257 pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07004258 skip = pipeline_barrier.Validate(*cb_access_context);
John Zulauf9cb530d2019-09-30 14:14:10 -06004259 return skip;
4260}
4261
4262void SyncValidator::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask,
4263 VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags,
4264 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
4265 uint32_t bufferMemoryBarrierCount,
4266 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
4267 uint32_t imageMemoryBarrierCount,
4268 const VkImageMemoryBarrier *pImageMemoryBarriers) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004269 auto *cb_access_context = GetAccessContext(commandBuffer);
4270 assert(cb_access_context);
4271 if (!cb_access_context) return;
John Zulauf9cb530d2019-09-30 14:14:10 -06004272
John Zulauf1bf30522021-09-03 15:39:06 -06004273 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER, *this, cb_access_context->GetQueueFlags(),
4274 srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
4275 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
4276 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf9cb530d2019-09-30 14:14:10 -06004277}
4278
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004279bool SyncValidator::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer,
4280 const VkDependencyInfoKHR *pDependencyInfo) const {
4281 bool skip = false;
4282 const auto *cb_access_context = GetAccessContext(commandBuffer);
4283 assert(cb_access_context);
4284 if (!cb_access_context) return skip;
4285
4286 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4287 skip = pipeline_barrier.Validate(*cb_access_context);
4288 return skip;
4289}
4290
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004291bool SyncValidator::PreCallValidateCmdPipelineBarrier2(VkCommandBuffer commandBuffer,
4292 const VkDependencyInfo *pDependencyInfo) const {
4293 bool skip = false;
4294 const auto *cb_access_context = GetAccessContext(commandBuffer);
4295 assert(cb_access_context);
4296 if (!cb_access_context) return skip;
4297
4298 SyncOpPipelineBarrier pipeline_barrier(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(), *pDependencyInfo);
4299 skip = pipeline_barrier.Validate(*cb_access_context);
4300 return skip;
4301}
4302
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004303void SyncValidator::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) {
4304 auto *cb_access_context = GetAccessContext(commandBuffer);
4305 assert(cb_access_context);
4306 if (!cb_access_context) return;
4307
John Zulauf1bf30522021-09-03 15:39:06 -06004308 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2KHR, *this, cb_access_context->GetQueueFlags(),
4309 *pDependencyInfo);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07004310}
4311
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07004312void SyncValidator::PreCallRecordCmdPipelineBarrier2(VkCommandBuffer commandBuffer, const VkDependencyInfo *pDependencyInfo) {
4313 auto *cb_access_context = GetAccessContext(commandBuffer);
4314 assert(cb_access_context);
4315 if (!cb_access_context) return;
4316
4317 cb_access_context->RecordSyncOp<SyncOpPipelineBarrier>(CMD_PIPELINEBARRIER2, *this, cb_access_context->GetQueueFlags(),
4318 *pDependencyInfo);
4319}
4320
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004321void SyncValidator::CreateDevice(const VkDeviceCreateInfo *pCreateInfo) {
John Zulauf9cb530d2019-09-30 14:14:10 -06004322 // The state tracker sets up the device state
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004323 StateTracker::CreateDevice(pCreateInfo);
John Zulauf9cb530d2019-09-30 14:14:10 -06004324
John Zulauf5f13a792020-03-10 07:31:21 -06004325 // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker
4326 // refactor would be messier without.
John Zulauf9cb530d2019-09-30 14:14:10 -06004327 // TODO: Find a good way to do this hooklessly.
Jeremy Gebben36a3b832022-03-23 10:54:18 -06004328 SetCommandBufferResetCallback([this](VkCommandBuffer command_buffer) -> void { ResetCommandBufferCallback(command_buffer); });
4329 SetCommandBufferFreeCallback([this](VkCommandBuffer command_buffer) -> void { FreeCommandBufferCallback(command_buffer); });
John Zulaufbbda4572022-04-19 16:20:45 -06004330
John Zulauf1d5f9c12022-05-13 14:51:08 -06004331 QueueId queue_id = QueueSyncState::kQueueIdBase;
4332 ForEachShared<QUEUE_STATE>([this, &queue_id](const std::shared_ptr<QUEUE_STATE> &queue_state) {
John Zulaufbbda4572022-04-19 16:20:45 -06004333 auto queue_flags = physical_device_state->queue_family_properties[queue_state->queueFamilyIndex].queueFlags;
John Zulauf1d5f9c12022-05-13 14:51:08 -06004334 std::shared_ptr<QueueSyncState> queue_sync_state = std::make_shared<QueueSyncState>(queue_state, queue_flags, queue_id++);
John Zulaufbbda4572022-04-19 16:20:45 -06004335 queue_sync_states_.emplace(std::make_pair(queue_state->Queue(), std::move(queue_sync_state)));
4336 });
John Zulauf9cb530d2019-09-30 14:14:10 -06004337}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004338
John Zulauf355e49b2020-04-24 15:11:15 -06004339bool SyncValidator::ValidateBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004340 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004341 bool skip = false;
John Zulauf355e49b2020-04-24 15:11:15 -06004342 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004343 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004344 SyncOpBeginRenderPass sync_op(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004345 skip = sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004346 }
John Zulauf355e49b2020-04-24 15:11:15 -06004347 return skip;
4348}
4349
4350bool SyncValidator::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4351 VkSubpassContents contents) const {
4352 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004353 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004354 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004355 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004356 return skip;
4357}
4358
4359bool SyncValidator::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004360 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004361 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004362 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004363 return skip;
4364}
4365
4366bool SyncValidator::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4367 const VkRenderPassBeginInfo *pRenderPassBegin,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004368 const VkSubpassBeginInfo *pSubpassBeginInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004369 bool skip = StateTracker::PreCallValidateCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004370 skip |= ValidateBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004371 return skip;
4372}
4373
John Zulauf3d84f1b2020-03-09 13:33:25 -06004374void SyncValidator::PostCallRecordBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo,
4375 VkResult result) {
4376 // The state tracker sets up the command buffer state
4377 StateTracker::PostCallRecordBeginCommandBuffer(commandBuffer, pBeginInfo, result);
4378
4379 // Create/initialize the structure that trackers accesses at the command buffer scope.
4380 auto cb_access_context = GetAccessContext(commandBuffer);
4381 assert(cb_access_context);
4382 cb_access_context->Reset();
4383}
4384
4385void SyncValidator::RecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
sjfricke0bea06e2022-06-05 09:22:26 +09004386 const VkSubpassBeginInfo *pSubpassBeginInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004387 auto cb_context = GetAccessContext(commandBuffer);
John Zulauf355e49b2020-04-24 15:11:15 -06004388 if (cb_context) {
sjfricke0bea06e2022-06-05 09:22:26 +09004389 cb_context->RecordSyncOp<SyncOpBeginRenderPass>(cmd_type, *this, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004390 }
4391}
4392
4393void SyncValidator::PostCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4394 VkSubpassContents contents) {
4395 StateTracker::PostCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004396 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004397 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004398 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, &subpass_begin_info, CMD_BEGINRENDERPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004399}
4400
4401void SyncValidator::PostCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin,
4402 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4403 StateTracker::PostCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004404 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004405}
4406
4407void SyncValidator::PostCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer,
4408 const VkRenderPassBeginInfo *pRenderPassBegin,
4409 const VkSubpassBeginInfo *pSubpassBeginInfo) {
4410 StateTracker::PostCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004411 RecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, pSubpassBeginInfo, CMD_BEGINRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004412}
4413
Mike Schuchardt2df08912020-12-15 16:28:09 -08004414bool SyncValidator::ValidateCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004415 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004416 bool skip = false;
4417
4418 auto cb_context = GetAccessContext(commandBuffer);
4419 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004420 if (!cb_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09004421 SyncOpNextSubpass sync_op(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004422 return sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004423}
4424
4425bool SyncValidator::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const {
4426 bool skip = StateTracker::PreCallValidateCmdNextSubpass(commandBuffer, contents);
John Zulauf64ffe552021-02-06 10:25:07 -07004427 // Convert to a NextSubpass2
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004428 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf355e49b2020-04-24 15:11:15 -06004429 subpass_begin_info.contents = contents;
John Zulauf64ffe552021-02-06 10:25:07 -07004430 auto subpass_end_info = LvlInitStruct<VkSubpassEndInfo>();
4431 skip |= ValidateCmdNextSubpass(commandBuffer, &subpass_begin_info, &subpass_end_info, CMD_NEXTSUBPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004432 return skip;
4433}
4434
Mike Schuchardt2df08912020-12-15 16:28:09 -08004435bool SyncValidator::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4436 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004437 bool skip = StateTracker::PreCallValidateCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004438 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004439 return skip;
4440}
4441
4442bool SyncValidator::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4443 const VkSubpassEndInfo *pSubpassEndInfo) const {
4444 bool skip = StateTracker::PreCallValidateCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004445 skip |= ValidateCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004446 return skip;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004447}
4448
4449void SyncValidator::RecordCmdNextSubpass(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004450 const VkSubpassEndInfo *pSubpassEndInfo, CMD_TYPE cmd_type) {
John Zulauf3d84f1b2020-03-09 13:33:25 -06004451 auto cb_context = GetAccessContext(commandBuffer);
4452 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004453 if (!cb_context) return;
John Zulauf3d84f1b2020-03-09 13:33:25 -06004454
sjfricke0bea06e2022-06-05 09:22:26 +09004455 cb_context->RecordSyncOp<SyncOpNextSubpass>(cmd_type, *this, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004456}
4457
4458void SyncValidator::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) {
4459 StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents);
Mark Lobodzinski6fe9e702020-12-30 15:36:39 -07004460 auto subpass_begin_info = LvlInitStruct<VkSubpassBeginInfo>();
John Zulauf3d84f1b2020-03-09 13:33:25 -06004461 subpass_begin_info.contents = contents;
John Zulauf355e49b2020-04-24 15:11:15 -06004462 RecordCmdNextSubpass(commandBuffer, &subpass_begin_info, nullptr, CMD_NEXTSUBPASS);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004463}
4464
4465void SyncValidator::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4466 const VkSubpassEndInfo *pSubpassEndInfo) {
4467 StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
John Zulauf355e49b2020-04-24 15:11:15 -06004468 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004469}
4470
4471void SyncValidator::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo,
4472 const VkSubpassEndInfo *pSubpassEndInfo) {
4473 StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004474 RecordCmdNextSubpass(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo, CMD_NEXTSUBPASS2KHR);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004475}
4476
sfricke-samsung85584a72021-09-30 21:43:38 -07004477bool SyncValidator::ValidateCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
sjfricke0bea06e2022-06-05 09:22:26 +09004478 CMD_TYPE cmd_type) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004479 bool skip = false;
4480
4481 auto cb_context = GetAccessContext(commandBuffer);
4482 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004483 if (!cb_context) return skip;
John Zulauf355e49b2020-04-24 15:11:15 -06004484
sjfricke0bea06e2022-06-05 09:22:26 +09004485 SyncOpEndRenderPass sync_op(cmd_type, *this, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004486 skip |= sync_op.Validate(*cb_context);
John Zulauf355e49b2020-04-24 15:11:15 -06004487 return skip;
4488}
4489
4490bool SyncValidator::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const {
4491 bool skip = StateTracker::PreCallValidateCmdEndRenderPass(commandBuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07004492 skip |= ValidateCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf355e49b2020-04-24 15:11:15 -06004493 return skip;
4494}
4495
Mike Schuchardt2df08912020-12-15 16:28:09 -08004496bool SyncValidator::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004497 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf64ffe552021-02-06 10:25:07 -07004498 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf355e49b2020-04-24 15:11:15 -06004499 return skip;
4500}
4501
4502bool SyncValidator::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer,
Mike Schuchardt2df08912020-12-15 16:28:09 -08004503 const VkSubpassEndInfo *pSubpassEndInfo) const {
John Zulauf355e49b2020-04-24 15:11:15 -06004504 bool skip = StateTracker::PreCallValidateCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
sfricke-samsung85584a72021-09-30 21:43:38 -07004505 skip |= ValidateCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf355e49b2020-04-24 15:11:15 -06004506 return skip;
4507}
4508
sjfricke0bea06e2022-06-05 09:22:26 +09004509void SyncValidator::RecordCmdEndRenderPass(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo,
4510 CMD_TYPE cmd_type) {
John Zulaufe5da6e52020-03-18 15:32:18 -06004511 // Resolve the all subpass contexts to the command buffer contexts
4512 auto cb_context = GetAccessContext(commandBuffer);
4513 assert(cb_context);
John Zulauf64ffe552021-02-06 10:25:07 -07004514 if (!cb_context) return;
John Zulaufe5da6e52020-03-18 15:32:18 -06004515
sjfricke0bea06e2022-06-05 09:22:26 +09004516 cb_context->RecordSyncOp<SyncOpEndRenderPass>(cmd_type, *this, pSubpassEndInfo);
John Zulaufe5da6e52020-03-18 15:32:18 -06004517}
John Zulauf3d84f1b2020-03-09 13:33:25 -06004518
John Zulauf33fc1d52020-07-17 11:01:10 -06004519// Simple heuristic rule to detect WAW operations representing algorithmically safe or increment
4520// updates to a resource which do not conflict at the byte level.
4521// TODO: Revisit this rule to see if it needs to be tighter or looser
4522// TODO: Add programatic control over suppression heuristics
4523bool SyncValidator::SupressedBoundDescriptorWAW(const HazardResult &hazard) const {
4524 return (hazard.hazard == WRITE_AFTER_WRITE) && (FlagBit(hazard.usage_index) == hazard.prior_access);
4525}
4526
John Zulauf3d84f1b2020-03-09 13:33:25 -06004527void SyncValidator::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) {
John Zulauf355e49b2020-04-24 15:11:15 -06004528 RecordCmdEndRenderPass(commandBuffer, nullptr, CMD_ENDRENDERPASS);
John Zulauf5a1a5382020-06-22 17:23:25 -06004529 StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004530}
4531
4532void SyncValidator::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
John Zulauf355e49b2020-04-24 15:11:15 -06004533 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2);
John Zulauf5a1a5382020-06-22 17:23:25 -06004534 StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004535}
4536
4537void SyncValidator::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) {
sfricke-samsung85584a72021-09-30 21:43:38 -07004538 RecordCmdEndRenderPass(commandBuffer, pSubpassEndInfo, CMD_ENDRENDERPASS2KHR);
John Zulauf5a1a5382020-06-22 17:23:25 -06004539 StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo);
John Zulauf3d84f1b2020-03-09 13:33:25 -06004540}
locke-lunarga19c71d2020-03-02 18:17:04 -07004541
sfricke-samsung71f04e32022-03-16 01:21:21 -05004542template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004543bool SyncValidator::ValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004544 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4545 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004546 bool skip = false;
4547 const auto *cb_access_context = GetAccessContext(commandBuffer);
4548 assert(cb_access_context);
4549 if (!cb_access_context) return skip;
4550
4551 const auto *context = cb_access_context->GetCurrentAccessContext();
4552 assert(context);
4553 if (!context) return skip;
4554
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004555 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4556 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004557
4558 for (uint32_t region = 0; region < regionCount; region++) {
4559 const auto &copy_region = pRegions[region];
John Zulauf477700e2021-01-06 11:41:49 -07004560 HazardResult hazard;
locke-lunarga19c71d2020-03-02 18:17:04 -07004561 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004562 if (src_buffer) {
4563 ResourceAccessRange src_range =
4564 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004565 hazard = context->DetectHazard(*src_buffer, SYNC_COPY_TRANSFER_READ, src_range);
John Zulauf477700e2021-01-06 11:41:49 -07004566 if (hazard.hazard) {
4567 // PHASE1 TODO -- add tag information to log msg when useful.
sjfricke0bea06e2022-06-05 09:22:26 +09004568 skip |=
4569 LogError(srcBuffer, string_SyncHazardVUID(hazard.hazard),
4570 "%s: Hazard %s for srcBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4571 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcBuffer).c_str(), region,
4572 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004573 }
4574 }
4575
Jeremy Gebben40a22942020-12-22 14:22:06 -07004576 hazard = context->DetectHazard(*dst_image, SYNC_COPY_TRANSFER_WRITE, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004577 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004578 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004579 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004580 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004581 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004582 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004583 }
4584 if (skip) break;
4585 }
4586 if (skip) break;
4587 }
4588 return skip;
4589}
4590
Jeff Leger178b1e52020-10-05 12:22:23 -04004591bool SyncValidator::PreCallValidateCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4592 VkImageLayout dstImageLayout, uint32_t regionCount,
4593 const VkBufferImageCopy *pRegions) const {
4594 return ValidateCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions,
Tony Barbour845d29b2021-11-09 11:43:14 -07004595 CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004596}
4597
4598bool SyncValidator::PreCallValidateCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4599 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) const {
4600 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4601 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004602 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4603}
4604
4605bool SyncValidator::PreCallValidateCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4606 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) const {
4607 return ValidateCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4608 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4609 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004610}
4611
sfricke-samsung71f04e32022-03-16 01:21:21 -05004612template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004613void SyncValidator::RecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004614 VkImageLayout dstImageLayout, uint32_t regionCount, const RegionType *pRegions,
4615 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004616 auto *cb_access_context = GetAccessContext(commandBuffer);
4617 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004618
Jeff Leger178b1e52020-10-05 12:22:23 -04004619 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004620 auto *context = cb_access_context->GetCurrentAccessContext();
4621 assert(context);
4622
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004623 auto src_buffer = Get<BUFFER_STATE>(srcBuffer);
4624 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004625
4626 for (uint32_t region = 0; region < regionCount; region++) {
4627 const auto &copy_region = pRegions[region];
locke-lunarga19c71d2020-03-02 18:17:04 -07004628 if (dst_image) {
John Zulauf477700e2021-01-06 11:41:49 -07004629 if (src_buffer) {
4630 ResourceAccessRange src_range =
4631 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, dst_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004632 context->UpdateAccessState(*src_buffer, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment, src_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004633 }
Jeremy Gebben40a22942020-12-22 14:22:06 -07004634 context->UpdateAccessState(*dst_image, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004635 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004636 }
4637 }
4638}
4639
Jeff Leger178b1e52020-10-05 12:22:23 -04004640void SyncValidator::PreCallRecordCmdCopyBufferToImage(VkCommandBuffer commandBuffer, VkBuffer srcBuffer, VkImage dstImage,
4641 VkImageLayout dstImageLayout, uint32_t regionCount,
4642 const VkBufferImageCopy *pRegions) {
4643 StateTracker::PreCallRecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions);
Tony Barbour845d29b2021-11-09 11:43:14 -07004644 RecordCmdCopyBufferToImage(commandBuffer, srcBuffer, dstImage, dstImageLayout, regionCount, pRegions, CMD_COPYBUFFERTOIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004645}
4646
4647void SyncValidator::PreCallRecordCmdCopyBufferToImage2KHR(VkCommandBuffer commandBuffer,
4648 const VkCopyBufferToImageInfo2KHR *pCopyBufferToImageInfo) {
4649 StateTracker::PreCallRecordCmdCopyBufferToImage2KHR(commandBuffer, pCopyBufferToImageInfo);
4650 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4651 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
Tony Barbour845d29b2021-11-09 11:43:14 -07004652 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2KHR);
4653}
4654
4655void SyncValidator::PreCallRecordCmdCopyBufferToImage2(VkCommandBuffer commandBuffer,
4656 const VkCopyBufferToImageInfo2 *pCopyBufferToImageInfo) {
4657 StateTracker::PreCallRecordCmdCopyBufferToImage2(commandBuffer, pCopyBufferToImageInfo);
4658 RecordCmdCopyBufferToImage(commandBuffer, pCopyBufferToImageInfo->srcBuffer, pCopyBufferToImageInfo->dstImage,
4659 pCopyBufferToImageInfo->dstImageLayout, pCopyBufferToImageInfo->regionCount,
4660 pCopyBufferToImageInfo->pRegions, CMD_COPYBUFFERTOIMAGE2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004661}
4662
sfricke-samsung71f04e32022-03-16 01:21:21 -05004663template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004664bool SyncValidator::ValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004665 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
4666 CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004667 bool skip = false;
4668 const auto *cb_access_context = GetAccessContext(commandBuffer);
4669 assert(cb_access_context);
4670 if (!cb_access_context) return skip;
Jeff Leger178b1e52020-10-05 12:22:23 -04004671
locke-lunarga19c71d2020-03-02 18:17:04 -07004672 const auto *context = cb_access_context->GetCurrentAccessContext();
4673 assert(context);
4674 if (!context) return skip;
4675
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004676 auto src_image = Get<IMAGE_STATE>(srcImage);
4677 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004678 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
locke-lunarga19c71d2020-03-02 18:17:04 -07004679 for (uint32_t region = 0; region < regionCount; region++) {
4680 const auto &copy_region = pRegions[region];
4681 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004682 auto hazard = context->DetectHazard(*src_image, SYNC_COPY_TRANSFER_READ, copy_region.imageSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004683 copy_region.imageOffset, copy_region.imageExtent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004684 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004685 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004686 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
John Zulauf1dae9192020-06-16 15:46:44 -06004687 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004688 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004689 }
John Zulauf477700e2021-01-06 11:41:49 -07004690 if (dst_mem) {
4691 ResourceAccessRange dst_range =
4692 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004693 hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, dst_range);
John Zulauf477700e2021-01-06 11:41:49 -07004694 if (hazard.hazard) {
sjfricke0bea06e2022-06-05 09:22:26 +09004695 skip |=
4696 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
4697 "%s: Hazard %s for dstBuffer %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
4698 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(), region,
4699 cb_access_context->FormatHazard(hazard).c_str());
John Zulauf477700e2021-01-06 11:41:49 -07004700 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004701 }
4702 }
4703 if (skip) break;
4704 }
4705 return skip;
4706}
4707
Jeff Leger178b1e52020-10-05 12:22:23 -04004708bool SyncValidator::PreCallValidateCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage,
4709 VkImageLayout srcImageLayout, VkBuffer dstBuffer, uint32_t regionCount,
4710 const VkBufferImageCopy *pRegions) const {
4711 return ValidateCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004712 CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004713}
4714
4715bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4716 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) const {
4717 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4718 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004719 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4720}
4721
4722bool SyncValidator::PreCallValidateCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4723 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) const {
4724 return ValidateCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4725 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4726 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004727}
4728
sfricke-samsung71f04e32022-03-16 01:21:21 -05004729template <typename RegionType>
Jeff Leger178b1e52020-10-05 12:22:23 -04004730void SyncValidator::RecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
sfricke-samsung71f04e32022-03-16 01:21:21 -05004731 VkBuffer dstBuffer, uint32_t regionCount, const RegionType *pRegions,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004732 CMD_TYPE cmd_type) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004733 auto *cb_access_context = GetAccessContext(commandBuffer);
4734 assert(cb_access_context);
Jeff Leger178b1e52020-10-05 12:22:23 -04004735
Jeff Leger178b1e52020-10-05 12:22:23 -04004736 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunarga19c71d2020-03-02 18:17:04 -07004737 auto *context = cb_access_context->GetCurrentAccessContext();
4738 assert(context);
4739
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004740 auto src_image = Get<IMAGE_STATE>(srcImage);
Jeremy Gebben9f537102021-10-05 16:37:12 -06004741 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebben6fbf8242021-06-21 09:14:46 -06004742 const auto dst_mem = (dst_buffer && !dst_buffer->sparse) ? dst_buffer->MemState()->mem() : VK_NULL_HANDLE;
John Zulauf5f13a792020-03-10 07:31:21 -06004743 const VulkanTypedHandle dst_handle(dst_mem, kVulkanObjectTypeDeviceMemory);
locke-lunarga19c71d2020-03-02 18:17:04 -07004744
4745 for (uint32_t region = 0; region < regionCount; region++) {
4746 const auto &copy_region = pRegions[region];
4747 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07004748 context->UpdateAccessState(*src_image, SYNC_COPY_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004749 copy_region.imageSubresource, copy_region.imageOffset, copy_region.imageExtent, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004750 if (dst_buffer) {
4751 ResourceAccessRange dst_range =
4752 MakeRange(copy_region.bufferOffset, GetBufferSizeFromCopyImage(copy_region, src_image->createInfo.format));
Jeremy Gebben40a22942020-12-22 14:22:06 -07004753 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, dst_range, tag);
John Zulauf477700e2021-01-06 11:41:49 -07004754 }
locke-lunarga19c71d2020-03-02 18:17:04 -07004755 }
4756 }
4757}
4758
Jeff Leger178b1e52020-10-05 12:22:23 -04004759void SyncValidator::PreCallRecordCmdCopyImageToBuffer(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4760 VkBuffer dstBuffer, uint32_t regionCount, const VkBufferImageCopy *pRegions) {
4761 StateTracker::PreCallRecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions);
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004762 RecordCmdCopyImageToBuffer(commandBuffer, srcImage, srcImageLayout, dstBuffer, regionCount, pRegions, CMD_COPYIMAGETOBUFFER);
Jeff Leger178b1e52020-10-05 12:22:23 -04004763}
4764
4765void SyncValidator::PreCallRecordCmdCopyImageToBuffer2KHR(VkCommandBuffer commandBuffer,
4766 const VkCopyImageToBufferInfo2KHR *pCopyImageToBufferInfo) {
4767 StateTracker::PreCallRecordCmdCopyImageToBuffer2KHR(commandBuffer, pCopyImageToBufferInfo);
4768 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4769 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
Tony-LunarGaf3632a2021-11-10 15:51:57 -07004770 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2KHR);
4771}
4772
4773void SyncValidator::PreCallRecordCmdCopyImageToBuffer2(VkCommandBuffer commandBuffer,
4774 const VkCopyImageToBufferInfo2 *pCopyImageToBufferInfo) {
4775 StateTracker::PreCallRecordCmdCopyImageToBuffer2(commandBuffer, pCopyImageToBufferInfo);
4776 RecordCmdCopyImageToBuffer(commandBuffer, pCopyImageToBufferInfo->srcImage, pCopyImageToBufferInfo->srcImageLayout,
4777 pCopyImageToBufferInfo->dstBuffer, pCopyImageToBufferInfo->regionCount,
4778 pCopyImageToBufferInfo->pRegions, CMD_COPYIMAGETOBUFFER2);
Jeff Leger178b1e52020-10-05 12:22:23 -04004779}
4780
4781template <typename RegionType>
4782bool SyncValidator::ValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4783 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
sjfricke0bea06e2022-06-05 09:22:26 +09004784 const RegionType *pRegions, VkFilter filter, CMD_TYPE cmd_type) const {
locke-lunarga19c71d2020-03-02 18:17:04 -07004785 bool skip = false;
4786 const auto *cb_access_context = GetAccessContext(commandBuffer);
4787 assert(cb_access_context);
4788 if (!cb_access_context) return skip;
4789
4790 const auto *context = cb_access_context->GetCurrentAccessContext();
4791 assert(context);
4792 if (!context) return skip;
4793
sjfricke0bea06e2022-06-05 09:22:26 +09004794 const char *caller_name = CommandTypeString(cmd_type);
4795
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004796 auto src_image = Get<IMAGE_STATE>(srcImage);
4797 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004798
4799 for (uint32_t region = 0; region < regionCount; region++) {
4800 const auto &blit_region = pRegions[region];
4801 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004802 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4803 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4804 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4805 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4806 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4807 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004808 auto hazard =
4809 context->DetectHazard(*src_image, SYNC_BLIT_TRANSFER_READ, blit_region.srcSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004810 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004811 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004812 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004813 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004814 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004815 }
4816 }
4817
4818 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004819 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4820 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4821 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4822 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4823 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4824 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Aitor Camachoe67f2c72022-06-08 14:41:58 +02004825 auto hazard =
4826 context->DetectHazard(*dst_image, SYNC_BLIT_TRANSFER_WRITE, blit_region.dstSubresource, offset, extent, false);
locke-lunarga19c71d2020-03-02 18:17:04 -07004827 if (hazard.hazard) {
locke-lunarga0003652020-03-10 11:38:51 -06004828 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004829 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", caller_name,
John Zulauf1dae9192020-06-16 15:46:44 -06004830 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06004831 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarga19c71d2020-03-02 18:17:04 -07004832 }
4833 if (skip) break;
4834 }
4835 }
4836
4837 return skip;
4838}
4839
Jeff Leger178b1e52020-10-05 12:22:23 -04004840bool SyncValidator::PreCallValidateCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4841 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4842 const VkImageBlit *pRegions, VkFilter filter) const {
4843 return ValidateCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter,
sjfricke0bea06e2022-06-05 09:22:26 +09004844 CMD_BLITIMAGE);
Jeff Leger178b1e52020-10-05 12:22:23 -04004845}
4846
4847bool SyncValidator::PreCallValidateCmdBlitImage2KHR(VkCommandBuffer commandBuffer,
4848 const VkBlitImageInfo2KHR *pBlitImageInfo) const {
4849 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4850 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
sjfricke0bea06e2022-06-05 09:22:26 +09004851 pBlitImageInfo->filter, CMD_BLITIMAGE2KHR);
Jeff Leger178b1e52020-10-05 12:22:23 -04004852}
4853
Tony-LunarG542ae912021-11-04 16:06:44 -06004854bool SyncValidator::PreCallValidateCmdBlitImage2(VkCommandBuffer commandBuffer,
4855 const VkBlitImageInfo2 *pBlitImageInfo) const {
4856 return ValidateCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
sjfricke0bea06e2022-06-05 09:22:26 +09004857 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4858 pBlitImageInfo->filter, CMD_BLITIMAGE2);
Tony-LunarG542ae912021-11-04 16:06:44 -06004859}
4860
Jeff Leger178b1e52020-10-05 12:22:23 -04004861template <typename RegionType>
4862void SyncValidator::RecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4863 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4864 const RegionType *pRegions, VkFilter filter, ResourceUsageTag tag) {
locke-lunarga19c71d2020-03-02 18:17:04 -07004865 auto *cb_access_context = GetAccessContext(commandBuffer);
4866 assert(cb_access_context);
4867 auto *context = cb_access_context->GetCurrentAccessContext();
4868 assert(context);
4869
Jeremy Gebben9f537102021-10-05 16:37:12 -06004870 auto src_image = Get<IMAGE_STATE>(srcImage);
4871 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarga19c71d2020-03-02 18:17:04 -07004872
4873 for (uint32_t region = 0; region < regionCount; region++) {
4874 const auto &blit_region = pRegions[region];
4875 if (src_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004876 VkOffset3D offset = {std::min(blit_region.srcOffsets[0].x, blit_region.srcOffsets[1].x),
4877 std::min(blit_region.srcOffsets[0].y, blit_region.srcOffsets[1].y),
4878 std::min(blit_region.srcOffsets[0].z, blit_region.srcOffsets[1].z)};
4879 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.srcOffsets[1].x - blit_region.srcOffsets[0].x)),
4880 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].y - blit_region.srcOffsets[0].y)),
4881 static_cast<uint32_t>(abs(blit_region.srcOffsets[1].z - blit_region.srcOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004882 context->UpdateAccessState(*src_image, SYNC_BLIT_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004883 blit_region.srcSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004884 }
4885 if (dst_image) {
locke-lunarg8f93acc2020-06-18 21:26:46 -06004886 VkOffset3D offset = {std::min(blit_region.dstOffsets[0].x, blit_region.dstOffsets[1].x),
4887 std::min(blit_region.dstOffsets[0].y, blit_region.dstOffsets[1].y),
4888 std::min(blit_region.dstOffsets[0].z, blit_region.dstOffsets[1].z)};
4889 VkExtent3D extent = {static_cast<uint32_t>(abs(blit_region.dstOffsets[1].x - blit_region.dstOffsets[0].x)),
4890 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].y - blit_region.dstOffsets[0].y)),
4891 static_cast<uint32_t>(abs(blit_region.dstOffsets[1].z - blit_region.dstOffsets[0].z))};
Jeremy Gebben40a22942020-12-22 14:22:06 -07004892 context->UpdateAccessState(*dst_image, SYNC_BLIT_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07004893 blit_region.dstSubresource, offset, extent, tag);
locke-lunarga19c71d2020-03-02 18:17:04 -07004894 }
4895 }
4896}
locke-lunarg36ba2592020-04-03 09:42:04 -06004897
Jeff Leger178b1e52020-10-05 12:22:23 -04004898void SyncValidator::PreCallRecordCmdBlitImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
4899 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
4900 const VkImageBlit *pRegions, VkFilter filter) {
4901 auto *cb_access_context = GetAccessContext(commandBuffer);
4902 assert(cb_access_context);
4903 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE);
4904 StateTracker::PreCallRecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
4905 pRegions, filter);
4906 RecordCmdBlitImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount, pRegions, filter, tag);
4907}
4908
4909void SyncValidator::PreCallRecordCmdBlitImage2KHR(VkCommandBuffer commandBuffer, const VkBlitImageInfo2KHR *pBlitImageInfo) {
4910 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4911 auto *cb_access_context = GetAccessContext(commandBuffer);
4912 assert(cb_access_context);
4913 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2KHR);
4914 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4915 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4916 pBlitImageInfo->filter, tag);
4917}
4918
Tony-LunarG542ae912021-11-04 16:06:44 -06004919void SyncValidator::PreCallRecordCmdBlitImage2(VkCommandBuffer commandBuffer, const VkBlitImageInfo2 *pBlitImageInfo) {
4920 StateTracker::PreCallRecordCmdBlitImage2KHR(commandBuffer, pBlitImageInfo);
4921 auto *cb_access_context = GetAccessContext(commandBuffer);
4922 assert(cb_access_context);
4923 const auto tag = cb_access_context->NextCommandTag(CMD_BLITIMAGE2);
4924 RecordCmdBlitImage(commandBuffer, pBlitImageInfo->srcImage, pBlitImageInfo->srcImageLayout, pBlitImageInfo->dstImage,
4925 pBlitImageInfo->dstImageLayout, pBlitImageInfo->regionCount, pBlitImageInfo->pRegions,
4926 pBlitImageInfo->filter, tag);
4927}
4928
John Zulauffaea0ee2021-01-14 14:01:32 -07004929bool SyncValidator::ValidateIndirectBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4930 VkCommandBuffer commandBuffer, const VkDeviceSize struct_size, const VkBuffer buffer,
4931 const VkDeviceSize offset, const uint32_t drawCount, const uint32_t stride,
sjfricke0bea06e2022-06-05 09:22:26 +09004932 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004933 bool skip = false;
4934 if (drawCount == 0) return skip;
4935
sjfricke0bea06e2022-06-05 09:22:26 +09004936 const char *caller_name = CommandTypeString(cmd_type);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004937 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004938 VkDeviceSize size = struct_size;
4939 if (drawCount == 1 || stride == size) {
4940 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004941 const ResourceAccessRange range = MakeRange(offset, size);
locke-lunargff255f92020-05-13 18:53:52 -06004942 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4943 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004944 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004945 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name, string_SyncHazard(hazard.hazard),
John Zulauf1dae9192020-06-16 15:46:44 -06004946 report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(commandBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06004947 cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004948 }
4949 } else {
4950 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004951 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
locke-lunargff255f92020-05-13 18:53:52 -06004952 auto hazard = context.DetectHazard(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4953 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004954 skip |= LogError(buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004955 "%s: Hazard %s for indirect %s in %s. Access info %s.", caller_name,
4956 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
4957 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004958 break;
4959 }
4960 }
4961 }
4962 return skip;
4963}
4964
John Zulauf14940722021-04-12 15:19:02 -06004965void SyncValidator::RecordIndirectBuffer(AccessContext &context, const ResourceUsageTag tag, const VkDeviceSize struct_size,
locke-lunarg61870c22020-06-09 14:51:50 -06004966 const VkBuffer buffer, const VkDeviceSize offset, const uint32_t drawCount,
4967 uint32_t stride) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004968 auto buf_state = Get<BUFFER_STATE>(buffer);
locke-lunargff255f92020-05-13 18:53:52 -06004969 VkDeviceSize size = struct_size;
4970 if (drawCount == 1 || stride == size) {
4971 if (drawCount > 1) size *= drawCount;
John Zulauf3e86bf02020-09-12 10:47:57 -06004972 const ResourceAccessRange range = MakeRange(offset, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004973 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06004974 } else {
4975 for (uint32_t i = 0; i < drawCount; ++i) {
John Zulauf3e86bf02020-09-12 10:47:57 -06004976 const ResourceAccessRange range = MakeRange(offset + i * stride, size);
John Zulauf8e3c3e92021-01-06 11:19:36 -07004977 context.UpdateAccessState(*buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range,
4978 tag);
locke-lunargff255f92020-05-13 18:53:52 -06004979 }
4980 }
4981}
4982
John Zulauffaea0ee2021-01-14 14:01:32 -07004983bool SyncValidator::ValidateCountBuffer(const CommandBufferAccessContext &cb_context, const AccessContext &context,
4984 VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
sjfricke0bea06e2022-06-05 09:22:26 +09004985 CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06004986 bool skip = false;
4987
Jeremy Gebbenf4449392022-01-28 10:09:10 -07004988 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06004989 const ResourceAccessRange range = MakeRange(offset, 4);
locke-lunargff255f92020-05-13 18:53:52 -06004990 auto hazard = context.DetectHazard(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, range);
4991 if (hazard.hazard) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06004992 skip |= LogError(count_buf_state->buffer(), string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09004993 "%s: Hazard %s for countBuffer %s in %s. Access info %s.", CommandTypeString(cmd_type),
4994 string_SyncHazard(hazard.hazard), report_data->FormatHandle(buffer).c_str(),
4995 report_data->FormatHandle(commandBuffer).c_str(), cb_context.FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06004996 }
4997 return skip;
4998}
4999
John Zulauf14940722021-04-12 15:19:02 -06005000void SyncValidator::RecordCountBuffer(AccessContext &context, const ResourceUsageTag tag, VkBuffer buffer, VkDeviceSize offset) {
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005001 auto count_buf_state = Get<BUFFER_STATE>(buffer);
John Zulauf3e86bf02020-09-12 10:47:57 -06005002 const ResourceAccessRange range = MakeRange(offset, 4);
John Zulauf8e3c3e92021-01-06 11:19:36 -07005003 context.UpdateAccessState(*count_buf_state, SYNC_DRAW_INDIRECT_INDIRECT_COMMAND_READ, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005004}
5005
locke-lunarg36ba2592020-04-03 09:42:04 -06005006bool SyncValidator::PreCallValidateCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) const {
locke-lunargff255f92020-05-13 18:53:52 -06005007 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005008 const auto *cb_access_context = GetAccessContext(commandBuffer);
5009 assert(cb_access_context);
5010 if (!cb_access_context) return skip;
5011
sjfricke0bea06e2022-06-05 09:22:26 +09005012 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005013 return skip;
locke-lunarg36ba2592020-04-03 09:42:04 -06005014}
5015
5016void SyncValidator::PreCallRecordCmdDispatch(VkCommandBuffer commandBuffer, uint32_t x, uint32_t y, uint32_t z) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005017 StateTracker::PreCallRecordCmdDispatch(commandBuffer, x, y, z);
locke-lunargff255f92020-05-13 18:53:52 -06005018 auto *cb_access_context = GetAccessContext(commandBuffer);
5019 assert(cb_access_context);
5020 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCH);
locke-lunargff255f92020-05-13 18:53:52 -06005021
locke-lunarg61870c22020-06-09 14:51:50 -06005022 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
locke-lunarg36ba2592020-04-03 09:42:04 -06005023}
locke-lunarge1a67022020-04-29 00:15:36 -06005024
5025bool SyncValidator::PreCallValidateCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) const {
locke-lunargff255f92020-05-13 18:53:52 -06005026 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005027 const auto *cb_access_context = GetAccessContext(commandBuffer);
5028 assert(cb_access_context);
5029 if (!cb_access_context) return skip;
5030
5031 const auto *context = cb_access_context->GetCurrentAccessContext();
5032 assert(context);
5033 if (!context) return skip;
5034
sjfricke0bea06e2022-06-05 09:22:26 +09005035 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, CMD_DISPATCHINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005036 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDispatchIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005037 1, sizeof(VkDispatchIndirectCommand), CMD_DISPATCHINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005038 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005039}
5040
5041void SyncValidator::PreCallRecordCmdDispatchIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005042 StateTracker::PreCallRecordCmdDispatchIndirect(commandBuffer, buffer, offset);
locke-lunargff255f92020-05-13 18:53:52 -06005043 auto *cb_access_context = GetAccessContext(commandBuffer);
5044 assert(cb_access_context);
5045 const auto tag = cb_access_context->NextCommandTag(CMD_DISPATCHINDIRECT);
5046 auto *context = cb_access_context->GetCurrentAccessContext();
5047 assert(context);
5048
locke-lunarg61870c22020-06-09 14:51:50 -06005049 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_COMPUTE, tag);
5050 RecordIndirectBuffer(*context, tag, sizeof(VkDispatchIndirectCommand), buffer, offset, 1, sizeof(VkDispatchIndirectCommand));
locke-lunarge1a67022020-04-29 00:15:36 -06005051}
5052
5053bool SyncValidator::PreCallValidateCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5054 uint32_t firstVertex, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005055 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005056 const auto *cb_access_context = GetAccessContext(commandBuffer);
5057 assert(cb_access_context);
5058 if (!cb_access_context) return skip;
5059
sjfricke0bea06e2022-06-05 09:22:26 +09005060 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAW);
5061 skip |= cb_access_context->ValidateDrawVertex(vertexCount, firstVertex, CMD_DRAW);
5062 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAW);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005063 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005064}
5065
5066void SyncValidator::PreCallRecordCmdDraw(VkCommandBuffer commandBuffer, uint32_t vertexCount, uint32_t instanceCount,
5067 uint32_t firstVertex, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005068 StateTracker::PreCallRecordCmdDraw(commandBuffer, vertexCount, instanceCount, firstVertex, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005069 auto *cb_access_context = GetAccessContext(commandBuffer);
5070 assert(cb_access_context);
5071 const auto tag = cb_access_context->NextCommandTag(CMD_DRAW);
locke-lunargff255f92020-05-13 18:53:52 -06005072
locke-lunarg61870c22020-06-09 14:51:50 -06005073 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5074 cb_access_context->RecordDrawVertex(vertexCount, firstVertex, tag);
5075 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005076}
5077
5078bool SyncValidator::PreCallValidateCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5079 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) const {
locke-lunarga4d39ea2020-05-22 14:17:29 -06005080 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005081 const auto *cb_access_context = GetAccessContext(commandBuffer);
5082 assert(cb_access_context);
5083 if (!cb_access_context) return skip;
5084
sjfricke0bea06e2022-06-05 09:22:26 +09005085 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXED);
5086 skip |= cb_access_context->ValidateDrawVertexIndex(indexCount, firstIndex, CMD_DRAWINDEXED);
5087 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXED);
locke-lunarga4d39ea2020-05-22 14:17:29 -06005088 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005089}
5090
5091void SyncValidator::PreCallRecordCmdDrawIndexed(VkCommandBuffer commandBuffer, uint32_t indexCount, uint32_t instanceCount,
5092 uint32_t firstIndex, int32_t vertexOffset, uint32_t firstInstance) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005093 StateTracker::PreCallRecordCmdDrawIndexed(commandBuffer, indexCount, instanceCount, firstIndex, vertexOffset, firstInstance);
locke-lunargff255f92020-05-13 18:53:52 -06005094 auto *cb_access_context = GetAccessContext(commandBuffer);
5095 assert(cb_access_context);
5096 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXED);
locke-lunargff255f92020-05-13 18:53:52 -06005097
locke-lunarg61870c22020-06-09 14:51:50 -06005098 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5099 cb_access_context->RecordDrawVertexIndex(indexCount, firstIndex, tag);
5100 cb_access_context->RecordDrawSubpassAttachment(tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005101}
5102
5103bool SyncValidator::PreCallValidateCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5104 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005105 bool skip = false;
5106 if (drawCount == 0) return skip;
5107
locke-lunargff255f92020-05-13 18:53:52 -06005108 const auto *cb_access_context = GetAccessContext(commandBuffer);
5109 assert(cb_access_context);
5110 if (!cb_access_context) return skip;
5111
5112 const auto *context = cb_access_context->GetCurrentAccessContext();
5113 assert(context);
5114 if (!context) return skip;
5115
sjfricke0bea06e2022-06-05 09:22:26 +09005116 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDIRECT);
5117 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005118 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005119 drawCount, stride, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005120
5121 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5122 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5123 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005124 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, CMD_DRAWINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005125 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005126}
5127
5128void SyncValidator::PreCallRecordCmdDrawIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5129 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005130 StateTracker::PreCallRecordCmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005131 if (drawCount == 0) return;
locke-lunargff255f92020-05-13 18:53:52 -06005132 auto *cb_access_context = GetAccessContext(commandBuffer);
5133 assert(cb_access_context);
5134 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDIRECT);
5135 auto *context = cb_access_context->GetCurrentAccessContext();
5136 assert(context);
5137
locke-lunarg61870c22020-06-09 14:51:50 -06005138 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5139 cb_access_context->RecordDrawSubpassAttachment(tag);
5140 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005141
5142 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5143 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5144 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005145 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005146}
5147
5148bool SyncValidator::PreCallValidateCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5149 uint32_t drawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005150 bool skip = false;
5151 if (drawCount == 0) return skip;
locke-lunargff255f92020-05-13 18:53:52 -06005152 const auto *cb_access_context = GetAccessContext(commandBuffer);
5153 assert(cb_access_context);
5154 if (!cb_access_context) return skip;
5155
5156 const auto *context = cb_access_context->GetCurrentAccessContext();
5157 assert(context);
5158 if (!context) return skip;
5159
sjfricke0bea06e2022-06-05 09:22:26 +09005160 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, CMD_DRAWINDEXEDINDIRECT);
5161 skip |= cb_access_context->ValidateDrawSubpassAttachment(CMD_DRAWINDEXEDINDIRECT);
John Zulauffaea0ee2021-01-14 14:01:32 -07005162 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005163 offset, drawCount, stride, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005164
5165 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5166 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5167 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005168 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, CMD_DRAWINDEXEDINDIRECT);
locke-lunargff255f92020-05-13 18:53:52 -06005169 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005170}
5171
5172void SyncValidator::PreCallRecordCmdDrawIndexedIndirect(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5173 uint32_t drawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005174 StateTracker::PreCallRecordCmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005175 auto *cb_access_context = GetAccessContext(commandBuffer);
5176 assert(cb_access_context);
5177 const auto tag = cb_access_context->NextCommandTag(CMD_DRAWINDEXEDINDIRECT);
5178 auto *context = cb_access_context->GetCurrentAccessContext();
5179 assert(context);
5180
locke-lunarg61870c22020-06-09 14:51:50 -06005181 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5182 cb_access_context->RecordDrawSubpassAttachment(tag);
5183 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, drawCount, stride);
locke-lunargff255f92020-05-13 18:53:52 -06005184
5185 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5186 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5187 // We will record the index and vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005188 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005189}
5190
5191bool SyncValidator::ValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5192 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005193 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005194 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005195 const auto *cb_access_context = GetAccessContext(commandBuffer);
5196 assert(cb_access_context);
5197 if (!cb_access_context) return skip;
5198
5199 const auto *context = cb_access_context->GetCurrentAccessContext();
5200 assert(context);
5201 if (!context) return skip;
5202
sjfricke0bea06e2022-06-05 09:22:26 +09005203 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5204 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005205 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndirectCommand), buffer, offset,
sjfricke0bea06e2022-06-05 09:22:26 +09005206 maxDrawCount, stride, cmd_type);
5207 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005208
5209 // TODO: For now, we validate the whole vertex buffer. It might cause some false positive.
5210 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5211 // We will validate the vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005212 skip |= cb_access_context->ValidateDrawVertex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005213 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005214}
5215
5216bool SyncValidator::PreCallValidateCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5217 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5218 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005219 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005220 CMD_DRAWINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005221}
5222
sfricke-samsung85584a72021-09-30 21:43:38 -07005223void SyncValidator::RecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5224 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5225 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005226 auto *cb_access_context = GetAccessContext(commandBuffer);
5227 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005228 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005229 auto *context = cb_access_context->GetCurrentAccessContext();
5230 assert(context);
5231
locke-lunarg61870c22020-06-09 14:51:50 -06005232 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5233 cb_access_context->RecordDrawSubpassAttachment(tag);
5234 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndirectCommand), buffer, offset, 1, stride);
5235 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005236
5237 // TODO: For now, we record the whole vertex buffer. It might cause some false positive.
5238 // VkDrawIndirectCommand buffer could be changed until SubmitQueue.
5239 // We will record the vertex buffer in SubmitQueue in the future.
locke-lunarg61870c22020-06-09 14:51:50 -06005240 cb_access_context->RecordDrawVertex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005241}
5242
sfricke-samsung85584a72021-09-30 21:43:38 -07005243void SyncValidator::PreCallRecordCmdDrawIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5244 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5245 uint32_t stride) {
5246 StateTracker::PreCallRecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5247 stride);
5248 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5249 CMD_DRAWINDIRECTCOUNT);
5250}
locke-lunarge1a67022020-04-29 00:15:36 -06005251bool SyncValidator::PreCallValidateCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5252 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5253 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005254 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005255 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005256}
5257
5258void SyncValidator::PreCallRecordCmdDrawIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5259 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5260 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005261 StateTracker::PreCallRecordCmdDrawIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5262 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005263 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5264 CMD_DRAWINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005265}
5266
5267bool SyncValidator::PreCallValidateCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5268 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5269 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005270 return ValidateCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005271 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005272}
5273
5274void SyncValidator::PreCallRecordCmdDrawIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5275 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5276 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005277 StateTracker::PreCallRecordCmdDrawIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount,
5278 stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005279 RecordCmdDrawIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5280 CMD_DRAWINDIRECTCOUNTAMD);
locke-lunargff255f92020-05-13 18:53:52 -06005281}
5282
5283bool SyncValidator::ValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5284 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
sjfricke0bea06e2022-06-05 09:22:26 +09005285 uint32_t stride, CMD_TYPE cmd_type) const {
locke-lunargff255f92020-05-13 18:53:52 -06005286 bool skip = false;
locke-lunargff255f92020-05-13 18:53:52 -06005287 const auto *cb_access_context = GetAccessContext(commandBuffer);
5288 assert(cb_access_context);
5289 if (!cb_access_context) return skip;
5290
5291 const auto *context = cb_access_context->GetCurrentAccessContext();
5292 assert(context);
5293 if (!context) return skip;
5294
sjfricke0bea06e2022-06-05 09:22:26 +09005295 skip |= cb_access_context->ValidateDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, cmd_type);
5296 skip |= cb_access_context->ValidateDrawSubpassAttachment(cmd_type);
John Zulauffaea0ee2021-01-14 14:01:32 -07005297 skip |= ValidateIndirectBuffer(*cb_access_context, *context, commandBuffer, sizeof(VkDrawIndexedIndirectCommand), buffer,
sjfricke0bea06e2022-06-05 09:22:26 +09005298 offset, maxDrawCount, stride, cmd_type);
5299 skip |= ValidateCountBuffer(*cb_access_context, *context, commandBuffer, countBuffer, countBufferOffset, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005300
5301 // TODO: For now, we validate the whole index and vertex buffer. It might cause some false positive.
5302 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
5303 // We will validate the index and vertex buffer in SubmitQueue in the future.
sjfricke0bea06e2022-06-05 09:22:26 +09005304 skip |= cb_access_context->ValidateDrawVertexIndex(UINT32_MAX, 0, cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005305 return skip;
locke-lunarge1a67022020-04-29 00:15:36 -06005306}
5307
5308bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5309 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5310 uint32_t maxDrawCount, uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005311 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005312 CMD_DRAWINDEXEDINDIRECTCOUNT);
locke-lunarge1a67022020-04-29 00:15:36 -06005313}
5314
sfricke-samsung85584a72021-09-30 21:43:38 -07005315void SyncValidator::RecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5316 VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5317 uint32_t stride, CMD_TYPE cmd_type) {
locke-lunargff255f92020-05-13 18:53:52 -06005318 auto *cb_access_context = GetAccessContext(commandBuffer);
5319 assert(cb_access_context);
sfricke-samsung85584a72021-09-30 21:43:38 -07005320 const auto tag = cb_access_context->NextCommandTag(cmd_type);
locke-lunargff255f92020-05-13 18:53:52 -06005321 auto *context = cb_access_context->GetCurrentAccessContext();
5322 assert(context);
5323
locke-lunarg61870c22020-06-09 14:51:50 -06005324 cb_access_context->RecordDispatchDrawDescriptorSet(VK_PIPELINE_BIND_POINT_GRAPHICS, tag);
5325 cb_access_context->RecordDrawSubpassAttachment(tag);
5326 RecordIndirectBuffer(*context, tag, sizeof(VkDrawIndexedIndirectCommand), buffer, offset, 1, stride);
5327 RecordCountBuffer(*context, tag, countBuffer, countBufferOffset);
locke-lunargff255f92020-05-13 18:53:52 -06005328
5329 // TODO: For now, we record the whole index and vertex buffer. It might cause some false positive.
5330 // VkDrawIndexedIndirectCommand buffer could be changed until SubmitQueue.
locke-lunarg61870c22020-06-09 14:51:50 -06005331 // We will update the index and vertex buffer in SubmitQueue in the future.
5332 cb_access_context->RecordDrawVertexIndex(UINT32_MAX, 0, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005333}
5334
sfricke-samsung85584a72021-09-30 21:43:38 -07005335void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCount(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5336 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5337 uint32_t maxDrawCount, uint32_t stride) {
5338 StateTracker::PreCallRecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5339 maxDrawCount, stride);
5340 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5341 CMD_DRAWINDEXEDINDIRECTCOUNT);
5342}
5343
locke-lunarge1a67022020-04-29 00:15:36 -06005344bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer,
5345 VkDeviceSize offset, VkBuffer countBuffer,
5346 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5347 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005348 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005349 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005350}
5351
5352void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountKHR(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5353 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5354 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005355 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5356 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005357 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5358 CMD_DRAWINDEXEDINDIRECTCOUNTKHR);
locke-lunarge1a67022020-04-29 00:15:36 -06005359}
5360
5361bool SyncValidator::PreCallValidateCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer,
5362 VkDeviceSize offset, VkBuffer countBuffer,
5363 VkDeviceSize countBufferOffset, uint32_t maxDrawCount,
5364 uint32_t stride) const {
locke-lunargff255f92020-05-13 18:53:52 -06005365 return ValidateCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
sjfricke0bea06e2022-06-05 09:22:26 +09005366 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005367}
5368
5369void SyncValidator::PreCallRecordCmdDrawIndexedIndirectCountAMD(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset,
5370 VkBuffer countBuffer, VkDeviceSize countBufferOffset,
5371 uint32_t maxDrawCount, uint32_t stride) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005372 StateTracker::PreCallRecordCmdDrawIndexedIndirectCountAMD(commandBuffer, buffer, offset, countBuffer, countBufferOffset,
5373 maxDrawCount, stride);
sfricke-samsung85584a72021-09-30 21:43:38 -07005374 RecordCmdDrawIndexedIndirectCount(commandBuffer, buffer, offset, countBuffer, countBufferOffset, maxDrawCount, stride,
5375 CMD_DRAWINDEXEDINDIRECTCOUNTAMD);
locke-lunarge1a67022020-04-29 00:15:36 -06005376}
5377
5378bool SyncValidator::PreCallValidateCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5379 const VkClearColorValue *pColor, uint32_t rangeCount,
5380 const VkImageSubresourceRange *pRanges) const {
5381 bool skip = false;
5382 const auto *cb_access_context = GetAccessContext(commandBuffer);
5383 assert(cb_access_context);
5384 if (!cb_access_context) return skip;
5385
5386 const auto *context = cb_access_context->GetCurrentAccessContext();
5387 assert(context);
5388 if (!context) return skip;
5389
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005390 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005391
5392 for (uint32_t index = 0; index < rangeCount; index++) {
5393 const auto &range = pRanges[index];
5394 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005395 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005396 if (hazard.hazard) {
5397 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005398 "vkCmdClearColorImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005399 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005400 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005401 }
5402 }
5403 }
5404 return skip;
5405}
5406
5407void SyncValidator::PreCallRecordCmdClearColorImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5408 const VkClearColorValue *pColor, uint32_t rangeCount,
5409 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005410 StateTracker::PreCallRecordCmdClearColorImage(commandBuffer, image, imageLayout, pColor, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005411 auto *cb_access_context = GetAccessContext(commandBuffer);
5412 assert(cb_access_context);
5413 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARCOLORIMAGE);
5414 auto *context = cb_access_context->GetCurrentAccessContext();
5415 assert(context);
5416
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005417 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005418
5419 for (uint32_t index = 0; index < rangeCount; index++) {
5420 const auto &range = pRanges[index];
5421 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005422 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005423 }
5424 }
5425}
5426
5427bool SyncValidator::PreCallValidateCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image,
5428 VkImageLayout imageLayout,
5429 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5430 const VkImageSubresourceRange *pRanges) const {
5431 bool skip = false;
5432 const auto *cb_access_context = GetAccessContext(commandBuffer);
5433 assert(cb_access_context);
5434 if (!cb_access_context) return skip;
5435
5436 const auto *context = cb_access_context->GetCurrentAccessContext();
5437 assert(context);
5438 if (!context) return skip;
5439
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005440 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005441
5442 for (uint32_t index = 0; index < rangeCount; index++) {
5443 const auto &range = pRanges[index];
5444 if (image_state) {
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005445 auto hazard = context->DetectHazard(*image_state, SYNC_CLEAR_TRANSFER_WRITE, range, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005446 if (hazard.hazard) {
5447 skip |= LogError(image, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005448 "vkCmdClearDepthStencilImage: Hazard %s for %s, range index %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005449 string_SyncHazard(hazard.hazard), report_data->FormatHandle(image).c_str(), index,
John Zulauf397e68b2022-04-19 11:44:07 -06005450 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005451 }
5452 }
5453 }
5454 return skip;
5455}
5456
5457void SyncValidator::PreCallRecordCmdClearDepthStencilImage(VkCommandBuffer commandBuffer, VkImage image, VkImageLayout imageLayout,
5458 const VkClearDepthStencilValue *pDepthStencil, uint32_t rangeCount,
5459 const VkImageSubresourceRange *pRanges) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005460 StateTracker::PreCallRecordCmdClearDepthStencilImage(commandBuffer, image, imageLayout, pDepthStencil, rangeCount, pRanges);
locke-lunarge1a67022020-04-29 00:15:36 -06005461 auto *cb_access_context = GetAccessContext(commandBuffer);
5462 assert(cb_access_context);
5463 const auto tag = cb_access_context->NextCommandTag(CMD_CLEARDEPTHSTENCILIMAGE);
5464 auto *context = cb_access_context->GetCurrentAccessContext();
5465 assert(context);
5466
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005467 auto image_state = Get<IMAGE_STATE>(image);
locke-lunarge1a67022020-04-29 00:15:36 -06005468
5469 for (uint32_t index = 0; index < rangeCount; index++) {
5470 const auto &range = pRanges[index];
5471 if (image_state) {
John Zulauf110413c2021-03-20 05:38:38 -06005472 context->UpdateAccessState(*image_state, SYNC_CLEAR_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005473 }
5474 }
5475}
5476
5477bool SyncValidator::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool,
5478 uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer,
5479 VkDeviceSize dstOffset, VkDeviceSize stride,
5480 VkQueryResultFlags flags) const {
5481 bool skip = false;
5482 const auto *cb_access_context = GetAccessContext(commandBuffer);
5483 assert(cb_access_context);
5484 if (!cb_access_context) return skip;
5485
5486 const auto *context = cb_access_context->GetCurrentAccessContext();
5487 assert(context);
5488 if (!context) return skip;
5489
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005490 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005491
5492 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005493 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005494 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005495 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005496 skip |=
5497 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5498 "vkCmdCopyQueryPoolResults: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005499 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005500 }
5501 }
locke-lunargff255f92020-05-13 18:53:52 -06005502
5503 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005504 return skip;
5505}
5506
5507void SyncValidator::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery,
5508 uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5509 VkDeviceSize stride, VkQueryResultFlags flags) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005510 StateTracker::PreCallRecordCmdCopyQueryPoolResults(commandBuffer, queryPool, firstQuery, queryCount, dstBuffer, dstOffset,
5511 stride, flags);
locke-lunarge1a67022020-04-29 00:15:36 -06005512 auto *cb_access_context = GetAccessContext(commandBuffer);
5513 assert(cb_access_context);
locke-lunargff255f92020-05-13 18:53:52 -06005514 const auto tag = cb_access_context->NextCommandTag(CMD_COPYQUERYPOOLRESULTS);
locke-lunarge1a67022020-04-29 00:15:36 -06005515 auto *context = cb_access_context->GetCurrentAccessContext();
5516 assert(context);
5517
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005518 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005519
5520 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005521 const ResourceAccessRange range = MakeRange(dstOffset, stride * queryCount);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005522 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005523 }
locke-lunargff255f92020-05-13 18:53:52 -06005524
5525 // TODO:Track VkQueryPool
locke-lunarge1a67022020-04-29 00:15:36 -06005526}
5527
5528bool SyncValidator::PreCallValidateCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5529 VkDeviceSize size, uint32_t data) const {
5530 bool skip = false;
5531 const auto *cb_access_context = GetAccessContext(commandBuffer);
5532 assert(cb_access_context);
5533 if (!cb_access_context) return skip;
5534
5535 const auto *context = cb_access_context->GetCurrentAccessContext();
5536 assert(context);
5537 if (!context) return skip;
5538
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005539 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005540
5541 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005542 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005543 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005544 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005545 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005546 "vkCmdFillBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005547 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005548 }
5549 }
5550 return skip;
5551}
5552
5553void SyncValidator::PreCallRecordCmdFillBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5554 VkDeviceSize size, uint32_t data) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005555 StateTracker::PreCallRecordCmdFillBuffer(commandBuffer, dstBuffer, dstOffset, size, data);
locke-lunarge1a67022020-04-29 00:15:36 -06005556 auto *cb_access_context = GetAccessContext(commandBuffer);
5557 assert(cb_access_context);
5558 const auto tag = cb_access_context->NextCommandTag(CMD_FILLBUFFER);
5559 auto *context = cb_access_context->GetCurrentAccessContext();
5560 assert(context);
5561
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005562 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005563
5564 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005565 const ResourceAccessRange range = MakeRange(*dst_buffer, dstOffset, size);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005566 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005567 }
5568}
5569
5570bool SyncValidator::PreCallValidateCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5571 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5572 const VkImageResolve *pRegions) const {
5573 bool skip = false;
5574 const auto *cb_access_context = GetAccessContext(commandBuffer);
5575 assert(cb_access_context);
5576 if (!cb_access_context) return skip;
5577
5578 const auto *context = cb_access_context->GetCurrentAccessContext();
5579 assert(context);
5580 if (!context) return skip;
5581
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005582 auto src_image = Get<IMAGE_STATE>(srcImage);
5583 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005584
5585 for (uint32_t region = 0; region < regionCount; region++) {
5586 const auto &resolve_region = pRegions[region];
5587 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005588 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005589 resolve_region.srcOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005590 if (hazard.hazard) {
5591 skip |= LogError(srcImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005592 "vkCmdResolveImage: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005593 string_SyncHazard(hazard.hazard), report_data->FormatHandle(srcImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005594 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005595 }
5596 }
5597
5598 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005599 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005600 resolve_region.dstOffset, resolve_region.extent, false);
locke-lunarge1a67022020-04-29 00:15:36 -06005601 if (hazard.hazard) {
5602 skip |= LogError(dstImage, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005603 "vkCmdResolveImage: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.",
John Zulauf1dae9192020-06-16 15:46:44 -06005604 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstImage).c_str(), region,
John Zulauf397e68b2022-04-19 11:44:07 -06005605 cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005606 }
5607 if (skip) break;
5608 }
5609 }
5610
5611 return skip;
5612}
5613
5614void SyncValidator::PreCallRecordCmdResolveImage(VkCommandBuffer commandBuffer, VkImage srcImage, VkImageLayout srcImageLayout,
5615 VkImage dstImage, VkImageLayout dstImageLayout, uint32_t regionCount,
5616 const VkImageResolve *pRegions) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005617 StateTracker::PreCallRecordCmdResolveImage(commandBuffer, srcImage, srcImageLayout, dstImage, dstImageLayout, regionCount,
5618 pRegions);
locke-lunarge1a67022020-04-29 00:15:36 -06005619 auto *cb_access_context = GetAccessContext(commandBuffer);
5620 assert(cb_access_context);
5621 const auto tag = cb_access_context->NextCommandTag(CMD_RESOLVEIMAGE);
5622 auto *context = cb_access_context->GetCurrentAccessContext();
5623 assert(context);
5624
Jeremy Gebben9f537102021-10-05 16:37:12 -06005625 auto src_image = Get<IMAGE_STATE>(srcImage);
5626 auto dst_image = Get<IMAGE_STATE>(dstImage);
locke-lunarge1a67022020-04-29 00:15:36 -06005627
5628 for (uint32_t region = 0; region < regionCount; region++) {
5629 const auto &resolve_region = pRegions[region];
5630 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005631 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005632 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005633 }
5634 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005635 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005636 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005637 }
5638 }
5639}
5640
Tony-LunarG562fc102021-11-12 13:58:35 -07005641bool SyncValidator::ValidateCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5642 CMD_TYPE cmd_type) const {
Jeff Leger178b1e52020-10-05 12:22:23 -04005643 bool skip = false;
5644 const auto *cb_access_context = GetAccessContext(commandBuffer);
5645 assert(cb_access_context);
5646 if (!cb_access_context) return skip;
5647
5648 const auto *context = cb_access_context->GetCurrentAccessContext();
5649 assert(context);
5650 if (!context) return skip;
5651
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005652 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5653 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005654
5655 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5656 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5657 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005658 auto hazard = context->DetectHazard(*src_image, SYNC_RESOLVE_TRANSFER_READ, resolve_region.srcSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005659 resolve_region.srcOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005660 if (hazard.hazard) {
5661 skip |= LogError(pResolveImageInfo->srcImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005662 "%s: Hazard %s for srcImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005663 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->srcImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005664 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005665 }
5666 }
5667
5668 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005669 auto hazard = context->DetectHazard(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, resolve_region.dstSubresource,
Aitor Camachoe67f2c72022-06-08 14:41:58 +02005670 resolve_region.dstOffset, resolve_region.extent, false);
Jeff Leger178b1e52020-10-05 12:22:23 -04005671 if (hazard.hazard) {
5672 skip |= LogError(pResolveImageInfo->dstImage, string_SyncHazardVUID(hazard.hazard),
sjfricke0bea06e2022-06-05 09:22:26 +09005673 "%s: Hazard %s for dstImage %s, region %" PRIu32 ". Access info %s.", CommandTypeString(cmd_type),
Jeff Leger178b1e52020-10-05 12:22:23 -04005674 string_SyncHazard(hazard.hazard), report_data->FormatHandle(pResolveImageInfo->dstImage).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06005675 region, cb_access_context->FormatHazard(hazard).c_str());
Jeff Leger178b1e52020-10-05 12:22:23 -04005676 }
5677 if (skip) break;
5678 }
5679 }
5680
5681 return skip;
5682}
5683
Tony-LunarG562fc102021-11-12 13:58:35 -07005684bool SyncValidator::PreCallValidateCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5685 const VkResolveImageInfo2KHR *pResolveImageInfo) const {
5686 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5687}
5688
5689bool SyncValidator::PreCallValidateCmdResolveImage2(VkCommandBuffer commandBuffer,
5690 const VkResolveImageInfo2 *pResolveImageInfo) const {
5691 return ValidateCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5692}
5693
5694void SyncValidator::RecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2KHR *pResolveImageInfo,
5695 CMD_TYPE cmd_type) {
Jeff Leger178b1e52020-10-05 12:22:23 -04005696 StateTracker::PreCallRecordCmdResolveImage2KHR(commandBuffer, pResolveImageInfo);
5697 auto *cb_access_context = GetAccessContext(commandBuffer);
5698 assert(cb_access_context);
Tony-LunarG562fc102021-11-12 13:58:35 -07005699 const auto tag = cb_access_context->NextCommandTag(cmd_type);
Jeff Leger178b1e52020-10-05 12:22:23 -04005700 auto *context = cb_access_context->GetCurrentAccessContext();
5701 assert(context);
5702
Jeremy Gebben9f537102021-10-05 16:37:12 -06005703 auto src_image = Get<IMAGE_STATE>(pResolveImageInfo->srcImage);
5704 auto dst_image = Get<IMAGE_STATE>(pResolveImageInfo->dstImage);
Jeff Leger178b1e52020-10-05 12:22:23 -04005705
5706 for (uint32_t region = 0; region < pResolveImageInfo->regionCount; region++) {
5707 const auto &resolve_region = pResolveImageInfo->pRegions[region];
5708 if (src_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005709 context->UpdateAccessState(*src_image, SYNC_RESOLVE_TRANSFER_READ, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005710 resolve_region.srcSubresource, resolve_region.srcOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005711 }
5712 if (dst_image) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07005713 context->UpdateAccessState(*dst_image, SYNC_RESOLVE_TRANSFER_WRITE, SyncOrdering::kNonAttachment,
John Zulauf8e3c3e92021-01-06 11:19:36 -07005714 resolve_region.dstSubresource, resolve_region.dstOffset, resolve_region.extent, tag);
Jeff Leger178b1e52020-10-05 12:22:23 -04005715 }
5716 }
5717}
5718
Tony-LunarG562fc102021-11-12 13:58:35 -07005719void SyncValidator::PreCallRecordCmdResolveImage2KHR(VkCommandBuffer commandBuffer,
5720 const VkResolveImageInfo2KHR *pResolveImageInfo) {
5721 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2KHR);
5722}
5723
5724void SyncValidator::PreCallRecordCmdResolveImage2(VkCommandBuffer commandBuffer, const VkResolveImageInfo2 *pResolveImageInfo) {
5725 RecordCmdResolveImage2(commandBuffer, pResolveImageInfo, CMD_RESOLVEIMAGE2);
5726}
5727
locke-lunarge1a67022020-04-29 00:15:36 -06005728bool SyncValidator::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5729 VkDeviceSize dataSize, const void *pData) const {
5730 bool skip = false;
5731 const auto *cb_access_context = GetAccessContext(commandBuffer);
5732 assert(cb_access_context);
5733 if (!cb_access_context) return skip;
5734
5735 const auto *context = cb_access_context->GetCurrentAccessContext();
5736 assert(context);
5737 if (!context) return skip;
5738
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005739 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005740
5741 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005742 // VK_WHOLE_SIZE not allowed
5743 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005744 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunarge1a67022020-04-29 00:15:36 -06005745 if (hazard.hazard) {
John Zulauf1dae9192020-06-16 15:46:44 -06005746 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
John Zulauf59e25072020-07-17 10:55:21 -06005747 "vkCmdUpdateBuffer: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005748 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunarge1a67022020-04-29 00:15:36 -06005749 }
5750 }
5751 return skip;
5752}
5753
5754void SyncValidator::PreCallRecordCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset,
5755 VkDeviceSize dataSize, const void *pData) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005756 StateTracker::PreCallRecordCmdUpdateBuffer(commandBuffer, dstBuffer, dstOffset, dataSize, pData);
locke-lunarge1a67022020-04-29 00:15:36 -06005757 auto *cb_access_context = GetAccessContext(commandBuffer);
5758 assert(cb_access_context);
5759 const auto tag = cb_access_context->NextCommandTag(CMD_UPDATEBUFFER);
5760 auto *context = cb_access_context->GetCurrentAccessContext();
5761 assert(context);
5762
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005763 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunarge1a67022020-04-29 00:15:36 -06005764
5765 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005766 // VK_WHOLE_SIZE not allowed
5767 const ResourceAccessRange range = MakeRange(dstOffset, dataSize);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005768 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunarge1a67022020-04-29 00:15:36 -06005769 }
5770}
locke-lunargff255f92020-05-13 18:53:52 -06005771
5772bool SyncValidator::PreCallValidateCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5773 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
5774 bool skip = false;
5775 const auto *cb_access_context = GetAccessContext(commandBuffer);
5776 assert(cb_access_context);
5777 if (!cb_access_context) return skip;
5778
5779 const auto *context = cb_access_context->GetCurrentAccessContext();
5780 assert(context);
5781 if (!context) return skip;
5782
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005783 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005784
5785 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005786 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005787 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
locke-lunargff255f92020-05-13 18:53:52 -06005788 if (hazard.hazard) {
John Zulauf59e25072020-07-17 10:55:21 -06005789 skip |=
5790 LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
5791 "vkCmdWriteBufferMarkerAMD: Hazard %s for dstBuffer %s. Access info %s.", string_SyncHazard(hazard.hazard),
John Zulauf397e68b2022-04-19 11:44:07 -06005792 report_data->FormatHandle(dstBuffer).c_str(), cb_access_context->FormatHazard(hazard).c_str());
locke-lunargff255f92020-05-13 18:53:52 -06005793 }
5794 }
5795 return skip;
5796}
5797
5798void SyncValidator::PreCallRecordCmdWriteBufferMarkerAMD(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage,
5799 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
locke-lunarg8ec19162020-06-16 18:48:34 -06005800 StateTracker::PreCallRecordCmdWriteBufferMarkerAMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
locke-lunargff255f92020-05-13 18:53:52 -06005801 auto *cb_access_context = GetAccessContext(commandBuffer);
5802 assert(cb_access_context);
5803 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
5804 auto *context = cb_access_context->GetCurrentAccessContext();
5805 assert(context);
5806
Jeremy Gebbenf4449392022-01-28 10:09:10 -07005807 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
locke-lunargff255f92020-05-13 18:53:52 -06005808
5809 if (dst_buffer) {
John Zulauf3e86bf02020-09-12 10:47:57 -06005810 const ResourceAccessRange range = MakeRange(dstOffset, 4);
Jeremy Gebben40a22942020-12-22 14:22:06 -07005811 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
locke-lunargff255f92020-05-13 18:53:52 -06005812 }
5813}
John Zulauf49beb112020-11-04 16:06:31 -07005814
5815bool SyncValidator::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const {
5816 bool skip = false;
5817 const auto *cb_context = GetAccessContext(commandBuffer);
5818 assert(cb_context);
5819 if (!cb_context) return skip;
John Zulaufe0757ba2022-06-10 16:51:45 -06005820 const auto *access_context = cb_context->GetCurrentAccessContext();
5821 assert(access_context);
5822 if (!access_context) return skip;
John Zulauf49beb112020-11-04 16:06:31 -07005823
John Zulaufe0757ba2022-06-10 16:51:45 -06005824 SyncOpSetEvent set_event_op(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask, nullptr);
John Zulauf6ce24372021-01-30 05:56:25 -07005825 return set_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005826}
5827
5828void SyncValidator::PostCallRecordCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5829 StateTracker::PostCallRecordCmdSetEvent(commandBuffer, event, stageMask);
5830 auto *cb_context = GetAccessContext(commandBuffer);
5831 assert(cb_context);
5832 if (!cb_context) return;
John Zulaufe0757ba2022-06-10 16:51:45 -06005833
5834 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask,
5835 cb_context->GetCurrentAccessContext());
John Zulauf49beb112020-11-04 16:06:31 -07005836}
5837
John Zulauf4edde622021-02-15 08:54:50 -07005838bool SyncValidator::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5839 const VkDependencyInfoKHR *pDependencyInfo) const {
5840 bool skip = false;
5841 const auto *cb_context = GetAccessContext(commandBuffer);
5842 assert(cb_context);
5843 if (!cb_context || !pDependencyInfo) return skip;
5844
John Zulaufe0757ba2022-06-10 16:51:45 -06005845 const auto *access_context = cb_context->GetCurrentAccessContext();
5846 assert(access_context);
5847 if (!access_context) return skip;
5848
5849 SyncOpSetEvent set_event_op(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
John Zulauf4edde622021-02-15 08:54:50 -07005850 return set_event_op.Validate(*cb_context);
5851}
5852
Tony-LunarGc43525f2021-11-15 16:12:38 -07005853bool SyncValidator::PreCallValidateCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5854 const VkDependencyInfo *pDependencyInfo) const {
5855 bool skip = false;
5856 const auto *cb_context = GetAccessContext(commandBuffer);
5857 assert(cb_context);
5858 if (!cb_context || !pDependencyInfo) return skip;
5859
John Zulaufe0757ba2022-06-10 16:51:45 -06005860 SyncOpSetEvent set_event_op(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo, nullptr);
Tony-LunarGc43525f2021-11-15 16:12:38 -07005861 return set_event_op.Validate(*cb_context);
5862}
5863
John Zulauf4edde622021-02-15 08:54:50 -07005864void SyncValidator::PostCallRecordCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5865 const VkDependencyInfoKHR *pDependencyInfo) {
5866 StateTracker::PostCallRecordCmdSetEvent2KHR(commandBuffer, event, pDependencyInfo);
5867 auto *cb_context = GetAccessContext(commandBuffer);
5868 assert(cb_context);
5869 if (!cb_context || !pDependencyInfo) return;
5870
John Zulaufe0757ba2022-06-10 16:51:45 -06005871 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5872 cb_context->GetCurrentAccessContext());
John Zulauf4edde622021-02-15 08:54:50 -07005873}
5874
Tony-LunarGc43525f2021-11-15 16:12:38 -07005875void SyncValidator::PostCallRecordCmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5876 const VkDependencyInfo *pDependencyInfo) {
5877 StateTracker::PostCallRecordCmdSetEvent2(commandBuffer, event, pDependencyInfo);
5878 auto *cb_context = GetAccessContext(commandBuffer);
5879 assert(cb_context);
5880 if (!cb_context || !pDependencyInfo) return;
5881
John Zulaufe0757ba2022-06-10 16:51:45 -06005882 cb_context->RecordSyncOp<SyncOpSetEvent>(CMD_SETEVENT2, *this, cb_context->GetQueueFlags(), event, *pDependencyInfo,
5883 cb_context->GetCurrentAccessContext());
Tony-LunarGc43525f2021-11-15 16:12:38 -07005884}
5885
John Zulauf49beb112020-11-04 16:06:31 -07005886bool SyncValidator::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event,
5887 VkPipelineStageFlags stageMask) const {
5888 bool skip = false;
5889 const auto *cb_context = GetAccessContext(commandBuffer);
5890 assert(cb_context);
5891 if (!cb_context) return skip;
5892
John Zulauf36ef9282021-02-02 11:47:24 -07005893 SyncOpResetEvent reset_event_op(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf6ce24372021-01-30 05:56:25 -07005894 return reset_event_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005895}
5896
5897void SyncValidator::PostCallRecordCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) {
5898 StateTracker::PostCallRecordCmdResetEvent(commandBuffer, event, stageMask);
5899 auto *cb_context = GetAccessContext(commandBuffer);
5900 assert(cb_context);
5901 if (!cb_context) return;
5902
John Zulauf1bf30522021-09-03 15:39:06 -06005903 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf49beb112020-11-04 16:06:31 -07005904}
5905
John Zulauf4edde622021-02-15 08:54:50 -07005906bool SyncValidator::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5907 VkPipelineStageFlags2KHR stageMask) const {
5908 bool skip = false;
5909 const auto *cb_context = GetAccessContext(commandBuffer);
5910 assert(cb_context);
5911 if (!cb_context) return skip;
5912
5913 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
5914 return reset_event_op.Validate(*cb_context);
5915}
5916
Tony-LunarGa2662db2021-11-16 07:26:24 -07005917bool SyncValidator::PreCallValidateCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event,
5918 VkPipelineStageFlags2 stageMask) const {
5919 bool skip = false;
5920 const auto *cb_context = GetAccessContext(commandBuffer);
5921 assert(cb_context);
5922 if (!cb_context) return skip;
5923
5924 SyncOpResetEvent reset_event_op(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5925 return reset_event_op.Validate(*cb_context);
5926}
5927
John Zulauf4edde622021-02-15 08:54:50 -07005928void SyncValidator::PostCallRecordCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event,
5929 VkPipelineStageFlags2KHR stageMask) {
5930 StateTracker::PostCallRecordCmdResetEvent2KHR(commandBuffer, event, stageMask);
5931 auto *cb_context = GetAccessContext(commandBuffer);
5932 assert(cb_context);
5933 if (!cb_context) return;
5934
John Zulauf1bf30522021-09-03 15:39:06 -06005935 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2KHR, *this, cb_context->GetQueueFlags(), event, stageMask);
John Zulauf4edde622021-02-15 08:54:50 -07005936}
5937
Tony-LunarGa2662db2021-11-16 07:26:24 -07005938void SyncValidator::PostCallRecordCmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2 stageMask) {
5939 StateTracker::PostCallRecordCmdResetEvent2(commandBuffer, event, stageMask);
5940 auto *cb_context = GetAccessContext(commandBuffer);
5941 assert(cb_context);
5942 if (!cb_context) return;
5943
5944 cb_context->RecordSyncOp<SyncOpResetEvent>(CMD_RESETEVENT2, *this, cb_context->GetQueueFlags(), event, stageMask);
5945}
5946
John Zulauf49beb112020-11-04 16:06:31 -07005947bool SyncValidator::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5948 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5949 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5950 uint32_t bufferMemoryBarrierCount,
5951 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5952 uint32_t imageMemoryBarrierCount,
5953 const VkImageMemoryBarrier *pImageMemoryBarriers) const {
5954 bool skip = false;
5955 const auto *cb_context = GetAccessContext(commandBuffer);
5956 assert(cb_context);
5957 if (!cb_context) return skip;
5958
John Zulauf36ef9282021-02-02 11:47:24 -07005959 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask,
5960 dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount,
5961 pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufd5115702021-01-18 12:34:33 -07005962 return wait_events_op.Validate(*cb_context);
John Zulauf49beb112020-11-04 16:06:31 -07005963}
5964
5965void SyncValidator::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5966 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
5967 uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers,
5968 uint32_t bufferMemoryBarrierCount,
5969 const VkBufferMemoryBarrier *pBufferMemoryBarriers,
5970 uint32_t imageMemoryBarrierCount,
5971 const VkImageMemoryBarrier *pImageMemoryBarriers) {
5972 StateTracker::PostCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
5973 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers,
5974 imageMemoryBarrierCount, pImageMemoryBarriers);
5975
5976 auto *cb_context = GetAccessContext(commandBuffer);
5977 assert(cb_context);
5978 if (!cb_context) return;
5979
John Zulauf1bf30522021-09-03 15:39:06 -06005980 cb_context->RecordSyncOp<SyncOpWaitEvents>(
John Zulauf610e28c2021-08-03 17:46:23 -06005981 CMD_WAITEVENTS, *this, cb_context->GetQueueFlags(), eventCount, pEvents, srcStageMask, dstStageMask, memoryBarrierCount,
John Zulauf1bf30522021-09-03 15:39:06 -06005982 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulauf4a6105a2020-11-17 15:11:05 -07005983}
5984
John Zulauf4edde622021-02-15 08:54:50 -07005985bool SyncValidator::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5986 const VkDependencyInfoKHR *pDependencyInfos) const {
5987 bool skip = false;
5988 const auto *cb_context = GetAccessContext(commandBuffer);
5989 assert(cb_context);
5990 if (!cb_context) return skip;
5991
5992 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
5993 skip |= wait_events_op.Validate(*cb_context);
5994 return skip;
5995}
5996
5997void SyncValidator::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
5998 const VkDependencyInfoKHR *pDependencyInfos) {
5999 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6000
6001 auto *cb_context = GetAccessContext(commandBuffer);
6002 assert(cb_context);
6003 if (!cb_context) return;
6004
John Zulauf1bf30522021-09-03 15:39:06 -06006005 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2KHR, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6006 pDependencyInfos);
John Zulauf4edde622021-02-15 08:54:50 -07006007}
6008
Tony-LunarG1364cf52021-11-17 16:10:11 -07006009bool SyncValidator::PreCallValidateCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6010 const VkDependencyInfo *pDependencyInfos) const {
6011 bool skip = false;
6012 const auto *cb_context = GetAccessContext(commandBuffer);
6013 assert(cb_context);
6014 if (!cb_context) return skip;
6015
6016 SyncOpWaitEvents wait_events_op(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents, pDependencyInfos);
6017 skip |= wait_events_op.Validate(*cb_context);
6018 return skip;
6019}
6020
6021void SyncValidator::PostCallRecordCmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents,
6022 const VkDependencyInfo *pDependencyInfos) {
6023 StateTracker::PostCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos);
6024
6025 auto *cb_context = GetAccessContext(commandBuffer);
6026 assert(cb_context);
6027 if (!cb_context) return;
6028
6029 cb_context->RecordSyncOp<SyncOpWaitEvents>(CMD_WAITEVENTS2, *this, cb_context->GetQueueFlags(), eventCount, pEvents,
6030 pDependencyInfos);
6031}
6032
John Zulauf4a6105a2020-11-17 15:11:05 -07006033void SyncEventState::ResetFirstScope() {
John Zulaufe0757ba2022-06-10 16:51:45 -06006034 first_scope.reset();
Jeremy Gebben9893daf2021-01-04 10:40:50 -07006035 scope = SyncExecScope();
John Zulauf78b1f892021-09-20 15:02:09 -06006036 first_scope_tag = 0;
John Zulauf4a6105a2020-11-17 15:11:05 -07006037}
6038
6039// Keep the "ignore this event" logic in same place for ValidateWait and RecordWait to use
sjfricke0bea06e2022-06-05 09:22:26 +09006040SyncEventState::IgnoreReason SyncEventState::IsIgnoredByWait(CMD_TYPE cmd_type, VkPipelineStageFlags2KHR srcStageMask) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006041 IgnoreReason reason = NotIgnored;
6042
sjfricke0bea06e2022-06-05 09:22:26 +09006043 if ((CMD_WAITEVENTS2KHR == cmd_type || CMD_WAITEVENTS2 == cmd_type) && (CMD_SETEVENT == last_command)) {
John Zulauf4edde622021-02-15 08:54:50 -07006044 reason = SetVsWait2;
6045 } else if ((last_command == CMD_RESETEVENT || last_command == CMD_RESETEVENT2KHR) && !HasBarrier(0U, 0U)) {
6046 reason = (last_command == CMD_RESETEVENT) ? ResetWaitRace : Reset2WaitRace;
John Zulauf4a6105a2020-11-17 15:11:05 -07006047 } else if (unsynchronized_set) {
6048 reason = SetRace;
John Zulaufe0757ba2022-06-10 16:51:45 -06006049 } else if (first_scope) {
Jeremy Gebben40a22942020-12-22 14:22:06 -07006050 const VkPipelineStageFlags2KHR missing_bits = scope.mask_param & ~srcStageMask;
John Zulaufe0757ba2022-06-10 16:51:45 -06006051 // Note it is the "not missing bits" path that is the only "NotIgnored" path
John Zulauf4a6105a2020-11-17 15:11:05 -07006052 if (missing_bits) reason = MissingStageBits;
John Zulaufe0757ba2022-06-10 16:51:45 -06006053 } else {
6054 reason = MissingSetEvent;
John Zulauf4a6105a2020-11-17 15:11:05 -07006055 }
6056
6057 return reason;
6058}
6059
Jeremy Gebben40a22942020-12-22 14:22:06 -07006060bool SyncEventState::HasBarrier(VkPipelineStageFlags2KHR stageMask, VkPipelineStageFlags2KHR exec_scope_arg) const {
John Zulauf4a6105a2020-11-17 15:11:05 -07006061 bool has_barrier = (last_command == CMD_NONE) || (stageMask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ||
6062 (barriers & exec_scope_arg) || (barriers & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
6063 return has_barrier;
John Zulauf49beb112020-11-04 16:06:31 -07006064}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006065
sjfricke0bea06e2022-06-05 09:22:26 +09006066SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulauf36ef9282021-02-02 11:47:24 -07006067 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6068 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006069 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6070 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6071 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006072 : SyncOpBase(cmd_type), barriers_(1) {
John Zulauf4edde622021-02-15 08:54:50 -07006073 auto &barrier_set = barriers_[0];
6074 barrier_set.dependency_flags = dependencyFlags;
6075 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, srcStageMask);
6076 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, dstStageMask);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006077 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
John Zulauf4edde622021-02-15 08:54:50 -07006078 barrier_set.MakeMemoryBarriers(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags, memoryBarrierCount,
6079 pMemoryBarriers);
6080 barrier_set.MakeBufferMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6081 bufferMemoryBarrierCount, pBufferMemoryBarriers);
6082 barrier_set.MakeImageMemoryBarriers(sync_state, barrier_set.src_exec_scope, barrier_set.dst_exec_scope, dependencyFlags,
6083 imageMemoryBarrierCount, pImageMemoryBarriers);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006084}
6085
sjfricke0bea06e2022-06-05 09:22:26 +09006086SyncOpBarriers::SyncOpBarriers(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, uint32_t event_count,
John Zulauf4edde622021-02-15 08:54:50 -07006087 const VkDependencyInfoKHR *dep_infos)
sjfricke0bea06e2022-06-05 09:22:26 +09006088 : SyncOpBase(cmd_type), barriers_(event_count) {
John Zulauf4edde622021-02-15 08:54:50 -07006089 for (uint32_t i = 0; i < event_count; i++) {
6090 const auto &dep_info = dep_infos[i];
6091 auto &barrier_set = barriers_[i];
6092 barrier_set.dependency_flags = dep_info.dependencyFlags;
6093 auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info);
6094 barrier_set.src_exec_scope = SyncExecScope::MakeSrc(queue_flags, stage_masks.src);
6095 barrier_set.dst_exec_scope = SyncExecScope::MakeDst(queue_flags, stage_masks.dst);
6096 // Translate the API parameters into structures SyncVal understands directly, and dehandle for safer/faster replay.
6097 barrier_set.MakeMemoryBarriers(queue_flags, dep_info.dependencyFlags, dep_info.memoryBarrierCount,
6098 dep_info.pMemoryBarriers);
6099 barrier_set.MakeBufferMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.bufferMemoryBarrierCount,
6100 dep_info.pBufferMemoryBarriers);
6101 barrier_set.MakeImageMemoryBarriers(sync_state, queue_flags, dep_info.dependencyFlags, dep_info.imageMemoryBarrierCount,
6102 dep_info.pImageMemoryBarriers);
6103 }
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006104}
6105
sjfricke0bea06e2022-06-05 09:22:26 +09006106SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
John Zulaufd5115702021-01-18 12:34:33 -07006107 VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask,
6108 VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount,
6109 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6110 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6111 const VkImageMemoryBarrier *pImageMemoryBarriers)
sjfricke0bea06e2022-06-05 09:22:26 +09006112 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount,
6113 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6114 pImageMemoryBarriers) {}
John Zulaufd5115702021-01-18 12:34:33 -07006115
sjfricke0bea06e2022-06-05 09:22:26 +09006116SyncOpPipelineBarrier::SyncOpPipelineBarrier(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006117 const VkDependencyInfoKHR &dep_info)
sjfricke0bea06e2022-06-05 09:22:26 +09006118 : SyncOpBarriers(cmd_type, sync_state, queue_flags, 1, &dep_info) {}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006119
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006120bool SyncOpPipelineBarrier::Validate(const CommandBufferAccessContext &cb_context) const {
6121 bool skip = false;
6122 const auto *context = cb_context.GetCurrentAccessContext();
6123 assert(context);
6124 if (!context) return skip;
John Zulauf6fdf3d02021-03-05 16:50:47 -07006125 assert(barriers_.size() == 1); // PipelineBarriers only support a single barrier set.
6126
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006127 // Validate Image Layout transitions
John Zulauf6fdf3d02021-03-05 16:50:47 -07006128 const auto &barrier_set = barriers_[0];
6129 for (const auto &image_barrier : barrier_set.image_memory_barriers) {
6130 if (image_barrier.new_layout == image_barrier.old_layout) continue; // Only interested in layout transitions at this point.
6131 const auto *image_state = image_barrier.image.get();
6132 if (!image_state) continue;
6133 const auto hazard = context->DetectImageBarrierHazard(image_barrier);
6134 if (hazard.hazard) {
6135 // PHASE1 TODO -- add tag information to log msg when useful.
6136 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006137 const auto image_handle = image_state->image();
John Zulauf6fdf3d02021-03-05 16:50:47 -07006138 skip |= sync_state.LogError(image_handle, string_SyncHazardVUID(hazard.hazard),
6139 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6140 string_SyncHazard(hazard.hazard), image_barrier.index,
6141 sync_state.report_data->FormatHandle(image_handle).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006142 cb_context.FormatHazard(hazard).c_str());
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006143 }
6144 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006145 return skip;
6146}
6147
John Zulaufd5115702021-01-18 12:34:33 -07006148struct SyncOpPipelineBarrierFunctorFactory {
6149 using BarrierOpFunctor = PipelineBarrierOp;
6150 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6151 using GlobalBarrierOpFunctor = PipelineBarrierOp;
6152 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6153 using BufferRange = ResourceAccessRange;
6154 using ImageRange = subresource_adapter::ImageRangeGenerator;
6155 using GlobalRange = ResourceAccessRange;
6156
John Zulauf00119522022-05-23 19:07:42 -06006157 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier, bool layout_transition) const {
6158 return ApplyFunctor(BarrierOpFunctor(queue_id, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006159 }
John Zulauf14940722021-04-12 15:19:02 -06006160 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006161 return GlobalApplyFunctor(true /* resolve */, size_hint, tag);
6162 }
John Zulauf00119522022-05-23 19:07:42 -06006163 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(QueueId queue_id, const SyncBarrier &barrier) const {
6164 return GlobalBarrierOpFunctor(queue_id, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006165 }
6166
6167 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range) const {
6168 if (!SimpleBinding(buffer)) return ResourceAccessRange();
6169 const auto base_address = ResourceBaseAddress(buffer);
6170 return (range + base_address);
6171 }
John Zulauf110413c2021-03-20 05:38:38 -06006172 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulauf264cce02021-02-05 14:40:47 -07006173 if (!SimpleBinding(image)) return subresource_adapter::ImageRangeGenerator();
John Zulaufd5115702021-01-18 12:34:33 -07006174
6175 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006176 subresource_adapter::ImageRangeGenerator range_gen(*image.fragment_encoder.get(), subresource_range, base_address, false);
John Zulaufd5115702021-01-18 12:34:33 -07006177 return range_gen;
6178 }
6179 GlobalRange MakeGlobalRangeGen(AccessAddressType) const { return kFullRange; }
6180};
6181
6182template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006183void SyncOpBarriers::ApplyBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6184 const ResourceUsageTag tag, AccessContext *context) {
John Zulaufd5115702021-01-18 12:34:33 -07006185 for (const auto &barrier : barriers) {
6186 const auto *state = barrier.GetState();
6187 if (state) {
6188 auto *const accesses = &context->GetAccessStateMap(GetAccessAddressType(*state));
John Zulauf00119522022-05-23 19:07:42 -06006189 auto update_action = factory.MakeApplyFunctor(queue_id, barrier.barrier, barrier.IsLayoutTransition());
John Zulaufd5115702021-01-18 12:34:33 -07006190 auto range_gen = factory.MakeRangeGen(*state, barrier.Range());
6191 UpdateMemoryAccessState(accesses, update_action, &range_gen);
6192 }
6193 }
6194}
6195
6196template <typename Barriers, typename FunctorFactory>
John Zulauf00119522022-05-23 19:07:42 -06006197void SyncOpBarriers::ApplyGlobalBarriers(const Barriers &barriers, const FunctorFactory &factory, const QueueId queue_id,
6198 const ResourceUsageTag tag, AccessContext *access_context) {
John Zulaufd5115702021-01-18 12:34:33 -07006199 auto barriers_functor = factory.MakeGlobalApplyFunctor(barriers.size(), tag);
6200 for (const auto &barrier : barriers) {
John Zulauf00119522022-05-23 19:07:42 -06006201 barriers_functor.EmplaceBack(factory.MakeGlobalBarrierOpFunctor(queue_id, barrier));
John Zulaufd5115702021-01-18 12:34:33 -07006202 }
6203 for (const auto address_type : kAddressTypes) {
6204 auto range_gen = factory.MakeGlobalRangeGen(address_type);
6205 UpdateMemoryAccessState(&(access_context->GetAccessStateMap(address_type)), barriers_functor, &range_gen);
6206 }
6207}
6208
John Zulauf8eda1562021-04-13 17:06:41 -06006209ResourceUsageTag SyncOpPipelineBarrier::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006210 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006211 ReplayRecord(*cb_context, tag);
John Zulauf4fa68462021-04-26 21:04:22 -06006212 return tag;
6213}
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006214
John Zulauf0223f142022-07-06 09:05:39 -06006215void SyncOpPipelineBarrier::ReplayRecord(CommandExecutionContext &exec_context, const ResourceUsageTag tag) const {
John Zulauf8eda1562021-04-13 17:06:41 -06006216 SyncOpPipelineBarrierFunctorFactory factory;
John Zulauf4edde622021-02-15 08:54:50 -07006217 // Pipeline barriers only have a single barrier set, unlike WaitEvents2
6218 assert(barriers_.size() == 1);
6219 const auto &barrier_set = barriers_[0];
John Zulauf0223f142022-07-06 09:05:39 -06006220 if (!exec_context.ValidForSyncOps()) return;
6221
6222 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6223 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6224 const auto queue_id = exec_context.GetQueueId();
John Zulauf00119522022-05-23 19:07:42 -06006225 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6226 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6227 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulauf4edde622021-02-15 08:54:50 -07006228 if (barrier_set.single_exec_scope) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006229 events_context->ApplyBarrier(barrier_set.src_exec_scope, barrier_set.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006230 } else {
6231 for (const auto &barrier : barrier_set.memory_barriers) {
John Zulaufe0757ba2022-06-10 16:51:45 -06006232 events_context->ApplyBarrier(barrier.src_exec_scope, barrier.dst_exec_scope, tag);
John Zulauf4edde622021-02-15 08:54:50 -07006233 }
6234 }
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006235}
6236
John Zulauf8eda1562021-04-13 17:06:41 -06006237bool SyncOpPipelineBarrier::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006238 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf4fa68462021-04-26 21:04:22 -06006239 // No Validation for replay, as the layout transition accesses are checked directly, and the src*Mask ordering is captured
6240 // with first access information.
John Zulauf8eda1562021-04-13 17:06:41 -06006241 return false;
6242}
6243
John Zulauf4edde622021-02-15 08:54:50 -07006244void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(const SyncExecScope &src, const SyncExecScope &dst,
6245 VkDependencyFlags dependency_flags, uint32_t memory_barrier_count,
6246 const VkMemoryBarrier *barriers) {
6247 memory_barriers.reserve(std::max<uint32_t>(1, memory_barrier_count));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006248 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006249 const auto &barrier = barriers[barrier_index];
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006250 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006251 memory_barriers.emplace_back(sync_barrier);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006252 }
6253 if (0 == memory_barrier_count) {
6254 // If there are no global memory barriers, force an exec barrier
John Zulauf4edde622021-02-15 08:54:50 -07006255 memory_barriers.emplace_back(SyncBarrier(src, dst));
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006256 }
John Zulauf4edde622021-02-15 08:54:50 -07006257 single_exec_scope = true;
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006258}
6259
John Zulauf4edde622021-02-15 08:54:50 -07006260void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6261 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6262 uint32_t barrier_count, const VkBufferMemoryBarrier *barriers) {
6263 buffer_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006264 for (uint32_t index = 0; index < barrier_count; index++) {
6265 const auto &barrier = barriers[index];
Jeremy Gebben9f537102021-10-05 16:37:12 -06006266 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006267 if (buffer) {
6268 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6269 const auto range = MakeRange(barrier.offset, barrier_size);
6270 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006271 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006272 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006273 buffer_memory_barriers.emplace_back();
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006274 }
6275 }
6276}
6277
John Zulauf4edde622021-02-15 08:54:50 -07006278void SyncOpBarriers::BarrierSet::MakeMemoryBarriers(VkQueueFlags queue_flags, VkDependencyFlags dependency_flags,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006279 uint32_t memory_barrier_count, const VkMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006280 memory_barriers.reserve(memory_barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006281 for (uint32_t barrier_index = 0; barrier_index < memory_barrier_count; barrier_index++) {
John Zulauf4edde622021-02-15 08:54:50 -07006282 const auto &barrier = barriers[barrier_index];
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006283 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6284 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
6285 SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006286 memory_barriers.emplace_back(sync_barrier);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006287 }
John Zulauf4edde622021-02-15 08:54:50 -07006288 single_exec_scope = false;
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006289}
6290
John Zulauf4edde622021-02-15 08:54:50 -07006291void SyncOpBarriers::BarrierSet::MakeBufferMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6292 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006293 const VkBufferMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006294 buffer_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006295 for (uint32_t index = 0; index < barrier_count; index++) {
6296 const auto &barrier = barriers[index];
6297 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6298 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebben9f537102021-10-05 16:37:12 -06006299 auto buffer = sync_state.Get<BUFFER_STATE>(barrier.buffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006300 if (buffer) {
6301 const auto barrier_size = GetBufferWholeSize(*buffer, barrier.offset, barrier.size);
6302 const auto range = MakeRange(barrier.offset, barrier_size);
6303 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006304 buffer_memory_barriers.emplace_back(buffer, sync_barrier, range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006305 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006306 buffer_memory_barriers.emplace_back();
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006307 }
6308 }
6309}
6310
John Zulauf4edde622021-02-15 08:54:50 -07006311void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, const SyncExecScope &src,
6312 const SyncExecScope &dst, VkDependencyFlags dependencyFlags,
6313 uint32_t barrier_count, const VkImageMemoryBarrier *barriers) {
6314 image_memory_barriers.reserve(barrier_count);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006315 for (uint32_t index = 0; index < barrier_count; index++) {
6316 const auto &barrier = barriers[index];
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006317 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006318 if (image) {
6319 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6320 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006321 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006322 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006323 image_memory_barriers.emplace_back();
6324 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
John Zulaufe7f6a5e2021-01-16 14:31:18 -07006325 }
6326 }
6327}
John Zulaufd5115702021-01-18 12:34:33 -07006328
John Zulauf4edde622021-02-15 08:54:50 -07006329void SyncOpBarriers::BarrierSet::MakeImageMemoryBarriers(const SyncValidator &sync_state, VkQueueFlags queue_flags,
6330 VkDependencyFlags dependencyFlags, uint32_t barrier_count,
Tony-LunarG3f6eceb2021-11-18 14:34:49 -07006331 const VkImageMemoryBarrier2 *barriers) {
John Zulauf4edde622021-02-15 08:54:50 -07006332 image_memory_barriers.reserve(barrier_count);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006333 for (uint32_t index = 0; index < barrier_count; index++) {
6334 const auto &barrier = barriers[index];
6335 auto src = SyncExecScope::MakeSrc(queue_flags, barrier.srcStageMask);
6336 auto dst = SyncExecScope::MakeDst(queue_flags, barrier.dstStageMask);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006337 auto image = sync_state.Get<IMAGE_STATE>(barrier.image);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006338 if (image) {
6339 auto subresource_range = NormalizeSubresourceRange(image->createInfo, barrier.subresourceRange);
6340 const SyncBarrier sync_barrier(barrier, src, dst);
John Zulauf4edde622021-02-15 08:54:50 -07006341 image_memory_barriers.emplace_back(image, index, sync_barrier, barrier.oldLayout, barrier.newLayout, subresource_range);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006342 } else {
John Zulauf4edde622021-02-15 08:54:50 -07006343 image_memory_barriers.emplace_back();
6344 image_memory_barriers.back().index = index; // Just in case we're interested in the ones we skipped.
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006345 }
6346 }
6347}
6348
sjfricke0bea06e2022-06-05 09:22:26 +09006349SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6350 uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask,
6351 VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount,
6352 const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount,
6353 const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount,
6354 const VkImageMemoryBarrier *pImageMemoryBarriers)
6355 : SyncOpBarriers(cmd_type, sync_state, queue_flags, srcStageMask, dstStageMask, VkDependencyFlags(0U), memoryBarrierCount,
John Zulaufd5115702021-01-18 12:34:33 -07006356 pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount,
6357 pImageMemoryBarriers) {
John Zulauf669dfd52021-01-27 17:15:28 -07006358 MakeEventsList(sync_state, eventCount, pEvents);
John Zulaufd5115702021-01-18 12:34:33 -07006359}
6360
sjfricke0bea06e2022-06-05 09:22:26 +09006361SyncOpWaitEvents::SyncOpWaitEvents(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags,
6362 uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfo)
6363 : SyncOpBarriers(cmd_type, sync_state, queue_flags, eventCount, pDependencyInfo) {
John Zulauf4edde622021-02-15 08:54:50 -07006364 MakeEventsList(sync_state, eventCount, pEvents);
6365 assert(events_.size() == barriers_.size()); // Just so nobody gets clever and decides to cull the event or barrier arrays
6366}
6367
John Zulauf610e28c2021-08-03 17:46:23 -06006368const char *const SyncOpWaitEvents::kIgnored = "Wait operation is ignored for this event.";
6369
John Zulaufd5115702021-01-18 12:34:33 -07006370bool SyncOpWaitEvents::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulaufd5115702021-01-18 12:34:33 -07006371 bool skip = false;
6372 const auto &sync_state = cb_context.GetSyncState();
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006373 const auto command_buffer_handle = cb_context.GetCBState().commandBuffer();
John Zulaufd5115702021-01-18 12:34:33 -07006374
John Zulauf610e28c2021-08-03 17:46:23 -06006375 // This is only interesting at record and not replay (Execute/Submit) time.
John Zulauf4edde622021-02-15 08:54:50 -07006376 for (size_t barrier_set_index = 0; barrier_set_index < barriers_.size(); barrier_set_index++) {
6377 const auto &barrier_set = barriers_[barrier_set_index];
6378 if (barrier_set.single_exec_scope) {
6379 if (barrier_set.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6380 const std::string vuid = std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6381 skip = sync_state.LogInfo(command_buffer_handle, vuid,
6382 "%s, srcStageMask includes %s, unsupported by synchronization validation.", CmdName(),
6383 string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT));
6384 } else {
6385 const auto &barriers = barrier_set.memory_barriers;
6386 for (size_t barrier_index = 0; barrier_index < barriers.size(); barrier_index++) {
6387 const auto &barrier = barriers[barrier_index];
6388 if (barrier.src_exec_scope.mask_param & VK_PIPELINE_STAGE_HOST_BIT) {
6389 const std::string vuid =
6390 std::string("SYNC-") + std::string(CmdName()) + std::string("-hostevent-unsupported");
6391 skip =
6392 sync_state.LogInfo(command_buffer_handle, vuid,
6393 "%s, srcStageMask %s of %s %zu, %s %zu, unsupported by synchronization validation.",
6394 CmdName(), string_VkPipelineStageFlagBits(VK_PIPELINE_STAGE_HOST_BIT),
6395 "pDependencyInfo", barrier_set_index, "pMemoryBarriers", barrier_index);
6396 }
6397 }
6398 }
6399 }
John Zulaufd5115702021-01-18 12:34:33 -07006400 }
6401
John Zulauf610e28c2021-08-03 17:46:23 -06006402 // The rest is common to record time and replay time.
6403 skip |= DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6404 return skip;
6405}
6406
John Zulaufbb890452021-12-14 11:30:18 -07006407bool SyncOpWaitEvents::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006408 bool skip = false;
John Zulaufbb890452021-12-14 11:30:18 -07006409 const auto &sync_state = exec_context.GetSyncState();
John Zulaufe0757ba2022-06-10 16:51:45 -06006410 const QueueId queue_id = exec_context.GetQueueId();
John Zulauf610e28c2021-08-03 17:46:23 -06006411
Jeremy Gebben40a22942020-12-22 14:22:06 -07006412 VkPipelineStageFlags2KHR event_stage_masks = 0U;
John Zulauf4edde622021-02-15 08:54:50 -07006413 VkPipelineStageFlags2KHR barrier_mask_params = 0U;
John Zulaufd5115702021-01-18 12:34:33 -07006414 bool events_not_found = false;
John Zulaufbb890452021-12-14 11:30:18 -07006415 const auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf669dfd52021-01-27 17:15:28 -07006416 assert(events_context);
John Zulauf4edde622021-02-15 08:54:50 -07006417 size_t barrier_set_index = 0;
6418 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
John Zulauf78394fc2021-07-12 15:41:40 -06006419 for (const auto &event : events_) {
6420 const auto *sync_event = events_context->Get(event.get());
6421 const auto &barrier_set = barriers_[barrier_set_index];
6422 if (!sync_event) {
6423 // NOTE PHASE2: This is where we'll need queue submit time validation to come back and check the srcStageMask bits
6424 // or solve this with replay creating the SyncEventState in the queue context... also this will be a
6425 // new validation error... wait without previously submitted set event...
6426 events_not_found = true; // Demote "extra_stage_bits" error to warning, to avoid false positives at *record time*
John Zulauf4edde622021-02-15 08:54:50 -07006427 barrier_set_index += barrier_set_incr;
John Zulauf78394fc2021-07-12 15:41:40 -06006428 continue; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulaufd5115702021-01-18 12:34:33 -07006429 }
John Zulauf610e28c2021-08-03 17:46:23 -06006430
6431 // For replay calls, don't revalidate "same command buffer" events
6432 if (sync_event->last_command_tag > base_tag) continue;
6433
John Zulauf78394fc2021-07-12 15:41:40 -06006434 const auto event_handle = sync_event->event->event();
6435 // TODO add "destroyed" checks
6436
John Zulaufe0757ba2022-06-10 16:51:45 -06006437 if (sync_event->first_scope) {
John Zulauf78b1f892021-09-20 15:02:09 -06006438 // Only accumulate barrier and event stages if there is a pending set in the current context
6439 barrier_mask_params |= barrier_set.src_exec_scope.mask_param;
6440 event_stage_masks |= sync_event->scope.mask_param;
6441 }
6442
John Zulauf78394fc2021-07-12 15:41:40 -06006443 const auto &src_exec_scope = barrier_set.src_exec_scope;
John Zulauf78b1f892021-09-20 15:02:09 -06006444
sjfricke0bea06e2022-06-05 09:22:26 +09006445 const auto ignore_reason = sync_event->IsIgnoredByWait(cmd_type_, src_exec_scope.mask_param);
John Zulauf78394fc2021-07-12 15:41:40 -06006446 if (ignore_reason) {
6447 switch (ignore_reason) {
6448 case SyncEventState::ResetWaitRace:
6449 case SyncEventState::Reset2WaitRace: {
6450 // Four permuations of Reset and Wait calls...
6451 const char *vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006452 (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent-event-03834" : "VUID-vkCmdResetEvent-event-03835";
John Zulauf78394fc2021-07-12 15:41:40 -06006453 if (ignore_reason == SyncEventState::Reset2WaitRace) {
sjfricke0bea06e2022-06-05 09:22:26 +09006454 vuid = (cmd_type_ == CMD_WAITEVENTS) ? "VUID-vkCmdResetEvent2-event-03831"
6455 : "VUID-vkCmdResetEvent2-event-03832";
John Zulauf78394fc2021-07-12 15:41:40 -06006456 }
6457 const char *const message =
6458 "%s: %s %s operation following %s without intervening execution barrier, may cause race condition. %s";
6459 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6460 sync_state.report_data->FormatHandle(event_handle).c_str(), CmdName(),
John Zulauf610e28c2021-08-03 17:46:23 -06006461 CommandTypeString(sync_event->last_command), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006462 break;
6463 }
6464 case SyncEventState::SetRace: {
6465 // Issue error message that Wait is waiting on an signal subject to race condition, and is thus ignored for
6466 // this event
6467 const char *const vuid = "SYNC-vkCmdWaitEvents-unsynchronized-setops";
6468 const char *const message =
6469 "%s: %s Unsychronized %s calls result in race conditions w.r.t. event signalling, %s %s";
6470 const char *const reason = "First synchronization scope is undefined.";
6471 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6472 sync_state.report_data->FormatHandle(event_handle).c_str(),
John Zulauf610e28c2021-08-03 17:46:23 -06006473 CommandTypeString(sync_event->last_command), reason, kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006474 break;
6475 }
6476 case SyncEventState::MissingStageBits: {
6477 const auto missing_bits = sync_event->scope.mask_param & ~src_exec_scope.mask_param;
6478 // Issue error message that event waited for is not in wait events scope
6479 const char *const vuid = "VUID-vkCmdWaitEvents-srcStageMask-01158";
6480 const char *const message = "%s: %s stageMask %" PRIx64 " includes bits not present in srcStageMask 0x%" PRIx64
6481 ". Bits missing from srcStageMask %s. %s";
6482 skip |= sync_state.LogError(event_handle, vuid, message, CmdName(),
6483 sync_state.report_data->FormatHandle(event_handle).c_str(),
6484 sync_event->scope.mask_param, src_exec_scope.mask_param,
John Zulauf610e28c2021-08-03 17:46:23 -06006485 sync_utils::StringPipelineStageFlags(missing_bits).c_str(), kIgnored);
John Zulauf78394fc2021-07-12 15:41:40 -06006486 break;
6487 }
6488 case SyncEventState::SetVsWait2: {
Tony-LunarG279601c2021-11-16 10:50:51 -07006489 skip |= sync_state.LogError(event_handle, "VUID-vkCmdWaitEvents2-pEvents-03837",
John Zulauf78394fc2021-07-12 15:41:40 -06006490 "%s: Follows set of %s by %s. Disallowed.", CmdName(),
6491 sync_state.report_data->FormatHandle(event_handle).c_str(),
6492 CommandTypeString(sync_event->last_command));
6493 break;
6494 }
John Zulaufe0757ba2022-06-10 16:51:45 -06006495 case SyncEventState::MissingSetEvent: {
6496 // TODO: There are conditions at queue submit time where we can definitively say that
6497 // a missing set event is an error. Add those if not captured in CoreChecks
6498 break;
6499 }
John Zulauf78394fc2021-07-12 15:41:40 -06006500 default:
6501 assert(ignore_reason == SyncEventState::NotIgnored);
6502 }
6503 } else if (barrier_set.image_memory_barriers.size()) {
6504 const auto &image_memory_barriers = barrier_set.image_memory_barriers;
John Zulaufbb890452021-12-14 11:30:18 -07006505 const auto *context = exec_context.GetCurrentAccessContext();
John Zulauf78394fc2021-07-12 15:41:40 -06006506 assert(context);
6507 for (const auto &image_memory_barrier : image_memory_barriers) {
6508 if (image_memory_barrier.old_layout == image_memory_barrier.new_layout) continue;
6509 const auto *image_state = image_memory_barrier.image.get();
6510 if (!image_state) continue;
6511 const auto &subresource_range = image_memory_barrier.range;
6512 const auto &src_access_scope = image_memory_barrier.barrier.src_access_scope;
John Zulaufe0757ba2022-06-10 16:51:45 -06006513 const auto hazard = context->DetectImageBarrierHazard(*image_state, subresource_range, sync_event->scope.exec_scope,
6514 src_access_scope, queue_id, *sync_event,
6515 AccessContext::DetectOptions::kDetectAll);
John Zulauf78394fc2021-07-12 15:41:40 -06006516 if (hazard.hazard) {
6517 skip |= sync_state.LogError(image_state->image(), string_SyncHazardVUID(hazard.hazard),
6518 "%s: Hazard %s for image barrier %" PRIu32 " %s. Access info %s.", CmdName(),
6519 string_SyncHazard(hazard.hazard), image_memory_barrier.index,
6520 sync_state.report_data->FormatHandle(image_state->image()).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006521 exec_context.FormatHazard(hazard).c_str());
John Zulauf78394fc2021-07-12 15:41:40 -06006522 break;
6523 }
6524 }
6525 }
6526 // TODO: Add infrastructure for checking pDependencyInfo's vs. CmdSetEvent2 VUID - vkCmdWaitEvents2KHR - pEvents -
6527 // 03839
6528 barrier_set_index += barrier_set_incr;
6529 }
John Zulaufd5115702021-01-18 12:34:33 -07006530
6531 // Note that we can't check for HOST in pEvents as we don't track that set event type
John Zulauf4edde622021-02-15 08:54:50 -07006532 const auto extra_stage_bits = (barrier_mask_params & ~VK_PIPELINE_STAGE_2_HOST_BIT_KHR) & ~event_stage_masks;
John Zulaufd5115702021-01-18 12:34:33 -07006533 if (extra_stage_bits) {
6534 // Issue error message that event waited for is not in wait events scope
John Zulauf4edde622021-02-15 08:54:50 -07006535 // NOTE: This isn't exactly the right VUID for WaitEvents2, but it's as close as we currently have support for
6536 const char *const vuid =
sjfricke0bea06e2022-06-05 09:22:26 +09006537 (CMD_WAITEVENTS == cmd_type_) ? "VUID-vkCmdWaitEvents-srcStageMask-01158" : "VUID-vkCmdWaitEvents2-pEvents-03838";
John Zulaufd5115702021-01-18 12:34:33 -07006538 const char *const message =
Jeremy Gebben40a22942020-12-22 14:22:06 -07006539 "%s: srcStageMask 0x%" PRIx64 " contains stages not present in pEvents stageMask. Extra stages are %s.%s";
John Zulaufbb890452021-12-14 11:30:18 -07006540 const auto handle = exec_context.Handle();
John Zulaufd5115702021-01-18 12:34:33 -07006541 if (events_not_found) {
John Zulaufbb890452021-12-14 11:30:18 -07006542 skip |= sync_state.LogInfo(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006543 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(),
John Zulaufd5115702021-01-18 12:34:33 -07006544 " vkCmdSetEvent may be in previously submitted command buffer.");
6545 } else {
John Zulaufbb890452021-12-14 11:30:18 -07006546 skip |= sync_state.LogError(handle, vuid, message, CmdName(), barrier_mask_params,
Jeremy Gebben40a22942020-12-22 14:22:06 -07006547 sync_utils::StringPipelineStageFlags(extra_stage_bits).c_str(), "");
John Zulaufd5115702021-01-18 12:34:33 -07006548 }
6549 }
6550 return skip;
6551}
6552
6553struct SyncOpWaitEventsFunctorFactory {
6554 using BarrierOpFunctor = WaitEventBarrierOp;
6555 using ApplyFunctor = ApplyBarrierFunctor<BarrierOpFunctor>;
6556 using GlobalBarrierOpFunctor = WaitEventBarrierOp;
6557 using GlobalApplyFunctor = ApplyBarrierOpsFunctor<GlobalBarrierOpFunctor>;
6558 using BufferRange = EventSimpleRangeGenerator;
6559 using ImageRange = EventImageRangeGenerator;
6560 using GlobalRange = EventSimpleRangeGenerator;
6561
6562 // Need to restrict to only valid exec and access scope for this event
6563 // Pass by value is intentional to get a copy we can change without modifying the passed barrier
6564 SyncBarrier RestrictToEvent(SyncBarrier barrier) const {
John Zulaufc523bf62021-02-16 08:20:34 -07006565 barrier.src_exec_scope.exec_scope = sync_event->scope.exec_scope & barrier.src_exec_scope.exec_scope;
John Zulaufd5115702021-01-18 12:34:33 -07006566 barrier.src_access_scope = sync_event->scope.valid_accesses & barrier.src_access_scope;
6567 return barrier;
6568 }
John Zulauf00119522022-05-23 19:07:42 -06006569 ApplyFunctor MakeApplyFunctor(QueueId queue_id, const SyncBarrier &barrier_arg, bool layout_transition) const {
John Zulaufd5115702021-01-18 12:34:33 -07006570 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006571 return ApplyFunctor(BarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, layout_transition));
John Zulaufd5115702021-01-18 12:34:33 -07006572 }
John Zulauf14940722021-04-12 15:19:02 -06006573 GlobalApplyFunctor MakeGlobalApplyFunctor(size_t size_hint, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006574 return GlobalApplyFunctor(false /* don't resolve */, size_hint, tag);
6575 }
John Zulauf00119522022-05-23 19:07:42 -06006576 GlobalBarrierOpFunctor MakeGlobalBarrierOpFunctor(const QueueId queue_id, const SyncBarrier &barrier_arg) const {
John Zulaufd5115702021-01-18 12:34:33 -07006577 auto barrier = RestrictToEvent(barrier_arg);
John Zulauf00119522022-05-23 19:07:42 -06006578 return GlobalBarrierOpFunctor(queue_id, sync_event->first_scope_tag, barrier, false);
John Zulaufd5115702021-01-18 12:34:33 -07006579 }
6580
6581 BufferRange MakeRangeGen(const BUFFER_STATE &buffer, const ResourceAccessRange &range_arg) const {
6582 const AccessAddressType address_type = GetAccessAddressType(buffer);
6583 const auto base_address = ResourceBaseAddress(buffer);
6584 ResourceAccessRange range = SimpleBinding(buffer) ? (range_arg + base_address) : ResourceAccessRange();
6585 EventSimpleRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), range);
6586 return filtered_range_gen;
6587 }
John Zulauf110413c2021-03-20 05:38:38 -06006588 ImageRange MakeRangeGen(const IMAGE_STATE &image, const VkImageSubresourceRange &subresource_range) const {
John Zulaufd5115702021-01-18 12:34:33 -07006589 if (!SimpleBinding(image)) return ImageRange();
6590 const auto address_type = GetAccessAddressType(image);
6591 const auto base_address = ResourceBaseAddress(image);
Aitor Camachoe67f2c72022-06-08 14:41:58 +02006592 subresource_adapter::ImageRangeGenerator image_range_gen(*image.fragment_encoder.get(), subresource_range, base_address,
6593 false);
John Zulaufd5115702021-01-18 12:34:33 -07006594 EventImageRangeGenerator filtered_range_gen(sync_event->FirstScope(address_type), image_range_gen);
6595
6596 return filtered_range_gen;
6597 }
6598 GlobalRange MakeGlobalRangeGen(AccessAddressType address_type) const {
6599 return EventSimpleRangeGenerator(sync_event->FirstScope(address_type), kFullRange);
6600 }
6601 SyncOpWaitEventsFunctorFactory(SyncEventState *sync_event_) : sync_event(sync_event_) { assert(sync_event); }
6602 SyncEventState *sync_event;
6603};
6604
John Zulauf8eda1562021-04-13 17:06:41 -06006605ResourceUsageTag SyncOpWaitEvents::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006606 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulaufd5115702021-01-18 12:34:33 -07006607
John Zulauf0223f142022-07-06 09:05:39 -06006608 ReplayRecord(*cb_context, tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006609 return tag;
6610}
6611
John Zulauf0223f142022-07-06 09:05:39 -06006612void SyncOpWaitEvents::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufd5115702021-01-18 12:34:33 -07006613 // Unlike PipelineBarrier, WaitEvent is *not* limited to accesses within the current subpass (if any) and thus needs to import
6614 // all accesses. Can instead import for all first_scopes, or a union of them, if this becomes a performance/memory issue,
6615 // but with no idea of the performance of the union, nor of whether it even matters... take the simplest approach here,
John Zulauf0223f142022-07-06 09:05:39 -06006616 if (!exec_context.ValidForSyncOps()) return;
6617 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6618 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6619 const QueueId queue_id = exec_context.GetQueueId();
6620
John Zulaufd5115702021-01-18 12:34:33 -07006621 access_context->ResolvePreviousAccesses();
6622
John Zulauf4edde622021-02-15 08:54:50 -07006623 size_t barrier_set_index = 0;
6624 size_t barrier_set_incr = (barriers_.size() == 1) ? 0 : 1;
6625 assert(barriers_.size() == 1 || (barriers_.size() == events_.size()));
John Zulauf669dfd52021-01-27 17:15:28 -07006626 for (auto &event_shared : events_) {
6627 if (!event_shared.get()) continue;
6628 auto *sync_event = events_context->GetFromShared(event_shared);
John Zulaufd5115702021-01-18 12:34:33 -07006629
sjfricke0bea06e2022-06-05 09:22:26 +09006630 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006631 sync_event->last_command_tag = tag;
John Zulaufd5115702021-01-18 12:34:33 -07006632
John Zulauf4edde622021-02-15 08:54:50 -07006633 const auto &barrier_set = barriers_[barrier_set_index];
6634 const auto &dst = barrier_set.dst_exec_scope;
sjfricke0bea06e2022-06-05 09:22:26 +09006635 if (!sync_event->IsIgnoredByWait(cmd_type_, barrier_set.src_exec_scope.mask_param)) {
John Zulaufd5115702021-01-18 12:34:33 -07006636 // These apply barriers one at a time as the are restricted to the resource ranges specified per each barrier,
6637 // but do not update the dependency chain information (but set the "pending" state) // s.t. the order independence
6638 // of the barriers is maintained.
6639 SyncOpWaitEventsFunctorFactory factory(sync_event);
John Zulauf00119522022-05-23 19:07:42 -06006640 ApplyBarriers(barrier_set.buffer_memory_barriers, factory, queue_id, tag, access_context);
6641 ApplyBarriers(barrier_set.image_memory_barriers, factory, queue_id, tag, access_context);
6642 ApplyGlobalBarriers(barrier_set.memory_barriers, factory, queue_id, tag, access_context);
John Zulaufd5115702021-01-18 12:34:33 -07006643
6644 // Apply the global barrier to the event itself (for race condition tracking)
6645 // Events don't happen at a stage, so we need to store the unexpanded ALL_COMMANDS if set for inter-event-calls
6646 sync_event->barriers = dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
6647 sync_event->barriers |= dst.exec_scope;
6648 } else {
6649 // We ignored this wait, so we don't have any effective synchronization barriers for it.
6650 sync_event->barriers = 0U;
6651 }
John Zulauf4edde622021-02-15 08:54:50 -07006652 barrier_set_index += barrier_set_incr;
John Zulaufd5115702021-01-18 12:34:33 -07006653 }
6654
6655 // Apply the pending barriers
6656 ResolvePendingBarrierFunctor apply_pending_action(tag);
6657 access_context->ApplyToContext(apply_pending_action);
6658}
6659
John Zulauf8eda1562021-04-13 17:06:41 -06006660bool SyncOpWaitEvents::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006661 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6662 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006663}
6664
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006665bool SyncValidator::PreCallValidateCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
6666 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) const {
6667 bool skip = false;
6668 const auto *cb_access_context = GetAccessContext(commandBuffer);
6669 assert(cb_access_context);
6670 if (!cb_access_context) return skip;
6671
6672 const auto *context = cb_access_context->GetCurrentAccessContext();
6673 assert(context);
6674 if (!context) return skip;
6675
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006676 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006677
6678 if (dst_buffer) {
6679 const ResourceAccessRange range = MakeRange(dstOffset, 4);
6680 auto hazard = context->DetectHazard(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, range);
6681 if (hazard.hazard) {
6682 skip |= LogError(dstBuffer, string_SyncHazardVUID(hazard.hazard),
6683 "vkCmdWriteBufferMarkerAMD2: Hazard %s for dstBuffer %s. Access info %s.",
6684 string_SyncHazard(hazard.hazard), report_data->FormatHandle(dstBuffer).c_str(),
John Zulauf397e68b2022-04-19 11:44:07 -06006685 cb_access_context->FormatHazard(hazard).c_str());
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07006686 }
6687 }
6688 return skip;
6689}
6690
John Zulauf669dfd52021-01-27 17:15:28 -07006691void SyncOpWaitEvents::MakeEventsList(const SyncValidator &sync_state, uint32_t event_count, const VkEvent *events) {
John Zulaufd5115702021-01-18 12:34:33 -07006692 events_.reserve(event_count);
6693 for (uint32_t event_index = 0; event_index < event_count; event_index++) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006694 events_.emplace_back(sync_state.Get<EVENT_STATE>(events[event_index]));
John Zulaufd5115702021-01-18 12:34:33 -07006695 }
6696}
John Zulauf6ce24372021-01-30 05:56:25 -07006697
sjfricke0bea06e2022-06-05 09:22:26 +09006698SyncOpResetEvent::SyncOpResetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulauf4edde622021-02-15 08:54:50 -07006699 VkPipelineStageFlags2KHR stageMask)
sjfricke0bea06e2022-06-05 09:22:26 +09006700 : SyncOpBase(cmd_type),
6701 event_(sync_state.Get<EVENT_STATE>(event)),
6702 exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)) {}
John Zulauf6ce24372021-01-30 05:56:25 -07006703
John Zulauf1bf30522021-09-03 15:39:06 -06006704bool SyncOpResetEvent::Validate(const CommandBufferAccessContext& cb_context) const {
6705 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6706}
6707
John Zulaufbb890452021-12-14 11:30:18 -07006708bool SyncOpResetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
6709 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006710 assert(events_context);
6711 bool skip = false;
6712 if (!events_context) return skip;
6713
John Zulaufbb890452021-12-14 11:30:18 -07006714 const auto &sync_state = exec_context.GetSyncState();
John Zulauf6ce24372021-01-30 05:56:25 -07006715 const auto *sync_event = events_context->Get(event_);
6716 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6717
John Zulauf1bf30522021-09-03 15:39:06 -06006718 if (sync_event->last_command_tag > base_tag) return skip; // if we validated this in recording of the secondary, don't repeat
6719
John Zulauf6ce24372021-01-30 05:56:25 -07006720 const char *const set_wait =
6721 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6722 "hazards.";
6723 const char *message = set_wait; // Only one message this call.
6724 if (!sync_event->HasBarrier(exec_scope_.mask_param, exec_scope_.exec_scope)) {
6725 const char *vuid = nullptr;
6726 switch (sync_event->last_command) {
6727 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006728 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006729 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006730 // Needs a barrier between set and reset
6731 vuid = "SYNC-vkCmdResetEvent-missingbarrier-set";
6732 break;
John Zulauf4edde622021-02-15 08:54:50 -07006733 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006734 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006735 case CMD_WAITEVENTS2KHR: {
John Zulauf6ce24372021-01-30 05:56:25 -07006736 // Needs to be in the barriers chain (either because of a barrier, or because of dstStageMask
6737 vuid = "SYNC-vkCmdResetEvent-missingbarrier-wait";
6738 break;
6739 }
6740 default:
6741 // The only other valid last command that wasn't one.
John Zulauf4edde622021-02-15 08:54:50 -07006742 assert((sync_event->last_command == CMD_NONE) || (sync_event->last_command == CMD_RESETEVENT) ||
6743 (sync_event->last_command == CMD_RESETEVENT2KHR));
John Zulauf6ce24372021-01-30 05:56:25 -07006744 break;
6745 }
6746 if (vuid) {
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006747 skip |= sync_state.LogError(event_->event(), vuid, message, CmdName(),
6748 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006749 CommandTypeString(sync_event->last_command));
6750 }
6751 }
6752 return skip;
6753}
6754
John Zulauf8eda1562021-04-13 17:06:41 -06006755ResourceUsageTag SyncOpResetEvent::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006756 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf0223f142022-07-06 09:05:39 -06006757 ReplayRecord(*cb_context, tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006758 return tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006759}
6760
John Zulauf8eda1562021-04-13 17:06:41 -06006761bool SyncOpResetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006762 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6763 return DoValidate(exec_context, base_tag);
John Zulauf8eda1562021-04-13 17:06:41 -06006764}
6765
John Zulauf0223f142022-07-06 09:05:39 -06006766void SyncOpResetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
6767 if (!exec_context.ValidForSyncOps()) return;
6768 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6769
John Zulaufe0757ba2022-06-10 16:51:45 -06006770 auto *sync_event = events_context->GetFromShared(event_);
6771 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
6772
6773 // Update the event state
6774 sync_event->last_command = cmd_type_;
6775 sync_event->last_command_tag = tag;
6776 sync_event->unsynchronized_set = CMD_NONE;
6777 sync_event->ResetFirstScope();
6778 sync_event->barriers = 0U;
6779}
John Zulauf8eda1562021-04-13 17:06:41 -06006780
sjfricke0bea06e2022-06-05 09:22:26 +09006781SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006782 VkPipelineStageFlags2KHR stageMask, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006783 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006784 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006785 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006786 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, stageMask)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006787 dep_info_() {
6788 // Snapshot the current access_context for later inspection at wait time.
6789 // NOTE: This appears brute force, but given that we only save a "first-last" model of access history, the current
6790 // access context (include barrier state for chaining) won't necessarily contain the needed information at Wait
6791 // or Submit time reference.
6792 if (access_context) {
6793 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6794 }
6795}
John Zulauf4edde622021-02-15 08:54:50 -07006796
sjfricke0bea06e2022-06-05 09:22:26 +09006797SyncOpSetEvent::SyncOpSetEvent(CMD_TYPE cmd_type, const SyncValidator &sync_state, VkQueueFlags queue_flags, VkEvent event,
John Zulaufe0757ba2022-06-10 16:51:45 -06006798 const VkDependencyInfoKHR &dep_info, const AccessContext *access_context)
sjfricke0bea06e2022-06-05 09:22:26 +09006799 : SyncOpBase(cmd_type),
Jeremy Gebben9f537102021-10-05 16:37:12 -06006800 event_(sync_state.Get<EVENT_STATE>(event)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006801 recorded_context_(),
John Zulauf4edde622021-02-15 08:54:50 -07006802 src_exec_scope_(SyncExecScope::MakeSrc(queue_flags, sync_utils::GetGlobalStageMasks(dep_info).src)),
John Zulaufe0757ba2022-06-10 16:51:45 -06006803 dep_info_(new safe_VkDependencyInfo(&dep_info)) {
6804 if (access_context) {
6805 recorded_context_ = std::make_shared<const AccessContext>(*access_context);
6806 }
6807}
John Zulauf6ce24372021-01-30 05:56:25 -07006808
6809bool SyncOpSetEvent::Validate(const CommandBufferAccessContext &cb_context) const {
John Zulauf610e28c2021-08-03 17:46:23 -06006810 return DoValidate(cb_context, ResourceUsageRecord::kMaxIndex);
6811}
6812bool SyncOpSetEvent::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06006813 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
6814 return DoValidate(exec_context, base_tag);
John Zulauf610e28c2021-08-03 17:46:23 -06006815}
6816
John Zulaufbb890452021-12-14 11:30:18 -07006817bool SyncOpSetEvent::DoValidate(const CommandExecutionContext &exec_context, const ResourceUsageTag base_tag) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006818 bool skip = false;
6819
John Zulaufbb890452021-12-14 11:30:18 -07006820 const auto &sync_state = exec_context.GetSyncState();
6821 auto *events_context = exec_context.GetCurrentEventsContext();
John Zulauf6ce24372021-01-30 05:56:25 -07006822 assert(events_context);
6823 if (!events_context) return skip;
6824
6825 const auto *sync_event = events_context->Get(event_);
6826 if (!sync_event) return skip; // Core, Lifetimes, or Param check needs to catch invalid events.
6827
John Zulauf610e28c2021-08-03 17:46:23 -06006828 if (sync_event->last_command_tag >= base_tag) return skip; // for replay we don't want to revalidate internal "last commmand"
6829
John Zulauf6ce24372021-01-30 05:56:25 -07006830 const char *const reset_set =
6831 "%s: %s %s operation following %s without intervening execution barrier, is a race condition and may result in data "
6832 "hazards.";
6833 const char *const wait =
6834 "%s: %s %s operation following %s without intervening vkCmdResetEvent, may result in data hazard and is ignored.";
6835
6836 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
John Zulauf4edde622021-02-15 08:54:50 -07006837 const char *vuid_stem = nullptr;
John Zulauf6ce24372021-01-30 05:56:25 -07006838 const char *message = nullptr;
6839 switch (sync_event->last_command) {
6840 case CMD_RESETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006841 case CMD_RESETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006842 case CMD_RESETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006843 // Needs a barrier between reset and set
John Zulauf4edde622021-02-15 08:54:50 -07006844 vuid_stem = "-missingbarrier-reset";
John Zulauf6ce24372021-01-30 05:56:25 -07006845 message = reset_set;
6846 break;
6847 case CMD_SETEVENT:
John Zulauf4edde622021-02-15 08:54:50 -07006848 case CMD_SETEVENT2KHR:
Tony-LunarG8d71c4f2022-01-27 15:25:53 -07006849 case CMD_SETEVENT2:
John Zulauf6ce24372021-01-30 05:56:25 -07006850 // Needs a barrier between set and set
John Zulauf4edde622021-02-15 08:54:50 -07006851 vuid_stem = "-missingbarrier-set";
John Zulauf6ce24372021-01-30 05:56:25 -07006852 message = reset_set;
6853 break;
6854 case CMD_WAITEVENTS:
Tony-LunarG1364cf52021-11-17 16:10:11 -07006855 case CMD_WAITEVENTS2:
John Zulauf4edde622021-02-15 08:54:50 -07006856 case CMD_WAITEVENTS2KHR:
John Zulauf6ce24372021-01-30 05:56:25 -07006857 // Needs a barrier or is in second execution scope
John Zulauf4edde622021-02-15 08:54:50 -07006858 vuid_stem = "-missingbarrier-wait";
John Zulauf6ce24372021-01-30 05:56:25 -07006859 message = wait;
6860 break;
6861 default:
6862 // The only other valid last command that wasn't one.
6863 assert(sync_event->last_command == CMD_NONE);
6864 break;
6865 }
John Zulauf4edde622021-02-15 08:54:50 -07006866 if (vuid_stem) {
John Zulauf6ce24372021-01-30 05:56:25 -07006867 assert(nullptr != message);
John Zulauf4edde622021-02-15 08:54:50 -07006868 std::string vuid("SYNC-");
6869 vuid.append(CmdName()).append(vuid_stem);
Jeremy Gebben14b0d1a2021-05-15 20:15:41 -06006870 skip |= sync_state.LogError(event_->event(), vuid.c_str(), message, CmdName(),
6871 sync_state.report_data->FormatHandle(event_->event()).c_str(), CmdName(),
John Zulauf6ce24372021-01-30 05:56:25 -07006872 CommandTypeString(sync_event->last_command));
6873 }
6874 }
6875
6876 return skip;
6877}
6878
John Zulauf8eda1562021-04-13 17:06:41 -06006879ResourceUsageTag SyncOpSetEvent::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09006880 const auto tag = cb_context->NextCommandTag(cmd_type_);
John Zulauf6ce24372021-01-30 05:56:25 -07006881 auto *events_context = cb_context->GetCurrentEventsContext();
John Zulauf00119522022-05-23 19:07:42 -06006882 const QueueId queue_id = cb_context->GetQueueId();
John Zulaufe0757ba2022-06-10 16:51:45 -06006883 assert(recorded_context_);
6884 if (recorded_context_ && events_context) {
6885 DoRecord(queue_id, tag, recorded_context_, events_context);
John Zulauf610e28c2021-08-03 17:46:23 -06006886 }
6887 return tag;
6888}
John Zulauf6ce24372021-01-30 05:56:25 -07006889
John Zulauf0223f142022-07-06 09:05:39 -06006890void SyncOpSetEvent::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {
John Zulaufe0757ba2022-06-10 16:51:45 -06006891 // Create a copy of the current context, and merge in the state snapshot at record set event time
6892 // Note: we mustn't change the recorded context copy, as a given CB could be submitted more than once (in generaL)
John Zulauf0223f142022-07-06 09:05:39 -06006893 if (!exec_context.ValidForSyncOps()) return;
6894 SyncEventsContext *events_context = exec_context.GetCurrentEventsContext();
6895 AccessContext *access_context = exec_context.GetCurrentAccessContext();
6896 const QueueId queue_id = exec_context.GetQueueId();
6897
John Zulaufe0757ba2022-06-10 16:51:45 -06006898 auto merged_context = std::make_shared<AccessContext>(*access_context);
6899 merged_context->ResolveFromContext(QueueTagOffsetBarrierAction(queue_id, tag), *recorded_context_);
6900 DoRecord(queue_id, tag, merged_context, events_context);
6901}
6902
6903void SyncOpSetEvent::DoRecord(QueueId queue_id, ResourceUsageTag tag, const std::shared_ptr<const AccessContext> &access_context,
6904 SyncEventsContext *events_context) const {
John Zulauf6ce24372021-01-30 05:56:25 -07006905 auto *sync_event = events_context->GetFromShared(event_);
John Zulauf610e28c2021-08-03 17:46:23 -06006906 if (!sync_event) return; // Core, Lifetimes, or Param check needs to catch invalid events.
John Zulauf6ce24372021-01-30 05:56:25 -07006907
6908 // NOTE: We're going to simply record the sync scope here, as anything else would be implementation defined/undefined
6909 // and we're issuing errors re: missing barriers between event commands, which if the user fixes would fix
6910 // any issues caused by naive scope setting here.
6911
6912 // What happens with two SetEvent is that one cannot know what group of operations will be waited for.
6913 // Given:
6914 // Stuff1; SetEvent; Stuff2; SetEvent; WaitEvents;
6915 // WaitEvents cannot know which of Stuff1, Stuff2, or both has completed execution.
6916
6917 if (!sync_event->HasBarrier(src_exec_scope_.mask_param, src_exec_scope_.exec_scope)) {
6918 sync_event->unsynchronized_set = sync_event->last_command;
6919 sync_event->ResetFirstScope();
John Zulaufe0757ba2022-06-10 16:51:45 -06006920 } else if (!sync_event->first_scope) {
John Zulauf6ce24372021-01-30 05:56:25 -07006921 // We only set the scope if there isn't one
6922 sync_event->scope = src_exec_scope_;
6923
John Zulaufe0757ba2022-06-10 16:51:45 -06006924 // Save the shared_ptr to copy of the access_context present at set time (sent us by the caller)
6925 sync_event->first_scope = access_context;
John Zulauf6ce24372021-01-30 05:56:25 -07006926 sync_event->unsynchronized_set = CMD_NONE;
6927 sync_event->first_scope_tag = tag;
6928 }
John Zulauf4edde622021-02-15 08:54:50 -07006929 // TODO: Store dep_info_ shared ptr in sync_state for WaitEvents2 validation
sjfricke0bea06e2022-06-05 09:22:26 +09006930 sync_event->last_command = cmd_type_;
John Zulauf610e28c2021-08-03 17:46:23 -06006931 sync_event->last_command_tag = tag;
John Zulauf6ce24372021-01-30 05:56:25 -07006932 sync_event->barriers = 0U;
6933}
John Zulauf64ffe552021-02-06 10:25:07 -07006934
sjfricke0bea06e2022-06-05 09:22:26 +09006935SyncOpBeginRenderPass::SyncOpBeginRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
John Zulauf64ffe552021-02-06 10:25:07 -07006936 const VkRenderPassBeginInfo *pRenderPassBegin,
sfricke-samsung85584a72021-09-30 21:43:38 -07006937 const VkSubpassBeginInfo *pSubpassBeginInfo)
sjfricke0bea06e2022-06-05 09:22:26 +09006938 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07006939 if (pRenderPassBegin) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006940 rp_state_ = sync_state.Get<RENDER_PASS_STATE>(pRenderPassBegin->renderPass);
John Zulauf64ffe552021-02-06 10:25:07 -07006941 renderpass_begin_info_ = safe_VkRenderPassBeginInfo(pRenderPassBegin);
Jeremy Gebbenf4449392022-01-28 10:09:10 -07006942 auto fb_state = sync_state.Get<FRAMEBUFFER_STATE>(pRenderPassBegin->framebuffer);
John Zulauf64ffe552021-02-06 10:25:07 -07006943 if (fb_state) {
Jeremy Gebben9f537102021-10-05 16:37:12 -06006944 shared_attachments_ = sync_state.GetAttachmentViews(*renderpass_begin_info_.ptr(), *fb_state);
John Zulauf64ffe552021-02-06 10:25:07 -07006945 // TODO: Revisit this when all attachment validation is through SyncOps to see if we can discard the plain pointer copy
6946 // Note that this a safe to presist as long as shared_attachments is not cleared
6947 attachments_.reserve(shared_attachments_.size());
sfricke-samsung01c9ae92021-02-09 22:30:52 -08006948 for (const auto &attachment : shared_attachments_) {
John Zulauf64ffe552021-02-06 10:25:07 -07006949 attachments_.emplace_back(attachment.get());
6950 }
6951 }
6952 if (pSubpassBeginInfo) {
6953 subpass_begin_info_ = safe_VkSubpassBeginInfo(pSubpassBeginInfo);
6954 }
6955 }
6956}
6957
6958bool SyncOpBeginRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
6959 // Check if any of the layout transitions are hazardous.... but we don't have the renderpass context to work with, so we
6960 bool skip = false;
6961
6962 assert(rp_state_.get());
6963 if (nullptr == rp_state_.get()) return skip;
6964 auto &rp_state = *rp_state_.get();
6965
6966 const uint32_t subpass = 0;
6967
6968 // Construct the state we can use to validate against... (since validation is const and RecordCmdBeginRenderPass
6969 // hasn't happened yet)
6970 const std::vector<AccessContext> empty_context_vector;
6971 AccessContext temp_context(subpass, cb_context.GetQueueFlags(), rp_state.subpass_dependencies, empty_context_vector,
6972 cb_context.GetCurrentAccessContext());
6973
6974 // Validate attachment operations
6975 if (attachments_.size() == 0) return skip;
6976 const auto &render_area = renderpass_begin_info_.renderArea;
John Zulaufd0ec59f2021-03-13 14:25:08 -07006977
6978 // Since the isn't a valid RenderPassAccessContext until Record, needs to create the view/generator list... we could limit this
6979 // by predicating on whether subpass 0 uses the attachment if it is too expensive to create the full list redundantly here.
6980 // More broadly we could look at thread specific state shared between Validate and Record as is done for other heavyweight
6981 // operations (though it's currently a messy approach)
6982 AttachmentViewGenVector view_gens = RenderPassAccessContext::CreateAttachmentViewGen(render_area, attachments_);
sjfricke0bea06e2022-06-05 09:22:26 +09006983 skip |= temp_context.ValidateLayoutTransitions(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07006984
6985 // Validate load operations if there were no layout transition hazards
6986 if (!skip) {
John Zulaufee984022022-04-13 16:39:50 -06006987 temp_context.RecordLayoutTransitions(rp_state, subpass, view_gens, kInvalidTag);
sjfricke0bea06e2022-06-05 09:22:26 +09006988 skip |= temp_context.ValidateLoadOperation(cb_context, rp_state, render_area, subpass, view_gens, cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07006989 }
6990
6991 return skip;
6992}
6993
John Zulauf8eda1562021-04-13 17:06:41 -06006994ResourceUsageTag SyncOpBeginRenderPass::Record(CommandBufferAccessContext *cb_context) const {
John Zulauf64ffe552021-02-06 10:25:07 -07006995 // TODO PHASE2 need to have a consistent way to record to either command buffer or queue contexts
6996 assert(rp_state_.get());
sjfricke0bea06e2022-06-05 09:22:26 +09006997 if (nullptr == rp_state_.get()) return cb_context->NextCommandTag(cmd_type_);
6998 return cb_context->RecordBeginRenderPass(cmd_type_, *rp_state_.get(), renderpass_begin_info_.renderArea, attachments_);
John Zulauf64ffe552021-02-06 10:25:07 -07006999}
7000
John Zulauf8eda1562021-04-13 17:06:41 -06007001bool SyncOpBeginRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007002 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007003 return false;
7004}
7005
John Zulauf0223f142022-07-06 09:05:39 -06007006void SyncOpBeginRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06007007
sjfricke0bea06e2022-06-05 09:22:26 +09007008SyncOpNextSubpass::SyncOpNextSubpass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7009 const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo)
7010 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007011 if (pSubpassBeginInfo) {
7012 subpass_begin_info_.initialize(pSubpassBeginInfo);
7013 }
7014 if (pSubpassEndInfo) {
7015 subpass_end_info_.initialize(pSubpassEndInfo);
7016 }
7017}
7018
7019bool SyncOpNextSubpass::Validate(const CommandBufferAccessContext &cb_context) const {
7020 bool skip = false;
7021 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7022 if (!renderpass_context) return skip;
7023
sjfricke0bea06e2022-06-05 09:22:26 +09007024 skip |= renderpass_context->ValidateNextSubpass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007025 return skip;
7026}
7027
John Zulauf8eda1562021-04-13 17:06:41 -06007028ResourceUsageTag SyncOpNextSubpass::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09007029 return cb_context->RecordNextSubpass(cmd_type_);
John Zulauf8eda1562021-04-13 17:06:41 -06007030}
7031
7032bool SyncOpNextSubpass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007033 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007034 return false;
John Zulauf64ffe552021-02-06 10:25:07 -07007035}
7036
sjfricke0bea06e2022-06-05 09:22:26 +09007037SyncOpEndRenderPass::SyncOpEndRenderPass(CMD_TYPE cmd_type, const SyncValidator &sync_state,
7038 const VkSubpassEndInfo *pSubpassEndInfo)
7039 : SyncOpBase(cmd_type) {
John Zulauf64ffe552021-02-06 10:25:07 -07007040 if (pSubpassEndInfo) {
7041 subpass_end_info_.initialize(pSubpassEndInfo);
7042 }
7043}
7044
John Zulauf0223f142022-07-06 09:05:39 -06007045void SyncOpNextSubpass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06007046
John Zulauf64ffe552021-02-06 10:25:07 -07007047bool SyncOpEndRenderPass::Validate(const CommandBufferAccessContext &cb_context) const {
7048 bool skip = false;
7049 const auto *renderpass_context = cb_context.GetCurrentRenderPassContext();
7050
7051 if (!renderpass_context) return skip;
sjfricke0bea06e2022-06-05 09:22:26 +09007052 skip |= renderpass_context->ValidateEndRenderPass(cb_context.GetExecutionContext(), cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007053 return skip;
7054}
7055
John Zulauf8eda1562021-04-13 17:06:41 -06007056ResourceUsageTag SyncOpEndRenderPass::Record(CommandBufferAccessContext *cb_context) const {
sjfricke0bea06e2022-06-05 09:22:26 +09007057 return cb_context->RecordEndRenderPass(cmd_type_);
John Zulauf64ffe552021-02-06 10:25:07 -07007058}
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007059
John Zulauf8eda1562021-04-13 17:06:41 -06007060bool SyncOpEndRenderPass::ReplayValidate(ResourceUsageTag recorded_tag, const CommandBufferAccessContext &recorded_context,
John Zulauf0223f142022-07-06 09:05:39 -06007061 ResourceUsageTag base_tag, CommandExecutionContext &exec_context) const {
John Zulauf8eda1562021-04-13 17:06:41 -06007062 return false;
7063}
7064
John Zulauf0223f142022-07-06 09:05:39 -06007065void SyncOpEndRenderPass::ReplayRecord(CommandExecutionContext &exec_context, ResourceUsageTag tag) const {}
John Zulauf8eda1562021-04-13 17:06:41 -06007066
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007067void SyncValidator::PreCallRecordCmdWriteBufferMarker2AMD(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage,
7068 VkBuffer dstBuffer, VkDeviceSize dstOffset, uint32_t marker) {
7069 StateTracker::PreCallRecordCmdWriteBufferMarker2AMD(commandBuffer, pipelineStage, dstBuffer, dstOffset, marker);
7070 auto *cb_access_context = GetAccessContext(commandBuffer);
7071 assert(cb_access_context);
7072 const auto tag = cb_access_context->NextCommandTag(CMD_WRITEBUFFERMARKERAMD);
7073 auto *context = cb_access_context->GetCurrentAccessContext();
7074 assert(context);
7075
Jeremy Gebbenf4449392022-01-28 10:09:10 -07007076 auto dst_buffer = Get<BUFFER_STATE>(dstBuffer);
Jeremy Gebbendf3fcc32021-02-15 08:53:17 -07007077
7078 if (dst_buffer) {
7079 const ResourceAccessRange range = MakeRange(dstOffset, 4);
7080 context->UpdateAccessState(*dst_buffer, SYNC_COPY_TRANSFER_WRITE, SyncOrdering::kNonAttachment, range, tag);
7081 }
7082}
John Zulaufd05c5842021-03-26 11:32:16 -06007083
John Zulaufae842002021-04-15 18:20:55 -06007084bool SyncValidator::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7085 const VkCommandBuffer *pCommandBuffers) const {
7086 bool skip = StateTracker::PreCallValidateCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulaufae842002021-04-15 18:20:55 -06007087 const auto *cb_context = GetAccessContext(commandBuffer);
7088 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007089
7090 // Heavyweight, but we need a proxy copy of the active command buffer access context
7091 CommandBufferAccessContext proxy_cb_context(*cb_context, CommandBufferAccessContext::AsProxyContext());
John Zulaufae842002021-04-15 18:20:55 -06007092
7093 // Make working copies of the access and events contexts
John Zulaufae842002021-04-15 18:20:55 -06007094 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007095 proxy_cb_context.NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
7096
John Zulaufae842002021-04-15 18:20:55 -06007097 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7098 if (!recorded_cb_context) continue;
John Zulauf4fa68462021-04-26 21:04:22 -06007099
7100 const auto *recorded_context = recorded_cb_context->GetCurrentAccessContext();
7101 assert(recorded_context);
John Zulauf0223f142022-07-06 09:05:39 -06007102 skip |= recorded_cb_context->ValidateFirstUse(proxy_cb_context, "vkCmdExecuteCommands", cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007103
7104 // The barriers have already been applied in ValidatFirstUse
7105 ResourceUsageRange tag_range = proxy_cb_context.ImportRecordedAccessLog(*recorded_cb_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007106 proxy_cb_context.ResolveExecutedCommandBuffer(*recorded_context, tag_range.begin);
John Zulaufae842002021-04-15 18:20:55 -06007107 }
7108
John Zulaufae842002021-04-15 18:20:55 -06007109 return skip;
7110}
7111
7112void SyncValidator::PreCallRecordCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBufferCount,
7113 const VkCommandBuffer *pCommandBuffers) {
7114 StateTracker::PreCallRecordCmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
John Zulauf4fa68462021-04-26 21:04:22 -06007115 auto *cb_context = GetAccessContext(commandBuffer);
7116 assert(cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007117 for (uint32_t cb_index = 0; cb_index < commandBufferCount; ++cb_index) {
John Zulauf41a9c7c2021-12-07 15:59:53 -07007118 cb_context->NextIndexedCommandTag(CMD_EXECUTECOMMANDS, cb_index);
John Zulauf4fa68462021-04-26 21:04:22 -06007119 const auto *recorded_cb_context = GetAccessContext(pCommandBuffers[cb_index]);
7120 if (!recorded_cb_context) continue;
sjfricke0bea06e2022-06-05 09:22:26 +09007121 cb_context->RecordExecutedCommandBuffer(*recorded_cb_context);
John Zulauf4fa68462021-04-26 21:04:22 -06007122 }
John Zulaufae842002021-04-15 18:20:55 -06007123}
7124
John Zulauf1d5f9c12022-05-13 14:51:08 -06007125void SyncValidator::PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) {
7126 StateTracker::PostCallRecordQueueWaitIdle(queue, result);
7127 if ((result != VK_SUCCESS) || (!enabled[sync_validation_queue_submit]) || (queue == VK_NULL_HANDLE)) return;
7128
7129 const auto queue_state = GetQueueSyncStateShared(queue);
7130 if (!queue_state) return; // Invalid queue
7131 QueueId waited_queue = queue_state->GetQueueId();
7132
7133 // We need to go through every queue batch context and clear all accesses this wait synchronizes
7134 // As usual -- two groups, the "last batch" and the signaled semaphores
7135 // NOTE: Since ApplyTaggedWait crawls through every usage in every ResourceAccessState in the AccessContext of *every*
7136 // QueueBatchContext, track which we've done to avoid duplicate traversals
John Zulaufe0757ba2022-06-10 16:51:45 -06007137 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7138 for (auto &batch : queue_batch_contexts) {
7139 batch->ApplyTaggedWait(waited_queue, ResourceUsageRecord::kMaxIndex);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007140 }
7141
John Zulaufe0757ba2022-06-10 16:51:45 -06007142 // TODO: Fences affected by Wait
John Zulauf1d5f9c12022-05-13 14:51:08 -06007143}
7144
7145void SyncValidator::PostCallRecordDeviceWaitIdle(VkDevice device, VkResult result) {
7146 StateTracker::PostCallRecordDeviceWaitIdle(device, result);
John Zulaufe0757ba2022-06-10 16:51:45 -06007147
7148 QueueBatchContext::BatchSet queue_batch_contexts = GetQueueBatchSnapshot();
7149 for (auto &batch : queue_batch_contexts) {
7150 batch->ApplyDeviceWait();
John Zulauf1d5f9c12022-05-13 14:51:08 -06007151 }
7152
John Zulaufe0757ba2022-06-10 16:51:45 -06007153 // TODO: Update Fences affected by Wait
John Zulauf1d5f9c12022-05-13 14:51:08 -06007154}
7155
John Zulauf697c0e12022-04-19 16:31:12 -06007156struct QueueSubmitCmdState {
7157 std::shared_ptr<const QueueSyncState> queue;
7158 std::shared_ptr<QueueBatchContext> last_batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007159 AccessLogger logger;
John Zulaufcb7e1672022-05-04 13:46:08 -06007160 SignaledSemaphores signaled;
John Zulauf00119522022-05-23 19:07:42 -06007161 QueueSubmitCmdState(const AccessLogger &parent_log, const SignaledSemaphores &parent_semaphores)
7162 : logger(&parent_log), signaled(parent_semaphores) {}
John Zulauf697c0e12022-04-19 16:31:12 -06007163};
7164
7165template <>
7166thread_local layer_data::optional<QueueSubmitCmdState> layer_data::TlsGuard<QueueSubmitCmdState>::payload_{};
7167
John Zulaufbbda4572022-04-19 16:20:45 -06007168bool SyncValidator::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits,
7169 VkFence fence) const {
7170 bool skip = false;
John Zulaufcb7e1672022-05-04 13:46:08 -06007171
7172 // Since this early return is above the TlsGuard, the Record phase must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007173 if (!enabled[sync_validation_queue_submit]) return skip;
7174
John Zulauf00119522022-05-23 19:07:42 -06007175 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state(&skip, global_access_log_, signaled_semaphores_);
John Zulauf697c0e12022-04-19 16:31:12 -06007176 const auto fence_state = Get<FENCE_STATE>(fence);
7177 cmd_state->queue = GetQueueSyncStateShared(queue);
7178 if (!cmd_state->queue) return skip; // Invalid Queue
John Zulaufbbda4572022-04-19 16:20:45 -06007179
John Zulauf697c0e12022-04-19 16:31:12 -06007180 // The submit id is a mutable automic which is not recoverable on a skip == true condition
7181 uint64_t submit_id = cmd_state->queue->ReserveSubmitId();
7182
7183 // verify each submit batch
7184 // Since the last batch from the queue state is const, we need to track the last_batch separately from the
7185 // most recently created batch
7186 std::shared_ptr<const QueueBatchContext> last_batch = cmd_state->queue->LastBatch();
7187 std::shared_ptr<QueueBatchContext> batch;
7188 for (uint32_t batch_idx = 0; batch_idx < submitCount; batch_idx++) {
7189 const VkSubmitInfo &submit = pSubmits[batch_idx];
John Zulaufcb7e1672022-05-04 13:46:08 -06007190 batch = std::make_shared<QueueBatchContext>(*this, *cmd_state->queue);
7191 batch->Setup(last_batch, submit, cmd_state->signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007192
John Zulaufe0757ba2022-06-10 16:51:45 -06007193 // Skip import and validation of empty batches
7194 if (batch->GetTagRange().size()) {
7195 batch->SetBatchLog(cmd_state->logger, submit_id, batch_idx);
John Zulauf697c0e12022-04-19 16:31:12 -06007196
John Zulaufe0757ba2022-06-10 16:51:45 -06007197 // For each submit in the batch...
7198 for (const auto &cb : *batch) {
7199 if (cb.cb->GetTagLimit() == 0) continue; // Skip empty CB's
John Zulauf0223f142022-07-06 09:05:39 -06007200 skip |= cb.cb->ValidateFirstUse(*batch.get(), "vkQueueSubmit", cb.index);
John Zulaufe0757ba2022-06-10 16:51:45 -06007201
7202 // The barriers have already been applied in ValidatFirstUse
7203 ResourceUsageRange tag_range = batch->ImportRecordedAccessLog(*cb.cb);
7204 batch->ResolveSubmittedCommandBuffer(*cb.cb->GetCurrentAccessContext(), tag_range.begin);
7205 }
John Zulauf697c0e12022-04-19 16:31:12 -06007206 }
7207
John Zulaufe0757ba2022-06-10 16:51:45 -06007208 // Empty batches could have semaphores, though.
John Zulauf697c0e12022-04-19 16:31:12 -06007209 for (auto &sem : layer_data::make_span(submit.pSignalSemaphores, submit.signalSemaphoreCount)) {
7210 // Make a copy of the state, signal the copy and pend it...
John Zulaufcb7e1672022-05-04 13:46:08 -06007211 auto sem_state = Get<SEMAPHORE_STATE>(sem);
John Zulauf697c0e12022-04-19 16:31:12 -06007212 if (!sem_state) continue;
John Zulaufcb7e1672022-05-04 13:46:08 -06007213 auto semaphore_info = lvl_init_struct<VkSemaphoreSubmitInfo>();
7214 semaphore_info.stageMask = VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT;
7215 cmd_state->signaled.SignalSemaphore(sem_state, batch, semaphore_info);
John Zulauf697c0e12022-04-19 16:31:12 -06007216 }
7217 // Unless the previous batch was referenced by a signal, the QueueBatchContext will self destruct, but as
7218 // we ResolvePrevious as we can let any contexts we've fully referenced go.
7219 last_batch = batch;
7220 }
7221 // The most recently created batch will become the queue's "last batch" in the record phase
7222 if (batch) {
7223 cmd_state->last_batch = std::move(batch);
7224 }
7225
7226 // Note that if we skip, guard cleans up for us, but cannot release the reserved tag range
John Zulaufbbda4572022-04-19 16:20:45 -06007227 return skip;
7228}
7229
7230void SyncValidator::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence,
7231 VkResult result) {
7232 StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007233
John Zulaufcb7e1672022-05-04 13:46:08 -06007234 // If this return is above the TlsGuard, then the Validate phase return must also be.
John Zulauf78cb2082022-04-20 16:37:48 -06007235 if (!enabled[sync_validation_queue_submit]) return; // Queue submit validation must be affirmatively enabled
7236
John Zulaufcb7e1672022-05-04 13:46:08 -06007237 // The earliest return (when enabled), must be *after* the TlsGuard, as it is the TlsGuard that cleans up the cmd_state
7238 // static payload
John Zulauf697c0e12022-04-19 16:31:12 -06007239 layer_data::TlsGuard<QueueSubmitCmdState> cmd_state;
John Zulaufcb7e1672022-05-04 13:46:08 -06007240
7241 if (VK_SUCCESS != result) return; // dispatched QueueSubmit failed
John Zulauf78cb2082022-04-20 16:37:48 -06007242 if (!cmd_state->queue) return; // Validation couldn't find a valid queue object
7243
John Zulauf697c0e12022-04-19 16:31:12 -06007244 // Don't need to look up the queue state again, but we need a non-const version
7245 std::shared_ptr<QueueSyncState> queue_state = std::const_pointer_cast<QueueSyncState>(std::move(cmd_state->queue));
John Zulauf697c0e12022-04-19 16:31:12 -06007246
John Zulaufcb7e1672022-05-04 13:46:08 -06007247 // The global the semaphores we applied to the cmd_state QueueBatchContexts
7248 // NOTE: All conserved QueueBatchContext's need to have there access logs reset to use the global logger and the only conserved
7249 // QBC's are those referenced by unwaited signals and the last batch.
7250 for (auto &sig_sem : cmd_state->signaled) {
7251 if (sig_sem.second && sig_sem.second->batch) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007252 auto &sig_batch = sig_sem.second->batch;
7253 sig_batch->ResetAccessLog();
7254 // Batches retained for signalled semaphore don't need to retain event data, unless it's the last batch in the submit
7255 if (sig_batch != cmd_state->last_batch) {
7256 sig_batch->ResetEventsContext();
7257 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007258 }
7259 signaled_semaphores_.Import(sig_sem.first, std::move(sig_sem.second));
John Zulauf697c0e12022-04-19 16:31:12 -06007260 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007261 cmd_state->signaled.Reset();
John Zulauf697c0e12022-04-19 16:31:12 -06007262
John Zulaufcb7e1672022-05-04 13:46:08 -06007263 // Update the queue to point to the last batch from the submit
7264 if (cmd_state->last_batch) {
7265 cmd_state->last_batch->ResetAccessLog();
John Zulaufe0757ba2022-06-10 16:51:45 -06007266
7267 // Clean up the events data in the previous last batch on queue, as only the subsequent batches have valid use for them
7268 // and the QueueBatchContext::Setup calls have be copying them along from batch to batch during submit.
7269 auto last_batch = queue_state->LastBatch();
7270 if (last_batch) {
7271 last_batch->ResetEventsContext();
7272 }
John Zulaufcb7e1672022-05-04 13:46:08 -06007273 queue_state->SetLastBatch(std::move(cmd_state->last_batch));
John Zulauf697c0e12022-04-19 16:31:12 -06007274 }
7275
7276 // Update the global access log from the one built during validation
7277 global_access_log_.MergeMove(std::move(cmd_state->logger));
7278
John Zulauf697c0e12022-04-19 16:31:12 -06007279
7280 // WIP: record information about fences
John Zulaufbbda4572022-04-19 16:20:45 -06007281}
7282
7283bool SyncValidator::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7284 VkFence fence) const {
John Zulauf78cb2082022-04-20 16:37:48 -06007285 bool skip = false;
7286 if (!enabled[sync_validation_queue_submit]) return skip;
7287
John Zulauf697c0e12022-04-19 16:31:12 -06007288 // WIP: Add Submit2 support
John Zulauf78cb2082022-04-20 16:37:48 -06007289 return skip;
John Zulaufbbda4572022-04-19 16:20:45 -06007290}
7291
7292void SyncValidator::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits,
7293 VkFence fence, VkResult result) {
7294 StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result);
John Zulauf78cb2082022-04-20 16:37:48 -06007295 if (VK_SUCCESS != result) return; // dispatched QueueSubmit2 failed
7296
7297 if (!enabled[sync_validation_queue_submit]) return;
7298
John Zulauf697c0e12022-04-19 16:31:12 -06007299 // WIP: Add Submit2 support
John Zulaufbbda4572022-04-19 16:20:45 -06007300}
7301
John Zulaufd0ec59f2021-03-13 14:25:08 -07007302AttachmentViewGen::AttachmentViewGen(const IMAGE_VIEW_STATE *view, const VkOffset3D &offset, const VkExtent3D &extent)
7303 : view_(view), view_mask_(), gen_store_() {
7304 if (!view_ || !view_->image_state || !SimpleBinding(*view_->image_state)) return;
7305 const IMAGE_STATE &image_state = *view_->image_state.get();
7306 const auto base_address = ResourceBaseAddress(image_state);
7307 const auto *encoder = image_state.fragment_encoder.get();
7308 if (!encoder) return;
Jeremy Gebben11a68a32021-07-29 11:59:22 -06007309 // Get offset and extent for the view, accounting for possible depth slicing
7310 const VkOffset3D zero_offset = view->GetOffset();
7311 const VkExtent3D &image_extent = view->GetExtent();
John Zulaufd0ec59f2021-03-13 14:25:08 -07007312 // Intentional copy
7313 VkImageSubresourceRange subres_range = view_->normalized_subresource_range;
7314 view_mask_ = subres_range.aspectMask;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007315 gen_store_[Gen::kViewSubresource].emplace(*encoder, subres_range, zero_offset, image_extent, base_address,
7316 view->IsDepthSliced());
7317 gen_store_[Gen::kRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007318
7319 const auto depth = view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT;
7320 if (depth && (depth != view_mask_)) {
7321 subres_range.aspectMask = depth;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007322 gen_store_[Gen::kDepthOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address, view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007323 }
7324 const auto stencil = view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT;
7325 if (stencil && (stencil != view_mask_)) {
7326 subres_range.aspectMask = stencil;
Aitor Camachoe67f2c72022-06-08 14:41:58 +02007327 gen_store_[Gen::kStencilOnlyRenderArea].emplace(*encoder, subres_range, offset, extent, base_address,
7328 view->IsDepthSliced());
John Zulaufd0ec59f2021-03-13 14:25:08 -07007329 }
7330}
7331
7332const ImageRangeGen *AttachmentViewGen::GetRangeGen(AttachmentViewGen::Gen gen_type) const {
7333 const ImageRangeGen *got = nullptr;
7334 switch (gen_type) {
7335 case kViewSubresource:
7336 got = &gen_store_[kViewSubresource];
7337 break;
7338 case kRenderArea:
7339 got = &gen_store_[kRenderArea];
7340 break;
7341 case kDepthOnlyRenderArea:
7342 got =
7343 (view_mask_ == VK_IMAGE_ASPECT_DEPTH_BIT) ? &gen_store_[Gen::kRenderArea] : &gen_store_[Gen::kDepthOnlyRenderArea];
7344 break;
7345 case kStencilOnlyRenderArea:
7346 got = (view_mask_ == VK_IMAGE_ASPECT_STENCIL_BIT) ? &gen_store_[Gen::kRenderArea]
7347 : &gen_store_[Gen::kStencilOnlyRenderArea];
7348 break;
7349 default:
7350 assert(got);
7351 }
7352 return got;
7353}
7354
7355AttachmentViewGen::Gen AttachmentViewGen::GetDepthStencilRenderAreaGenType(bool depth_op, bool stencil_op) const {
7356 assert(IsValid());
7357 assert(view_mask_ & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT));
7358 if (depth_op) {
7359 assert(view_mask_ & VK_IMAGE_ASPECT_DEPTH_BIT);
7360 if (stencil_op) {
7361 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7362 return kRenderArea;
7363 }
7364 return kDepthOnlyRenderArea;
7365 }
7366 if (stencil_op) {
7367 assert(view_mask_ & VK_IMAGE_ASPECT_STENCIL_BIT);
7368 return kStencilOnlyRenderArea;
7369 }
7370
7371 assert(depth_op || stencil_op);
7372 return kRenderArea;
7373}
7374
7375AccessAddressType AttachmentViewGen::GetAddressType() const { return AccessContext::ImageAddressType(*view_->image_state); }
John Zulauf8eda1562021-04-13 17:06:41 -06007376
John Zulaufe0757ba2022-06-10 16:51:45 -06007377void SyncEventsContext::ApplyBarrier(const SyncExecScope &src, const SyncExecScope &dst, ResourceUsageTag tag) {
John Zulauf8eda1562021-04-13 17:06:41 -06007378 const bool all_commands_bit = 0 != (src.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT);
7379 for (auto &event_pair : map_) {
7380 assert(event_pair.second); // Shouldn't be storing empty
7381 auto &sync_event = *event_pair.second;
7382 // Events don't happen at a stage, so we need to check and store the unexpanded ALL_COMMANDS if set for inter-event-calls
John Zulaufe0757ba2022-06-10 16:51:45 -06007383 // But only if occuring before the tag
7384 if (((sync_event.barriers & src.exec_scope) || all_commands_bit) && (sync_event.last_command_tag <= tag)) {
John Zulauf8eda1562021-04-13 17:06:41 -06007385 sync_event.barriers |= dst.exec_scope;
7386 sync_event.barriers |= dst.mask_param & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT;
7387 }
7388 }
7389}
John Zulaufbb890452021-12-14 11:30:18 -07007390
John Zulaufe0757ba2022-06-10 16:51:45 -06007391void SyncEventsContext::ApplyTaggedWait(VkQueueFlags queue_flags, ResourceUsageTag tag) {
7392 const SyncExecScope src_scope =
7393 SyncExecScope::MakeSrc(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT);
7394 const SyncExecScope dst_scope = SyncExecScope::MakeDst(queue_flags, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT);
7395 ApplyBarrier(src_scope, dst_scope, tag);
7396}
7397
7398SyncEventsContext &SyncEventsContext::DeepCopy(const SyncEventsContext &from) {
7399 // We need a deep copy of the const context to update during validation phase
7400 for (const auto &event : from.map_) {
7401 map_.emplace(event.first, std::make_shared<SyncEventState>(*event.second));
7402 }
7403 return *this;
7404}
7405
John Zulaufcb7e1672022-05-04 13:46:08 -06007406QueueBatchContext::QueueBatchContext(const SyncValidator &sync_state, const QueueSyncState &queue_state)
7407 : CommandExecutionContext(&sync_state), queue_state_(&queue_state), tag_range_(0, 0), batch_log_(nullptr) {}
7408
John Zulauf697c0e12022-04-19 16:31:12 -06007409template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007410void QueueBatchContext::Setup(const std::shared_ptr<const QueueBatchContext> &prev_batch, const BatchInfo &batch_info,
7411 SignaledSemaphores &signaled) {
John Zulauf697c0e12022-04-19 16:31:12 -06007412 SetupCommandBufferInfo(batch_info);
John Zulaufcb7e1672022-05-04 13:46:08 -06007413 SetupAccessContext(prev_batch, batch_info, signaled);
John Zulauf697c0e12022-04-19 16:31:12 -06007414}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007415void QueueBatchContext::ResolveSubmittedCommandBuffer(const AccessContext &recorded_context, ResourceUsageTag offset) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007416 GetCurrentAccessContext()->ResolveFromContext(QueueTagOffsetBarrierAction(GetQueueId(), offset), recorded_context);
John Zulauf1d5f9c12022-05-13 14:51:08 -06007417}
John Zulauf697c0e12022-04-19 16:31:12 -06007418
7419VulkanTypedHandle QueueBatchContext::Handle() const { return queue_state_->Handle(); }
7420
John Zulauf1d5f9c12022-05-13 14:51:08 -06007421void QueueBatchContext::ApplyTaggedWait(QueueId queue_id, ResourceUsageTag tag) {
7422 QueueWaitWorm wait_worm(queue_id);
7423 access_context_.ForAll(wait_worm);
7424 if (wait_worm.erase_all) {
7425 access_context_.Reset();
7426 } else {
7427 // TODO: Profiling will tell us if we need a more efficient clean up.
7428 for (const auto &address : wait_worm.erase_list) {
7429 access_context_.DeleteAccess(address);
7430 }
7431 }
John Zulaufe0757ba2022-06-10 16:51:45 -06007432
7433 if (queue_id == GetQueueId()) {
7434 events_context_.ApplyTaggedWait(GetQueueFlags(), tag);
7435 }
John Zulauf1d5f9c12022-05-13 14:51:08 -06007436}
7437
7438// Clear all accesses
John Zulaufe0757ba2022-06-10 16:51:45 -06007439void QueueBatchContext::ApplyDeviceWait() {
7440 access_context_.Reset();
7441 events_context_.ApplyTaggedWait(GetQueueFlags(), ResourceUsageRecord::kMaxIndex);
7442}
John Zulauf1d5f9c12022-05-13 14:51:08 -06007443
John Zulaufecf4ac52022-06-06 10:08:42 -06007444class ApplySemaphoreBarrierAction {
7445 public:
7446 ApplySemaphoreBarrierAction(const SemaphoreScope &signal, const SemaphoreScope &wait) : signal_(signal), wait_(wait) {}
7447 void operator()(ResourceAccessState *access) const { access->ApplySemaphore(signal_, wait_); }
7448
7449 private:
7450 const SemaphoreScope &signal_;
7451 const SemaphoreScope wait_;
7452};
7453
7454std::shared_ptr<QueueBatchContext> QueueBatchContext::ResolveOneWaitSemaphore(VkSemaphore sem, VkPipelineStageFlags2 wait_mask,
7455 SignaledSemaphores &signaled) {
John Zulaufcb7e1672022-05-04 13:46:08 -06007456 auto sem_state = sync_state_->Get<SEMAPHORE_STATE>(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007457 if (!sem_state) return nullptr; // Semaphore validity is handled by CoreChecks
John Zulauf697c0e12022-04-19 16:31:12 -06007458
John Zulaufcb7e1672022-05-04 13:46:08 -06007459 // When signal state goes out of scope, the signal information will be dropped, as Unsignal has released ownership.
7460 auto signal_state = signaled.Unsignal(sem);
John Zulaufecf4ac52022-06-06 10:08:42 -06007461 if (!signal_state) return nullptr; // Invalid signal, skip it.
John Zulaufcb7e1672022-05-04 13:46:08 -06007462
John Zulaufecf4ac52022-06-06 10:08:42 -06007463 assert(signal_state->batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007464
John Zulaufecf4ac52022-06-06 10:08:42 -06007465 const SemaphoreScope &signal_scope = signal_state->first_scope;
John Zulauf697c0e12022-04-19 16:31:12 -06007466 const auto queue_flags = queue_state_->GetQueueFlags();
John Zulaufecf4ac52022-06-06 10:08:42 -06007467 SemaphoreScope wait_scope{GetQueueId(), SyncExecScope::MakeDst(queue_flags, wait_mask)};
7468 if (signal_scope.queue == wait_scope.queue) {
7469 // If signal queue == wait queue, signal is treated as a memory barrier with an access scope equal to the
7470 // valid accesses for the sync scope.
7471 SyncBarrier sem_barrier(signal_scope, wait_scope, SyncBarrier::AllAccess());
7472 const BatchBarrierOp sem_barrier_op(wait_scope.queue, sem_barrier);
7473 access_context_.ResolveFromContext(sem_barrier_op, signal_state->batch->access_context_);
John Zulaufe0757ba2022-06-10 16:51:45 -06007474 events_context_.ApplyBarrier(sem_barrier.src_exec_scope, sem_barrier.dst_exec_scope, ResourceUsageRecord::kMaxIndex);
John Zulaufecf4ac52022-06-06 10:08:42 -06007475 } else {
7476 ApplySemaphoreBarrierAction sem_op(signal_scope, wait_scope);
7477 access_context_.ResolveFromContext(sem_op, signal_state->batch->access_context_);
John Zulauf697c0e12022-04-19 16:31:12 -06007478 }
John Zulaufecf4ac52022-06-06 10:08:42 -06007479 // Cannot move from the signal state because it could be from the const global state, and C++ doesn't
7480 // enforce deep constness.
7481 return signal_state->batch;
John Zulauf697c0e12022-04-19 16:31:12 -06007482}
7483
7484// Accessor Traits to allow Submit and Submit2 constructors to call the same utilities
7485template <>
7486class QueueBatchContext::SubmitInfoAccessor<VkSubmitInfo> {
7487 public:
7488 SubmitInfoAccessor(const VkSubmitInfo &info) : info_(info) {}
7489 inline uint32_t WaitSemaphoreCount() const { return info_.waitSemaphoreCount; }
7490 inline VkSemaphore WaitSemaphore(uint32_t index) { return info_.pWaitSemaphores[index]; }
7491 inline VkPipelineStageFlags2 WaitDstMask(uint32_t index) { return info_.pWaitDstStageMask[index]; }
7492 inline uint32_t CommandBufferCount() const { return info_.commandBufferCount; }
7493 inline VkCommandBuffer CommandBuffer(uint32_t index) { return info_.pCommandBuffers[index]; }
7494
7495 private:
7496 const VkSubmitInfo &info_;
7497};
7498template <typename BatchInfo, typename Fn>
7499void QueueBatchContext::ForEachWaitSemaphore(const BatchInfo &batch_info, Fn &&func) {
7500 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7501 Accessor batch(batch_info);
7502 const uint32_t wait_count = batch.WaitSemaphoreCount();
7503 for (uint32_t i = 0; i < wait_count; ++i) {
7504 func(batch.WaitSemaphore(i), batch.WaitDstMask(i));
7505 }
7506}
7507
7508template <typename BatchInfo>
John Zulaufcb7e1672022-05-04 13:46:08 -06007509void QueueBatchContext::SetupAccessContext(const std::shared_ptr<const QueueBatchContext> &prev, const BatchInfo &batch_info,
7510 SignaledSemaphores &signaled) {
John Zulaufe0757ba2022-06-10 16:51:45 -06007511 // Copy in the event state from the previous batch (on this queue)
7512 if (prev) {
7513 events_context_.DeepCopy(prev->events_context_);
7514 }
7515
John Zulaufecf4ac52022-06-06 10:08:42 -06007516 // Import (resolve) the batches that are waited on, with the semaphore's effective barriers applied
7517 layer_data::unordered_set<std::shared_ptr<const QueueBatchContext>> batches_resolved;
7518 ForEachWaitSemaphore(batch_info, [this, &signaled, &batches_resolved](VkSemaphore sem, VkPipelineStageFlags2 wait_mask) {
7519 std::shared_ptr<QueueBatchContext> resolved = ResolveOneWaitSemaphore(sem, wait_mask, signaled);
7520 if (resolved) {
7521 batches_resolved.emplace(std::move(resolved));
7522 }
John Zulauf697c0e12022-04-19 16:31:12 -06007523 });
7524
John Zulaufecf4ac52022-06-06 10:08:42 -06007525 // If there are no semaphores to the previous batch, make sure a "submit order" non-barriered import is done
7526 if (prev && !layer_data::Contains(batches_resolved, prev)) {
7527 access_context_.ResolveFromContext(NoopBarrierAction(), prev->access_context_);
John Zulauf78cb2082022-04-20 16:37:48 -06007528 }
7529
John Zulauf697c0e12022-04-19 16:31:12 -06007530 // Gather async context information for hazard checks and conserve the QBC's for the async batches
John Zulaufecf4ac52022-06-06 10:08:42 -06007531 async_batches_ =
7532 sync_state_->GetQueueLastBatchSnapshot([&batches_resolved, &prev](const std::shared_ptr<const QueueBatchContext> &batch) {
7533 return (batch != prev) && !layer_data::Contains(batches_resolved, batch);
John Zulauf697c0e12022-04-19 16:31:12 -06007534 });
7535 for (const auto &async_batch : async_batches_) {
7536 access_context_.AddAsyncContext(async_batch->GetCurrentAccessContext());
7537 }
7538}
7539
7540template <typename BatchInfo>
7541void QueueBatchContext::SetupCommandBufferInfo(const BatchInfo &batch_info) {
7542 using Accessor = QueueBatchContext::SubmitInfoAccessor<BatchInfo>;
7543 Accessor batch(batch_info);
7544
7545 // Create the list of command buffers to submit
7546 const uint32_t cb_count = batch.CommandBufferCount();
7547 command_buffers_.reserve(cb_count);
7548 for (uint32_t index = 0; index < cb_count; ++index) {
7549 auto cb_context = sync_state_->GetAccessContextShared(batch.CommandBuffer(index));
7550 if (cb_context) {
7551 tag_range_.end += cb_context->GetTagLimit();
7552 command_buffers_.emplace_back(index, std::move(cb_context));
7553 }
7554 }
7555}
7556
7557// Look up the usage informaiton from the local or global logger
7558std::string QueueBatchContext::FormatUsage(ResourceUsageTag tag) const {
7559 const AccessLogger &use_logger = (logger_) ? *logger_ : sync_state_->global_access_log_;
7560 std::stringstream out;
7561 AccessLogger::AccessRecord access = use_logger[tag];
7562 if (access.IsValid()) {
7563 const AccessLogger::BatchRecord &batch = *access.batch;
7564 const ResourceUsageRecord &record = *access.record;
7565 // Queue and Batch information
7566 out << SyncNodeFormatter(*sync_state_, batch.queue->GetQueueState());
7567 out << ", submit: " << batch.submit_index << ", batch: " << batch.batch_index;
7568
7569 // Commandbuffer Usages Information
7570 out << record;
7571 out << SyncNodeFormatter(*sync_state_, record.cb_state);
7572 out << ", reset_no: " << std::to_string(record.reset_count);
7573 }
7574 return out.str();
7575}
7576
7577VkQueueFlags QueueBatchContext::GetQueueFlags() const { return queue_state_->GetQueueFlags(); }
7578
John Zulauf00119522022-05-23 19:07:42 -06007579QueueId QueueBatchContext::GetQueueId() const {
7580 QueueId id = queue_state_ ? queue_state_->GetQueueId() : QueueSyncState::kQueueIdInvalid;
7581 return id;
7582}
7583
John Zulauf697c0e12022-04-19 16:31:12 -06007584void QueueBatchContext::SetBatchLog(AccessLogger &logger, uint64_t submit_id, uint32_t batch_id) {
7585 // Need new global tags for all accesses... the Reserve updates a mutable atomic
7586 ResourceUsageRange global_tags = sync_state_->ReserveGlobalTagRange(GetTagRange().size());
7587 SetTagBias(global_tags.begin);
7588 // Add an access log for the batches range and point the batch at it.
7589 logger_ = &logger;
7590 batch_log_ = logger.AddBatch(queue_state_, submit_id, batch_id, global_tags);
7591}
7592
7593void QueueBatchContext::InsertRecordedAccessLogEntries(const CommandBufferAccessContext &submitted_cb) {
7594 assert(batch_log_); // Don't import command buffer contexts until you've set up the log for the batch context
7595 batch_log_->Append(submitted_cb.GetAccessLog());
7596}
7597
7598void QueueBatchContext::SetTagBias(ResourceUsageTag bias) {
7599 const auto size = tag_range_.size();
7600 tag_range_.begin = bias;
7601 tag_range_.end = bias + size;
7602 access_context_.SetStartTag(bias);
7603}
7604
John Zulauf1d5f9c12022-05-13 14:51:08 -06007605QueueBatchContext::QueueWaitWorm::QueueWaitWorm(QueueId queue, ResourceUsageTag tag) : predicate(queue) {}
7606
7607void QueueBatchContext::QueueWaitWorm::operator()(AccessAddressType address_type, ResourceAccessRangeMap::value_type &access) {
7608 bool erased = access.second.ApplyQueueTagWait(predicate);
7609 if (erased) {
7610 erase_list.emplace_back(address_type, access.first);
7611 } else {
7612 erase_all = false;
7613 }
7614}
7615
John Zulauf697c0e12022-04-19 16:31:12 -06007616AccessLogger::BatchLog *AccessLogger::AddBatch(const QueueSyncState *queue_state, uint64_t submit_id, uint32_t batch_id,
7617 const ResourceUsageRange &range) {
7618 const auto inserted = access_log_map_.insert(std::make_pair(range, BatchLog(BatchRecord(queue_state, submit_id, batch_id))));
7619 assert(inserted.second);
7620 return &inserted.first->second;
7621}
7622
7623void AccessLogger::MergeMove(AccessLogger &&child) {
7624 for (auto &range : child.access_log_map_) {
7625 BatchLog &child_batch = range.second;
7626 auto insert_pair = access_log_map_.insert(std::make_pair(range.first, BatchLog()));
7627 insert_pair.first->second = std::move(child_batch);
7628 assert(insert_pair.second);
7629 }
7630 child.Reset();
7631}
7632
7633void AccessLogger::Reset() {
7634 prev_ = nullptr;
7635 access_log_map_.clear();
7636}
7637
7638// Since we're updating the QueueSync state, this is Record phase and the access log needs to point to the global one
7639// Batch Contexts saved during signalling have their AccessLog reset when the pending signals are signalled.
7640// NOTE: By design, QueueBatchContexts that are neither last, nor referenced by a signal are abandoned as unowned, since
7641// the contexts Resolve all history from previous all contexts when created
7642void QueueSyncState::SetLastBatch(std::shared_ptr<QueueBatchContext> &&last) {
7643 last_batch_ = std::move(last);
7644 last_batch_->ResetAccessLog();
7645}
7646
7647// Note that function is const, but updates mutable submit_index to allow Validate to create correct tagging for command invocation
7648// scope state.
7649// Given that queue submits are supposed to be externally synchronized for the same queue, this should safe without being
7650// atomic... but as the ops are per submit, the performance cost is negible for the peace of mind.
7651uint64_t QueueSyncState::ReserveSubmitId() const { return submit_index_.fetch_add(1); }
7652
7653void AccessLogger::BatchLog::Append(const CommandExecutionContext::AccessLog &other) {
7654 log_.insert(log_.end(), other.cbegin(), other.cend());
7655 for (const auto &record : other) {
7656 assert(record.cb_state);
7657 cbs_referenced_.insert(record.cb_state->shared_from_this());
7658 }
7659}
7660
7661AccessLogger::AccessRecord AccessLogger::BatchLog::operator[](size_t index) const {
7662 assert(index < log_.size());
7663 return AccessRecord{&batch_, &log_[index]};
7664}
7665
7666AccessLogger::AccessRecord AccessLogger::operator[](ResourceUsageTag tag) const {
7667 AccessRecord access_record = {nullptr, nullptr};
7668
7669 auto found_range = access_log_map_.find(tag);
7670 if (found_range != access_log_map_.cend()) {
7671 const ResourceUsageTag bias = found_range->first.begin;
7672 assert(tag >= bias);
7673 access_record = found_range->second[tag - bias];
7674 } else if (prev_) {
7675 access_record = (*prev_)[tag];
7676 }
7677
7678 return access_record;
7679}
John Zulaufcb7e1672022-05-04 13:46:08 -06007680
John Zulaufecf4ac52022-06-06 10:08:42 -06007681// This is a const method, force the returned value to be const
7682std::shared_ptr<const SignaledSemaphores::Signal> SignaledSemaphores::GetPrev(VkSemaphore sem) const {
John Zulaufcb7e1672022-05-04 13:46:08 -06007683 std::shared_ptr<Signal> prev_state;
7684 if (prev_) {
7685 prev_state = GetMapped(prev_->signaled_, sem, [&prev_state]() { return prev_state; });
7686 }
7687 return prev_state;
7688}
John Zulaufecf4ac52022-06-06 10:08:42 -06007689
7690SignaledSemaphores::Signal::Signal(const std::shared_ptr<const SEMAPHORE_STATE> &sem_state_,
7691 const std::shared_ptr<QueueBatchContext> &batch_, const SyncExecScope &exec_scope_)
7692 : sem_state(sem_state_), batch(batch_), first_scope({batch->GetQueueId(), exec_scope_}) {
7693 // Illegal to create a signal from no batch or an invalid semaphore... caller must assure validity
7694 assert(batch);
7695 assert(sem_state);
7696}